diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..dfe0770
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 0000000..6f48231
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,2 @@
+github: Domi04151309
+custom: ['https://www.paypal.com/donate/?hosted_button_id=487FTCX52P9WA']
diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md
new file mode 100644
index 0000000..5e21670
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug-report.md
@@ -0,0 +1,31 @@
+---
+name: Bug Report
+about: Create a report to help improving the app
+title: "[Bug Report] Your Title"
+labels: bug
+assignees: ''
+
+---
+
+**Description**
+
+_A clear and concise description of what the bug is.
+Please add steps to reproduce the behavior._
+
+
+ Screenshots
+
+ _Add screenshots here to describe the problem._
+
+
+
+ Logs
+
+ _Add a detailed stack trace / crash log here if applicable_
+
+
+**Additional information**
+
+ - Android version: _System Settings > About > Android version (varies per device)_
+ - Home App version: _Settings > About > Version_
+ - Installation source: _Google Play / F-Drod / Own Build_
diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md
new file mode 100644
index 0000000..26704ff
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature-request.md
@@ -0,0 +1,18 @@
+---
+name: Feature Request
+about: Suggest an idea for this project
+title: "[Feature Request] Your Title"
+labels: enhancement
+assignees: ''
+
+---
+
+**Describe the solution you'd like**
+
+_A clear and concise description of what you want to happen._
+
+
+ Additional context
+
+ _Add any other context or screenshots about the feature request here._
+
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..bca3767
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,72 @@
+name: Continuous Integration
+
+on:
+ push:
+ branches:
+ - main
+ pull_request:
+ branches:
+ - main
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ ktlint:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@v4
+ - name: Install
+ run: |
+ curl -sSLO https://github.com/pinterest/ktlint/releases/download/1.0.1/ktlint
+ chmod a+x ktlint
+ sudo mv ktlint /usr/local/bin/
+ - name: Run
+ run: ktlint --reporter sarif -l none > ktlint.sarif
+ - name: Upload SARIF
+ uses: github/codeql-action/upload-sarif@v3
+ if: success() || failure()
+ with:
+ sarif_file: ktlint.sarif
+ detekt:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@v4
+ - name: Setup Java
+ uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: 17
+ - name: Setup Gradle
+ uses: gradle/actions/setup-gradle@v3
+ - name: Run
+ run: |
+ chmod +x gradlew
+ ./gradlew detekt
+ - name: Upload SARIF
+ uses: github/codeql-action/upload-sarif@v3
+ if: success() || failure()
+ with:
+ sarif_file: app/build/reports/detekt/detekt.sarif
+ - name: Job Summary
+ if: success() || failure()
+ run: cat ./app/build/reports/detekt/detekt.md >> $GITHUB_STEP_SUMMARY
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+ - name: Setup Java
+ uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: 17
+ - name: Setup Gradle
+ uses: gradle/actions/setup-gradle@v3
+ - name: Run
+ run: |
+ chmod +x gradlew
+ ./gradlew build
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5d18272
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,89 @@
+# Built application files
+*.apk
+*.aar
+*.ap_
+*.aab
+
+# Files for the ART/Dalvik VM
+*.dex
+
+# Java class files
+*.class
+
+# Generated files
+bin/
+gen/
+out/
+# Uncomment the following line in case you need and you don't have the release build type files in your app
+# release/
+
+# Gradle files
+.gradle/
+build/
+
+# Local configuration file (sdk path, etc)
+local.properties
+
+# Proguard folder generated by Eclipse
+proguard/
+
+# Log Files
+*.log
+
+# Android Studio Navigation editor temp files
+.navigation/
+
+# Android Studio captures folder
+captures/
+
+# IntelliJ
+*.iml
+.idea/workspace.xml
+.idea/tasks.xml
+.idea/gradle.xml
+.idea/assetWizardSettings.xml
+.idea/dictionaries
+.idea/libraries
+.idea/jarRepositories.xml
+# Android Studio 3 in .gitignore file.
+.idea/caches
+.idea/modules.xml
+# Comment next line if keeping position of elements in Navigation Editor is relevant for you
+.idea/navEditor.xml
+
+# Keystore files
+# Uncomment the following lines if you do not want to check your keystore files in.
+#*.jks
+#*.keystore
+
+# External native build folder generated in Android Studio 2.2 and later
+.externalNativeBuild
+.cxx/
+
+# Google Services (e.g. APIs or Firebase)
+# google-services.json
+
+# Freeline
+freeline.py
+freeline/
+freeline_project_description.json
+
+# fastlane
+fastlane/report.xml
+fastlane/Preview.html
+fastlane/screenshots
+fastlane/test_output
+fastlane/readme.md
+
+# Version control
+vcs.xml
+
+# lint
+lint/intermediates/
+lint/generated/
+lint/outputs/
+lint/tmp/
+# lint/reports/
+
+# Android Profiling
+*.hprof
diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml
new file mode 100644
index 0000000..4a53bee
--- /dev/null
+++ b/.idea/AndroidProjectSystem.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml
new file mode 100644
index 0000000..7643783
--- /dev/null
+++ b/.idea/codeStyles/Project.xml
@@ -0,0 +1,123 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ xmlns:android
+
+ ^$
+
+
+
+
+
+
+
+
+ xmlns:.*
+
+ ^$
+
+
+ BY_NAME
+
+
+
+
+
+
+ .*:id
+
+ http://schemas.android.com/apk/res/android
+
+
+
+
+
+
+
+
+ .*:name
+
+ http://schemas.android.com/apk/res/android
+
+
+
+
+
+
+
+
+ name
+
+ ^$
+
+
+
+
+
+
+
+
+ style
+
+ ^$
+
+
+
+
+
+
+
+
+ .*
+
+ ^$
+
+
+ BY_NAME
+
+
+
+
+
+
+ .*
+
+ http://schemas.android.com/apk/res/android
+
+
+ ANDROID_ATTRIBUTE_ORDER
+
+
+
+
+
+
+ .*
+
+ .*
+
+
+ BY_NAME
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml
new file mode 100644
index 0000000..79ee123
--- /dev/null
+++ b/.idea/codeStyles/codeStyleConfig.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 0000000..b86273d
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/deploymentTargetDropDown.xml b/.idea/deploymentTargetDropDown.xml
new file mode 100644
index 0000000..0c0c338
--- /dev/null
+++ b/.idea/deploymentTargetDropDown.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml
new file mode 100644
index 0000000..b268ef3
--- /dev/null
+++ b/.idea/deploymentTargetSelector.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
new file mode 100644
index 0000000..15a15b2
--- /dev/null
+++ b/.idea/encodings.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/Strict.xml b/.idea/inspectionProfiles/Strict.xml
new file mode 100644
index 0000000..7532a01
--- /dev/null
+++ b/.idea/inspectionProfiles/Strict.xml
@@ -0,0 +1,1006 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..ce11e3f
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml
new file mode 100644
index 0000000..c22b6fa
--- /dev/null
+++ b/.idea/kotlinc.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/migrations.xml b/.idea/migrations.xml
new file mode 100644
index 0000000..f8051a6
--- /dev/null
+++ b/.idea/migrations.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..5cc7043
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,58 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml
new file mode 100644
index 0000000..16660f1
--- /dev/null
+++ b/.idea/runConfigurations.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..61d1860
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+ .
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
\ No newline at end of file
diff --git a/README.md b/README.md
index 9010d67..758fe4b 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,56 @@
-# home-app
+
+# Home App for Android™
+HomeApp is a small and easy to use smart home app with a simple framework. The goal of this application is to make remote execution of predefined features as easy and user-friendly as possible to help you get started with smart home technology.
-Home-Lab Integration for Android
\ No newline at end of file
+
+
+
+
+## Donate
+Support the development by donating.
+
+
+
+
+
+## Supported devices
+Home App natively supports the following devices:
+
+- [Philips Hue Bridge](https://github.com/Domi04151309/HomeApp/wiki/Hue-API-%28v1%29)
+- [Shelly](https://github.com/Domi04151309/HomeApp/wiki/Shelly) Gen 1 devices
+- [Shelly](https://github.com/Domi04151309/HomeApp/wiki/Shelly) Gen 2 devices
+- Devices using [ESP Easy](https://github.com/Domi04151309/HomeApp/wiki/ESP-Easy)
+- Devices using [Tasmota](https://github.com/Domi04151309/HomeApp/wiki/Tasmota)
+- Devices using the [Node-RED dashboard](https://github.com/Domi04151309/HomeApp/wiki/Node-RED-Dashboard)
+- Devices using the [SimpleHome API](https://github.com/Domi04151309/HomeApp/wiki/SimpleHome-API)
+- Devices with a [web interface](https://github.com/Domi04151309/HomeApp/wiki/Websites)
+
+## How it works
+Communication between the devices uses HTTP requests and JSON strings. After the commanding device has send a HTTP request to the smart home device, the smart home device sends back a JSON string containing the information the app needs.
+
+This app is especially useful if you are using microcontrollers or other small devices such as the Raspberry Pi for smart home automation.
+
+## Previews
+
+
+Android, Google Play and the Google Play logo are trademarks of Google LLC.
+
+## Legal Notice
+Copyright (C) 2020 Domi04151309
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
+
+Impressum
diff --git a/app/.gitignore b/app/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/app/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
new file mode 100644
index 0000000..e1db910
--- /dev/null
+++ b/app/build.gradle.kts
@@ -0,0 +1,103 @@
+import com.android.build.gradle.internal.tasks.factory.dependsOn
+
+private val readAndUnderstoodLicense = false
+
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+ id("io.gitlab.arturbosch.detekt")
+}
+
+android {
+ namespace = "io.github.domi04151309.home"
+ compileSdk = 34
+
+ defaultConfig {
+ applicationId = "io.github.domi04151309.home"
+ minSdk = 23
+ //noinspection EditedTargetSdkVersion
+ targetSdk = 34
+ versionCode = 1120
+ versionName = "1.12.0"
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ }
+
+ buildTypes {
+ debug {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro",
+ )
+ }
+ release {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro",
+ )
+ }
+ }
+ testOptions {
+ unitTests.isIncludeAndroidResources = true
+ }
+ buildFeatures {
+ buildConfig = true
+ }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+ detekt {
+ config.setFrom(file("detekt-config.yml"))
+ buildUponDefaultConfig = true
+ basePath = rootProject.projectDir.absolutePath
+ }
+ lint {
+ disable += "MissingTranslation"
+ }
+ project.tasks.preBuild.dependsOn("license")
+}
+
+tasks.register("license") {
+ doFirst {
+ val data =
+ file("./src/main/res/xml/pref_about.xml")
+ .readText()
+ .contains("app:key=\"license\"")
+ if (!data) {
+ throw Exception(
+ "Please note that removing the license from the about page is not allowed if you " +
+ "plan to publish your modified version of this app. " +
+ "Please read the project's LICENSE.",
+ )
+ }
+ if (!(
+ android.defaultConfig.applicationId?.contains("domi04151309") == true ||
+ readAndUnderstoodLicense
+ )
+ ) {
+ throw Exception(
+ "Please make sure you have read and understood the LICENSE!",
+ )
+ }
+ }
+}
+
+dependencies {
+ implementation("androidx.appcompat:appcompat:1.7.1")
+ implementation("com.google.android.material:material:1.12.0")
+ implementation("androidx.preference:preference-ktx:1.2.1")
+ implementation("androidx.annotation:annotation:1.9.1")
+ implementation("com.android.volley:volley:1.2.1")
+ implementation("androidx.security:security-crypto-ktx:1.1.0-beta01")
+ implementation("com.github.skydoves:colorpickerview:2.3.0")
+
+ testImplementation("junit:junit:4.13.2")
+ testImplementation("org.robolectric:robolectric:4.14.1")
+}
diff --git a/app/detekt-config.yml b/app/detekt-config.yml
new file mode 100644
index 0000000..af903e4
--- /dev/null
+++ b/app/detekt-config.yml
@@ -0,0 +1,784 @@
+build:
+ maxIssues: 0
+ excludeCorrectable: true
+ weights:
+ # complexity: 2
+ # LongParameterList: 1
+ # style: 1
+ # comments: 1
+
+config:
+ validation: true
+ warningsAsErrors: true
+ checkExhaustiveness: true
+ # when writing own rules with new properties, exclude the property path e.g.: 'my_rule_set,.*>.*>[my_property]'
+ excludes: ''
+
+processors:
+ active: true
+ exclude:
+ - 'DetektProgressListener'
+ # - 'KtFileCountProcessor'
+ # - 'PackageCountProcessor'
+ # - 'ClassCountProcessor'
+ # - 'FunctionCountProcessor'
+ # - 'PropertyCountProcessor'
+ # - 'ProjectComplexityProcessor'
+ # - 'ProjectCognitiveComplexityProcessor'
+ # - 'ProjectLLOCProcessor'
+ # - 'ProjectCLOCProcessor'
+ # - 'ProjectLOCProcessor'
+ # - 'ProjectSLOCProcessor'
+ # - 'LicenseHeaderLoaderExtension'
+
+console-reports:
+ active: true
+ exclude:
+ - 'ProjectStatisticsReport'
+ - 'ComplexityReport'
+ - 'NotificationReport'
+ - 'FindingsReport'
+ - 'FileBasedFindingsReport'
+ # - 'LiteFindingsReport'
+
+output-reports:
+ active: true
+ exclude:
+ # - 'TxtOutputReport'
+ # - 'XmlOutputReport'
+ # - 'HtmlOutputReport'
+ # - 'MdOutputReport'
+ # - 'SarifOutputReport'
+
+comments:
+ active: true
+ AbsentOrWrongFileLicense:
+ active: false
+ licenseTemplateFile: 'license.template'
+ licenseTemplateIsRegex: true
+ CommentOverPrivateFunction:
+ active: true
+ CommentOverPrivateProperty:
+ active: true
+ DeprecatedBlockTag:
+ active: true
+ EndOfSentenceFormat:
+ active: true
+ endOfSentenceFormat: '([.?!][ \t\n\r\f<])|([.?!:]$)'
+ KDocReferencesNonPublicProperty:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ OutdatedDocumentation:
+ active: true
+ matchTypeParameters: true
+ matchDeclarationsOrder: true
+ allowParamOnConstructorProperties: true
+ UndocumentedPublicClass:
+ active: false
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ searchInNestedClass: true
+ searchInInnerClass: true
+ searchInInnerObject: true
+ searchInInnerInterface: true
+ searchInProtectedClass: true
+ UndocumentedPublicFunction:
+ active: false
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ searchProtectedFunction: true
+ UndocumentedPublicProperty:
+ active: false
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ searchProtectedProperty: true
+
+complexity:
+ active: true
+ CognitiveComplexMethod:
+ active: true
+ threshold: 15
+ ComplexCondition:
+ active: true
+ threshold: 4
+ ComplexInterface:
+ active: true
+ threshold: 10
+ includeStaticDeclarations: true
+ includePrivateDeclarations: true
+ ignoreOverloaded: true
+ CyclomaticComplexMethod:
+ active: true
+ threshold: 15
+ ignoreSingleWhenExpression: true
+ ignoreSimpleWhenEntries: true
+ ignoreNestingFunctions: true
+ nestingFunctions:
+ - 'also'
+ - 'apply'
+ - 'forEach'
+ - 'isNotNull'
+ - 'ifNull'
+ - 'let'
+ - 'run'
+ - 'use'
+ - 'with'
+ LabeledExpression:
+ active: true
+ ignoredLabels: []
+ LargeClass:
+ active: true
+ threshold: 600
+ LongMethod:
+ active: true
+ threshold: 60
+ LongParameterList:
+ active: true
+ functionThreshold: 6
+ constructorThreshold: 7
+ ignoreDefaultParameters: true
+ ignoreDataClasses: true
+ ignoreAnnotatedParameter: []
+ MethodOverloading:
+ active: true
+ threshold: 6
+ NamedArguments:
+ active: true
+ threshold: 3
+ ignoreArgumentsMatchingNames: true
+ NestedBlockDepth:
+ active: true
+ threshold: 4
+ NestedScopeFunctions:
+ active: true
+ threshold: 1
+ functions:
+ - 'kotlin.apply'
+ - 'kotlin.run'
+ - 'kotlin.with'
+ - 'kotlin.let'
+ - 'kotlin.also'
+ ReplaceSafeCallChainWithRun:
+ active: true
+ StringLiteralDuplication:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ threshold: 3
+ ignoreAnnotation: true
+ excludeStringsWithLessThan5Characters: true
+ ignoreStringsRegex: '$^'
+ TooManyFunctions:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ thresholdInFiles: 11
+ thresholdInClasses: 11
+ thresholdInInterfaces: 11
+ thresholdInObjects: 11
+ thresholdInEnums: 11
+ ignoreDeprecated: true
+ ignorePrivate: true
+ ignoreOverridden: true
+
+coroutines:
+ active: true
+ GlobalCoroutineUsage:
+ active: true
+ InjectDispatcher:
+ active: true
+ dispatcherNames:
+ - 'IO'
+ - 'Default'
+ - 'Unconfined'
+ RedundantSuspendModifier:
+ active: true
+ SleepInsteadOfDelay:
+ active: true
+ SuspendFunSwallowedCancellation:
+ active: true
+ SuspendFunWithCoroutineScopeReceiver:
+ active: true
+ SuspendFunWithFlowReturnType:
+ active: true
+
+empty-blocks:
+ active: true
+ EmptyCatchBlock:
+ active: true
+ allowedExceptionNameRegex: '_|(ignore|expected).*'
+ EmptyClassBlock:
+ active: true
+ EmptyDefaultConstructor:
+ active: true
+ EmptyDoWhileBlock:
+ active: true
+ EmptyElseBlock:
+ active: true
+ EmptyFinallyBlock:
+ active: true
+ EmptyForBlock:
+ active: true
+ EmptyFunctionBlock:
+ active: true
+ ignoreOverridden: true
+ EmptyIfBlock:
+ active: true
+ EmptyInitBlock:
+ active: true
+ EmptyKtFile:
+ active: true
+ EmptySecondaryConstructor:
+ active: true
+ EmptyTryBlock:
+ active: true
+ EmptyWhenBlock:
+ active: true
+ EmptyWhileBlock:
+ active: true
+
+exceptions:
+ active: true
+ ExceptionRaisedInUnexpectedLocation:
+ active: true
+ methodNames:
+ - 'equals'
+ - 'finalize'
+ - 'hashCode'
+ - 'toString'
+ InstanceOfCheckForException:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ NotImplementedDeclaration:
+ active: true
+ ObjectExtendsThrowable:
+ active: true
+ PrintStackTrace:
+ active: true
+ RethrowCaughtException:
+ active: true
+ ReturnFromFinally:
+ active: true
+ ignoreLabeled: true
+ SwallowedException:
+ active: true
+ ignoredExceptionTypes:
+ - 'InterruptedException'
+ - 'MalformedURLException'
+ - 'NumberFormatException'
+ - 'ParseException'
+ allowedExceptionNameRegex: '_|(ignore|expected).*'
+ ThrowingExceptionFromFinally:
+ active: true
+ ThrowingExceptionInMain:
+ active: true
+ ThrowingExceptionsWithoutMessageOrCause:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ exceptions:
+ - 'ArrayIndexOutOfBoundsException'
+ - 'Exception'
+ - 'IllegalArgumentException'
+ - 'IllegalMonitorStateException'
+ - 'IllegalStateException'
+ - 'IndexOutOfBoundsException'
+ - 'NullPointerException'
+ - 'RuntimeException'
+ - 'Throwable'
+ ThrowingNewInstanceOfSameException:
+ active: true
+ TooGenericExceptionCaught:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ exceptionNames:
+ - 'ArrayIndexOutOfBoundsException'
+ - 'Error'
+ - 'Exception'
+ - 'IllegalMonitorStateException'
+ - 'IndexOutOfBoundsException'
+ - 'NullPointerException'
+ - 'RuntimeException'
+ - 'Throwable'
+ allowedExceptionNameRegex: '_|(ignore|expected).*'
+ TooGenericExceptionThrown:
+ active: true
+ exceptionNames:
+ - 'Error'
+ - 'Exception'
+ - 'RuntimeException'
+ - 'Throwable'
+
+naming:
+ active: true
+ BooleanPropertyNaming:
+ active: true
+ allowedPattern: '^(is|has|are)'
+ ClassNaming:
+ active: true
+ classPattern: '[A-Z][a-zA-Z0-9]*'
+ ConstructorParameterNaming:
+ active: true
+ parameterPattern: '[a-z][A-Za-z0-9]*'
+ privateParameterPattern: '[a-z][A-Za-z0-9]*'
+ excludeClassPattern: '$^'
+ EnumNaming:
+ active: true
+ enumEntryPattern: '[A-Z][_a-zA-Z0-9]*'
+ ForbiddenClassName:
+ active: true
+ forbiddenName: []
+ FunctionMaxLength:
+ active: true
+ maximumFunctionNameLength: 30
+ FunctionMinLength:
+ active: true
+ minimumFunctionNameLength: 3
+ FunctionNaming:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ functionPattern: '[a-z][a-zA-Z0-9]*'
+ excludeClassPattern: '$^'
+ FunctionParameterNaming:
+ active: true
+ parameterPattern: '[a-z][A-Za-z0-9]*'
+ excludeClassPattern: '$^'
+ InvalidPackageDeclaration:
+ active: true
+ rootPackage: ''
+ requireRootInDeclaration: false
+ LambdaParameterNaming:
+ active: true
+ parameterPattern: '[a-z][A-Za-z0-9]*|_'
+ MatchingDeclarationName:
+ active: true
+ mustBeFirst: true
+ MemberNameEqualsClassName:
+ active: true
+ ignoreOverridden: true
+ NoNameShadowing:
+ active: true
+ NonBooleanPropertyPrefixedWithIs:
+ active: true
+ ObjectPropertyNaming:
+ active: true
+ constantPattern: '[A-Za-z][_A-Za-z0-9]*'
+ propertyPattern: '[A-Za-z][_A-Za-z0-9]*'
+ privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*'
+ PackageNaming:
+ active: true
+ packagePattern: '[a-z]+(\.[a-z][A-Za-z0-9]*)*'
+ TopLevelPropertyNaming:
+ active: true
+ constantPattern: '[A-Z][_A-Z0-9]*'
+ propertyPattern: '[A-Za-z][_A-Za-z0-9]*'
+ privatePropertyPattern: '_?[A-Za-z][_A-Za-z0-9]*'
+ VariableMaxLength:
+ active: true
+ maximumVariableNameLength: 64
+ VariableMinLength:
+ active: true
+ minimumVariableNameLength: 1
+ VariableNaming:
+ active: true
+ variablePattern: '[a-z][A-Za-z0-9]*'
+ privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*'
+ excludeClassPattern: '$^'
+
+performance:
+ active: true
+ ArrayPrimitive:
+ active: true
+ CouldBeSequence:
+ active: true
+ threshold: 3
+ ForEachOnRange:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ SpreadOperator:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ UnnecessaryPartOfBinaryExpression:
+ active: true
+ UnnecessaryTemporaryInstantiation:
+ active: true
+
+potential-bugs:
+ active: true
+ AvoidReferentialEquality:
+ active: true
+ forbiddenTypePatterns:
+ - 'kotlin.String'
+ CastNullableToNonNullableType:
+ active: true
+ CastToNullableType:
+ active: true
+ Deprecation:
+ active: true
+ DontDowncastCollectionTypes:
+ active: true
+ DoubleMutabilityForCollection:
+ active: true
+ mutableTypes:
+ - 'kotlin.collections.MutableList'
+ - 'kotlin.collections.MutableMap'
+ - 'kotlin.collections.MutableSet'
+ - 'java.util.ArrayList'
+ - 'java.util.LinkedHashSet'
+ - 'java.util.HashSet'
+ - 'java.util.LinkedHashMap'
+ - 'java.util.HashMap'
+ ElseCaseInsteadOfExhaustiveWhen:
+ active: true
+ ignoredSubjectTypes: []
+ EqualsAlwaysReturnsTrueOrFalse:
+ active: true
+ EqualsWithHashCodeExist:
+ active: true
+ ExitOutsideMain:
+ active: true
+ ExplicitGarbageCollectionCall:
+ active: true
+ HasPlatformType:
+ active: true
+ IgnoredReturnValue:
+ active: true
+ restrictToConfig: true
+ returnValueAnnotations:
+ - 'CheckResult'
+ - '*.CheckResult'
+ - 'CheckReturnValue'
+ - '*.CheckReturnValue'
+ ignoreReturnValueAnnotations:
+ - 'CanIgnoreReturnValue'
+ - '*.CanIgnoreReturnValue'
+ returnValueTypes:
+ - 'kotlin.sequences.Sequence'
+ - 'kotlinx.coroutines.flow.*Flow'
+ - 'java.util.stream.*Stream'
+ ignoreFunctionCall: []
+ ImplicitDefaultLocale:
+ active: true
+ ImplicitUnitReturnType:
+ active: true
+ allowExplicitReturnType: true
+ InvalidRange:
+ active: true
+ IteratorHasNextCallsNextMethod:
+ active: true
+ IteratorNotThrowingNoSuchElementException:
+ active: true
+ LateinitUsage:
+ active: false
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ ignoreOnClassesPattern: ''
+ MapGetWithNotNullAssertionOperator:
+ active: true
+ MissingPackageDeclaration:
+ active: true
+ excludes: ['**/*.kts']
+ NullCheckOnMutableProperty:
+ active: true
+ NullableToStringCall:
+ active: true
+ PropertyUsedBeforeDeclaration:
+ active: true
+ UnconditionalJumpStatementInLoop:
+ active: true
+ UnnecessaryNotNullCheck:
+ active: true
+ UnnecessaryNotNullOperator:
+ active: true
+ UnnecessarySafeCall:
+ active: true
+ UnreachableCatchBlock:
+ active: true
+ UnreachableCode:
+ active: true
+ UnsafeCallOnNullableType:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**']
+ UnsafeCast:
+ active: true
+ UnusedUnaryOperator:
+ active: true
+ UselessPostfixExpression:
+ active: true
+ WrongEqualsTypeParameter:
+ active: true
+
+style:
+ active: true
+ AlsoCouldBeApply:
+ active: true
+ BracesOnIfStatements:
+ active: true
+ singleLine: 'never'
+ multiLine: 'always'
+ BracesOnWhenStatements:
+ active: true
+ singleLine: 'necessary'
+ multiLine: 'consistent'
+ CanBeNonNullable:
+ active: true
+ CascadingCallWrapping:
+ active: true
+ includeElvis: true
+ ClassOrdering:
+ active: true
+ CollapsibleIfStatements:
+ active: true
+ DataClassContainsFunctions:
+ active: true
+ conversionFunctionPrefix:
+ - 'to'
+ allowOperators: true
+ DataClassShouldBeImmutable:
+ active: true
+ DestructuringDeclarationWithTooManyEntries:
+ active: true
+ maxDestructuringEntries: 3
+ DoubleNegativeLambda:
+ active: true
+ negativeFunctions:
+ - reason: 'Use `takeIf` instead.'
+ value: 'takeUnless'
+ - reason: 'Use `all` instead.'
+ value: 'none'
+ negativeFunctionNameParts:
+ - 'not'
+ - 'non'
+ EqualsNullCall:
+ active: true
+ EqualsOnSignatureLine:
+ active: true
+ ExplicitCollectionElementAccessMethod:
+ active: true
+ ExplicitItLambdaParameter:
+ active: true
+ ExpressionBodySyntax:
+ active: true
+ includeLineWrapping: true
+ ForbiddenAnnotation:
+ active: true
+ annotations:
+ - reason: 'it is a java annotation. Use `Suppress` instead.'
+ value: 'java.lang.SuppressWarnings'
+ - reason: 'it is a java annotation. Use `kotlin.Deprecated` instead.'
+ value: 'java.lang.Deprecated'
+ - reason: 'it is a java annotation. Use `kotlin.annotation.MustBeDocumented` instead.'
+ value: 'java.lang.annotation.Documented'
+ - reason: 'it is a java annotation. Use `kotlin.annotation.Target` instead.'
+ value: 'java.lang.annotation.Target'
+ - reason: 'it is a java annotation. Use `kotlin.annotation.Retention` instead.'
+ value: 'java.lang.annotation.Retention'
+ - reason: 'it is a java annotation. Use `kotlin.annotation.Repeatable` instead.'
+ value: 'java.lang.annotation.Repeatable'
+ - reason: 'Kotlin does not support @Inherited annotation, see https://youtrack.jetbrains.com/issue/KT-22265'
+ value: 'java.lang.annotation.Inherited'
+ ForbiddenComment:
+ active: true
+ comments:
+ - reason: 'Forbidden FIXME todo marker in comment, please fix the problem.'
+ value: 'FIXME:'
+ - reason: 'Forbidden STOPSHIP todo marker in comment, please address the problem before shipping the code.'
+ value: 'STOPSHIP:'
+ - reason: 'Forbidden TODO todo marker in comment, please do the changes.'
+ value: 'TODO:'
+ allowedPatterns: ''
+ ForbiddenImport:
+ active: true
+ imports: []
+ forbiddenPatterns: ''
+ ForbiddenMethodCall:
+ active: true
+ methods:
+ - reason: 'print does not allow you to configure the output stream. Use a logger instead.'
+ value: 'kotlin.io.print'
+ - reason: 'println does not allow you to configure the output stream. Use a logger instead.'
+ value: 'kotlin.io.println'
+ ForbiddenSuppress:
+ active: true
+ rules: []
+ ForbiddenVoid:
+ active: true
+ ignoreOverridden: true
+ ignoreUsageInGenerics: true
+ FunctionOnlyReturningConstant:
+ active: true
+ ignoreOverridableFunction: true
+ ignoreActualFunction: true
+ excludedFunctions: []
+ LoopWithTooManyJumpStatements:
+ active: true
+ maxJumpCount: 1
+ MagicNumber:
+ active: true
+ excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**', '**/*.kts']
+ ignoreNumbers:
+ - '-1'
+ - '0'
+ - '1'
+ - '2'
+ ignoreHashCodeFunction: true
+ ignorePropertyDeclaration: true
+ ignoreLocalVariableDeclaration: true
+ ignoreConstantDeclaration: true
+ ignoreCompanionObjectPropertyDeclaration: true
+ ignoreAnnotation: true
+ ignoreNamedArgument: true
+ ignoreEnums: true
+ ignoreRanges: true
+ ignoreExtensionFunctions: true
+ MandatoryBracesLoops:
+ active: true
+ MaxChainedCallsOnSameLine:
+ active: true
+ maxChainedCalls: 5
+ MaxLineLength:
+ active: true
+ maxLineLength: 120
+ excludePackageStatements: true
+ excludeImportStatements: true
+ excludeCommentStatements: true
+ excludeRawStrings: true
+ MayBeConst:
+ active: true
+ ModifierOrder:
+ active: true
+ MultilineLambdaItParameter:
+ active: true
+ MultilineRawStringIndentation:
+ active: false
+ indentSize: 4
+ trimmingMethods:
+ - 'trimIndent'
+ - 'trimMargin'
+ NestedClassesVisibility:
+ active: true
+ NewLineAtEndOfFile:
+ active: true
+ NoTabs:
+ active: true
+ NullableBooleanCheck:
+ active: true
+ ObjectLiteralToLambda:
+ active: true
+ OptionalAbstractKeyword:
+ active: true
+ OptionalUnit:
+ active: true
+ PreferToOverPairSyntax:
+ active: true
+ ProtectedMemberInFinalClass:
+ active: true
+ RedundantExplicitType:
+ active: true
+ RedundantHigherOrderMapUsage:
+ active: true
+ RedundantVisibilityModifierRule:
+ active: true
+ ReturnCount:
+ active: true
+ max: 2
+ excludedFunctions:
+ - 'equals'
+ excludeLabeled: true
+ excludeReturnFromLambda: true
+ excludeGuardClauses: true
+ SafeCast:
+ active: true
+ SerialVersionUIDInSerializableClass:
+ active: true
+ SpacingBetweenPackageAndImports:
+ active: true
+ StringShouldBeRawString:
+ active: true
+ maxEscapedCharacterCount: 2
+ ignoredCharacters: []
+ ThrowsCount:
+ active: true
+ max: 2
+ excludeGuardClauses: true
+ TrailingWhitespace:
+ active: true
+ TrimMultilineRawString:
+ active: false
+ trimmingMethods:
+ - 'trimIndent'
+ - 'trimMargin'
+ UnderscoresInNumericLiterals:
+ active: true
+ acceptableLength: 4
+ allowNonStandardGrouping: true
+ UnnecessaryAbstractClass:
+ active: true
+ UnnecessaryAnnotationUseSiteTarget:
+ active: true
+ UnnecessaryApply:
+ active: true
+ UnnecessaryBackticks:
+ active: true
+ UnnecessaryBracesAroundTrailingLambda:
+ active: true
+ UnnecessaryFilter:
+ active: true
+ UnnecessaryInheritance:
+ active: true
+ UnnecessaryInnerClass:
+ active: true
+ UnnecessaryLet:
+ active: true
+ UnnecessaryParentheses:
+ active: true
+ allowForUnclearPrecedence: true
+ UntilInsteadOfRangeTo:
+ active: true
+ UnusedImports:
+ active: true
+ UnusedParameter:
+ active: true
+ allowedNames: 'ignored|expected'
+ UnusedPrivateClass:
+ active: true
+ UnusedPrivateMember:
+ active: true
+ allowedNames: ''
+ UnusedPrivateProperty:
+ active: true
+ allowedNames: '_|ignored|expected|serialVersionUID'
+ UseAnyOrNoneInsteadOfFind:
+ active: true
+ UseArrayLiteralsInAnnotations:
+ active: true
+ UseCheckNotNull:
+ active: true
+ UseCheckOrError:
+ active: true
+ UseDataClass:
+ active: true
+ allowVars: true
+ UseEmptyCounterpart:
+ active: true
+ UseIfEmptyOrIfBlank:
+ active: true
+ UseIfInsteadOfWhen:
+ active: true
+ ignoreWhenContainingVariableDeclaration: true
+ UseIsNullOrEmpty:
+ active: true
+ UseLet:
+ active: true
+ UseOrEmpty:
+ active: true
+ UseRequire:
+ active: true
+ UseRequireNotNull:
+ active: true
+ UseSumOfInsteadOfFlatMapSize:
+ active: true
+ UselessCallOnNotNull:
+ active: true
+ UtilityClassWithPublicConstructor:
+ active: true
+ VarCouldBeVal:
+ active: true
+ ignoreLateinitVar: true
+ WildcardImport:
+ active: true
+ excludeImports:
+ - 'java.util.*'
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
new file mode 100644
index 0000000..2f45576
--- /dev/null
+++ b/app/proguard-rules.pro
@@ -0,0 +1,27 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+-keepattributes SourceFile,LineNumberTable
+-dontobfuscate
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
+
+# This is generated automatically by the Android Gradle plugin.
+-dontwarn com.google.errorprone.annotations.Immutable
+-dontwarn javax.annotation.concurrent.GuardedBy
+-dontwarn javax.annotation.Nullable
\ No newline at end of file
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..230adaa
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,157 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/ic_launcher-playstore.png b/app/src/main/ic_launcher-playstore.png
new file mode 100644
index 0000000..183b8ed
Binary files /dev/null and b/app/src/main/ic_launcher-playstore.png differ
diff --git a/app/src/main/java/com/rine/upnpdiscovery/UPnPDevice.kt b/app/src/main/java/com/rine/upnpdiscovery/UPnPDevice.kt
new file mode 100644
index 0000000..2ce6696
--- /dev/null
+++ b/app/src/main/java/com/rine/upnpdiscovery/UPnPDevice.kt
@@ -0,0 +1,110 @@
+package com.rine.upnpdiscovery
+
+import android.util.Log
+import org.xmlpull.v1.XmlPullParser
+import org.xmlpull.v1.XmlPullParserException
+import org.xmlpull.v1.XmlPullParserFactory
+import java.io.ByteArrayInputStream
+
+class UPnPDevice internal constructor(val hostAddress: String, header: String) {
+ internal val location: String
+ val server: String
+
+ // XML content
+ private var descriptionXML: String = ""
+
+ // From description XML
+ var friendlyName: String = ""
+ private var deviceType: String = ""
+ private var presentationURL: String = ""
+ private var serialNumber: String = ""
+ private var modelName: String = ""
+ private var modelNumber: String = ""
+ private var modelURL: String = ""
+ private var manufacturer: String = ""
+ private var manufacturerURL: String = ""
+ private var udn: String = ""
+ private var urlBase: String = ""
+
+ init {
+ location = parseHeader(header, "LOCATION: ")
+ server = parseHeader(header, "SERVER: ")
+ }
+
+ internal fun update(xml: String) {
+ descriptionXML = xml
+ try {
+ xmlParse(xml)
+ } catch (e: XmlPullParserException) {
+ Log.w(UPnPDiscovery.TAG, e.toString())
+ }
+ }
+
+ override fun toString(): String =
+ "FriendlyName: " + friendlyName + LINE_END +
+ "ModelName: " + modelName + LINE_END +
+ "HostAddress: " + hostAddress + LINE_END +
+ "Location: " + location + LINE_END +
+ "DeviceType: " + deviceType + LINE_END +
+ "PresentationURL: " + presentationURL + LINE_END +
+ "SerialNumber: " + serialNumber + LINE_END +
+ "ModelURL: " + modelURL + LINE_END +
+ "ModelNumber: " + modelNumber + LINE_END +
+ "Manufacturer: " + manufacturer + LINE_END +
+ "ManufacturerURL: " + manufacturerURL + LINE_END +
+ "UDN: " + udn + LINE_END +
+ "URLBase: " + urlBase
+
+ private fun parseHeader(
+ mSearchAnswer: String,
+ whatSearch: String,
+ ): String {
+ var result = ""
+ var searchLinePos = mSearchAnswer.indexOf(whatSearch)
+ if (searchLinePos != -1) {
+ searchLinePos += whatSearch.length
+ val locColon = mSearchAnswer.indexOf(LINE_END, searchLinePos)
+ result = mSearchAnswer.substring(searchLinePos, locColon)
+ }
+ return result
+ }
+
+ private fun readText(parser: XmlPullParser): String {
+ var result = ""
+ if (parser.next() == XmlPullParser.TEXT) {
+ result = parser.text
+ parser.nextTag()
+ }
+ return result
+ }
+
+ private fun xmlParse(xml: String) {
+ val xmlFactoryObject = XmlPullParserFactory.newInstance()
+ val parser = xmlFactoryObject.newPullParser()
+ parser.setInput(ByteArrayInputStream(xml.toByteArray(Charsets.UTF_8)), null)
+ var event = parser.eventType
+ while (event != XmlPullParser.END_DOCUMENT) {
+ val name = parser.name
+ if (event == XmlPullParser.START_TAG) {
+ when (name) {
+ "friendlyName" -> friendlyName = readText(parser)
+ "deviceType" -> deviceType = readText(parser)
+ "presentationURL" -> presentationURL = readText(parser)
+ "serialNumber" -> serialNumber = readText(parser)
+ "modelName" -> modelName = readText(parser)
+ "modelNumber" -> modelNumber = readText(parser)
+ "modelURL" -> modelURL = readText(parser)
+ "manufacturer" -> manufacturer = readText(parser)
+ "manufacturerURL" -> manufacturerURL = readText(parser)
+ "UDN" -> udn = readText(parser)
+ "URLBase" -> urlBase = readText(parser)
+ }
+ }
+ event = parser.next()
+ }
+ }
+
+ companion object {
+ private const val LINE_END = "\r\n"
+ }
+}
diff --git a/app/src/main/java/com/rine/upnpdiscovery/UPnPDiscovery.kt b/app/src/main/java/com/rine/upnpdiscovery/UPnPDiscovery.kt
new file mode 100644
index 0000000..deef452
--- /dev/null
+++ b/app/src/main/java/com/rine/upnpdiscovery/UPnPDiscovery.kt
@@ -0,0 +1,178 @@
+package com.rine.upnpdiscovery
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.content.Context
+import android.net.wifi.WifiManager
+import android.os.AsyncTask
+import android.util.Log
+import com.android.volley.Request
+import com.android.volley.toolbox.StringRequest
+import com.android.volley.toolbox.Volley
+import java.io.IOException
+import java.net.DatagramPacket
+import java.net.DatagramSocket
+import java.net.InetAddress
+import java.net.InetSocketAddress
+
+@Suppress("MagicNumber")
+class UPnPDiscovery : AsyncTask {
+ private val devices = HashSet()
+
+ @SuppressLint("StaticFieldLeak")
+ private val mContext: Context
+ private var mThreadsCount: Int = 0
+ private val mCustomQuery: String
+ private val mInternetAddress: String
+ private val mPort: Int
+
+ private val mListener: OnDiscoveryListener
+
+ interface OnDiscoveryListener {
+ fun onStart()
+
+ fun onFoundNewDevice(device: UPnPDevice)
+
+ fun onFinish(devices: HashSet)
+
+ fun onError(e: Exception)
+ }
+
+ private constructor(activity: Activity, listener: OnDiscoveryListener) {
+ mContext = activity.applicationContext
+ mListener = listener
+ mThreadsCount = 0
+ mCustomQuery = DEFAULT_QUERY
+ mInternetAddress = DEFAULT_ADDRESS
+ mPort = 1900
+ }
+
+ private constructor(
+ activity: Activity,
+ listener: OnDiscoveryListener,
+ customQuery: String,
+ address: String,
+ port: Int,
+ ) {
+ mContext = activity.applicationContext
+ mListener = listener
+ mThreadsCount = 0
+ mCustomQuery = customQuery
+ mInternetAddress = address
+ mPort = port
+ }
+
+ @Deprecated("Deprecated in Java")
+ override fun doInBackground(vararg p0: Activity?): Void? {
+ mListener.onStart()
+ val wifi = mContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
+ val lock = wifi.createMulticastLock("The Lock")
+ lock.acquire()
+ var socket: DatagramSocket? = null
+ try {
+ val group = InetAddress.getByName(mInternetAddress)
+ val port = mPort
+ val query = mCustomQuery
+ socket = DatagramSocket(null)
+ socket.reuseAddress = true
+ socket.broadcast = true
+ socket.bind(InetSocketAddress(port))
+
+ val datagramPacketRequest = DatagramPacket(query.toByteArray(), query.length, group, port)
+ socket.send(datagramPacketRequest)
+
+ val time = System.currentTimeMillis()
+ var curTime = System.currentTimeMillis()
+
+ while (curTime - time < 1000) {
+ val datagramPacket = DatagramPacket(ByteArray(1024), 1024)
+ socket.receive(datagramPacket)
+ val response = String(datagramPacket.data, 0, datagramPacket.length)
+ if (response.substring(0, 12).uppercase() == "HTTP/1.1 200") {
+ val device = UPnPDevice(datagramPacket.address.hostAddress ?: continue, response)
+ mThreadsCount++
+ getData(device.location, device)
+ }
+ curTime = System.currentTimeMillis()
+ }
+ } catch (e: IOException) {
+ mListener.onError(e)
+ } finally {
+ socket?.close()
+ }
+ lock.release()
+ return null
+ }
+
+ private fun getData(
+ url: String,
+ device: UPnPDevice,
+ ) {
+ val stringRequest =
+ StringRequest(
+ Request.Method.GET,
+ url,
+ { response ->
+ device.update(response)
+ mListener.onFoundNewDevice(device)
+ devices.add(device)
+ mThreadsCount--
+ if (mThreadsCount == 0) {
+ mListener.onFinish(devices)
+ }
+ },
+ {
+ mThreadsCount--
+ Log.e(TAG, "URL: $url get content error!")
+ },
+ )
+ stringRequest.tag = TAG + "SSDP description request"
+ Volley.newRequestQueue(mContext).add(stringRequest)
+ }
+
+ companion object {
+ internal val TAG: String = UPnPDiscovery::class.java.simpleName
+
+ private const val DISCOVER_TIMEOUT = 1500
+ private const val LINE_END = "\r\n"
+ private const val DEFAULT_QUERY =
+ "M-SEARCH * HTTP/1.1" + LINE_END +
+ "HOST: 239.255.255.250:1900" + LINE_END +
+ "MAN: \"ssdp:discover\"" + LINE_END +
+ "MX: 1" + LINE_END +
+ "ST: ssdp:all" + LINE_END +
+ LINE_END
+ private const val DEFAULT_ADDRESS = "239.255.255.250"
+
+ fun discoveryDevices(
+ activity: Activity,
+ listener: OnDiscoveryListener,
+ ): Boolean {
+ val discover = UPnPDiscovery(activity, listener)
+ discover.execute()
+ return try {
+ Thread.sleep(DISCOVER_TIMEOUT.toLong())
+ true
+ } catch (e: InterruptedException) {
+ false
+ }
+ }
+
+ fun discoveryDevices(
+ activity: Activity,
+ listener: OnDiscoveryListener,
+ customQuery: String,
+ address: String,
+ port: Int,
+ ): Boolean {
+ val discover = UPnPDiscovery(activity, listener, customQuery, address, port)
+ discover.execute()
+ return try {
+ Thread.sleep(DISCOVER_TIMEOUT.toLong())
+ true
+ } catch (e: InterruptedException) {
+ false
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/Application.kt b/app/src/main/java/io/github/domi04151309/home/Application.kt
new file mode 100644
index 0000000..a57db64
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/Application.kt
@@ -0,0 +1,10 @@
+package io.github.domi04151309.home
+
+import com.google.android.material.color.DynamicColors
+
+class Application : android.app.Application() {
+ override fun onCreate() {
+ super.onCreate()
+ DynamicColors.applyToActivitiesIfAvailable(this)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/AboutActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/AboutActivity.kt
new file mode 100644
index 0000000..4d91266
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/AboutActivity.kt
@@ -0,0 +1,112 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.os.Bundle
+import androidx.core.net.toUri
+import androidx.preference.Preference
+import androidx.preference.PreferenceFragmentCompat
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import io.github.domi04151309.home.BuildConfig
+import io.github.domi04151309.home.R
+
+class AboutActivity : BaseActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_settings)
+ supportFragmentManager
+ .beginTransaction()
+ .replace(R.id.settings, GeneralPreferenceFragment())
+ .commit()
+ }
+
+ class GeneralPreferenceFragment : PreferenceFragmentCompat() {
+ @Suppress("SameReturnValue")
+ private fun onIconsClicked(): Boolean {
+ MaterialAlertDialogBuilder(requireContext())
+ .setTitle(R.string.about_icons)
+ .setItems(resources.getStringArray(R.array.about_icons_array)) { _, which ->
+ startActivity(
+ Intent(
+ Intent.ACTION_VIEW,
+ when (which) {
+ 0 -> "https://icons8.com/"
+ 1 -> "https://fonts.google.com/icons?selected=Material+Icons"
+ else -> "about:blank"
+ }.toUri(),
+ ),
+ )
+ }
+ .show()
+ return true
+ }
+
+ @Suppress("SameReturnValue")
+ private fun onExternalClicked(link: String): Boolean {
+ MaterialAlertDialogBuilder(requireContext())
+ .setTitle(R.string.about_privacy)
+ .setMessage(R.string.about_privacy_desc)
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ startActivity(
+ Intent(
+ Intent.ACTION_VIEW,
+ link.toUri(),
+ ),
+ )
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .setNeutralButton(R.string.about_privacy_policy) { _, _ ->
+ startActivity(
+ Intent(
+ Intent.ACTION_VIEW,
+ "https://docs.github.com/en/github/site-policy/github-privacy-statement".toUri(),
+ ),
+ )
+ }
+ .show()
+ return true
+ }
+
+ override fun onCreatePreferences(
+ savedInstanceState: Bundle?,
+ rootKey: String?,
+ ) {
+ addPreferencesFromResource(R.xml.pref_about)
+ findPreference("app_version")?.apply {
+ summary =
+ requireContext().getString(
+ R.string.about_app_version_desc,
+ BuildConfig.VERSION_NAME,
+ BuildConfig.VERSION_CODE,
+ )
+ setOnPreferenceClickListener {
+ onExternalClicked("$REPOSITORY_URL/releases")
+ }
+ }
+ findPreference("github")?.apply {
+ summary = REPOSITORY_URL
+ setOnPreferenceClickListener {
+ onExternalClicked(REPOSITORY_URL)
+ }
+ }
+ findPreference("license")?.setOnPreferenceClickListener {
+ onExternalClicked("$REPOSITORY_URL/blob/$BRANCH/LICENSE")
+ }
+ findPreference("icons")?.setOnPreferenceClickListener {
+ onIconsClicked()
+ }
+ findPreference("contributors")?.setOnPreferenceClickListener {
+ onExternalClicked("$REPOSITORY_URL/graphs/contributors")
+ }
+ findPreference("libraries")?.setOnPreferenceClickListener {
+ startActivity(Intent(requireContext(), LibraryActivity::class.java))
+ true
+ }
+ }
+ }
+
+ companion object {
+ private const val REPOSITORY: String = "Domi04151309/HomeApp"
+ private const val BRANCH: String = "main"
+ private const val REPOSITORY_URL: String = "https://github.com/$REPOSITORY"
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/BaseActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/BaseActivity.kt
new file mode 100644
index 0000000..f059af5
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/BaseActivity.kt
@@ -0,0 +1,22 @@
+package io.github.domi04151309.home.activities
+
+import android.content.res.Configuration
+import android.os.Bundle
+import androidx.appcompat.app.AppCompatActivity
+import com.google.android.material.elevation.SurfaceColors
+import io.github.domi04151309.home.R
+
+abstract class BaseActivity : AppCompatActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (resources.configuration.uiMode.and(
+ Configuration.UI_MODE_NIGHT_MASK,
+ ) != Configuration.UI_MODE_NIGHT_YES
+ ) {
+ setTheme(R.style.LightStatusBarOverlay)
+ }
+ val color = SurfaceColors.SURFACE_2.getColor(this)
+ window.statusBarColor = color
+ window.navigationBarColor = color
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ControlInfoActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/ControlInfoActivity.kt
new file mode 100644
index 0000000..b1b390c
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ControlInfoActivity.kt
@@ -0,0 +1,70 @@
+package io.github.domi04151309.home.activities
+
+import android.os.Bundle
+import com.google.android.material.elevation.SurfaceColors
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.fragments.ControlInfoFragment
+import io.github.domi04151309.home.fragments.HueColorFragment
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HueRoomInterface
+
+class ControlInfoActivity : BaseActivity() {
+ private var hueRoom: ControlInfoActivityHueRoom? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_settings)
+
+ window.statusBarColor = SurfaceColors.SURFACE_0.getColor(this)
+
+ val id = intent.getStringExtra(EXTRA_ID)
+ if (id === null) {
+ return
+ }
+
+ val device = Devices(this).getDeviceById(id.substring(0, id.indexOf('@')))
+
+ if (device.mode == Global.HUE_API) {
+ showHueFragment(id, device)
+ return
+ }
+
+ supportFragmentManager
+ .beginTransaction()
+ .replace(R.id.settings, ControlInfoFragment(device, intent.getStringExtra(EXTRA_TITLE) ?: ""))
+ .commit()
+ }
+
+ override fun onStart() {
+ super.onStart()
+ hueRoom?.onStart()
+ }
+
+ override fun onStop() {
+ super.onStop()
+ hueRoom?.onStop()
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ hueRoom?.onDestroy()
+ }
+
+ private fun showHueFragment(
+ id: String,
+ device: DeviceItem,
+ ) {
+ hueRoom = ControlInfoActivityHueRoom(this, device, id.substring(id.indexOf('@') + 1))
+ supportFragmentManager
+ .beginTransaction()
+ .replace(R.id.settings, HueColorFragment(hueRoom as HueRoomInterface))
+ .commit()
+ }
+
+ companion object {
+ const val EXTRA_ID: String = "EXTRA_ID"
+ const val EXTRA_TITLE: String = "EXTRA_TITLE"
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ControlInfoActivityHueRoom.kt b/app/src/main/java/io/github/domi04151309/home/activities/ControlInfoActivityHueRoom.kt
new file mode 100644
index 0000000..1a5ba4c
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ControlInfoActivityHueRoom.kt
@@ -0,0 +1,97 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Context
+import com.android.volley.Request
+import com.android.volley.toolbox.JsonObjectRequest
+import com.android.volley.toolbox.Volley
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.LightStates
+import io.github.domi04151309.home.helpers.HueLightListener
+import io.github.domi04151309.home.helpers.HueUtils.MIN_COLOR_TEMPERATURE
+import io.github.domi04151309.home.helpers.UpdateHandler
+import io.github.domi04151309.home.interfaces.HueRoomInterface
+import org.json.JSONArray
+
+class ControlInfoActivityHueRoom : HueRoomInterface {
+ override var lights: JSONArray?
+ override var lampData: HueLightListener
+ override var id: String
+ override var device: DeviceItem
+ override var addressPrefix: String
+ override var canReceiveRequest: Boolean
+
+ private var updateDataRequest: JsonObjectRequest? = null
+ private var updateHandler: UpdateHandler = UpdateHandler()
+
+ constructor(context: Context, device: DeviceItem, id: String) {
+ val hueApi = HueAPI(context, device.id)
+ val queue = Volley.newRequestQueue(context)
+
+ this.lights = null
+ this.lampData = HueLightListener()
+ this.id = id
+ this.device = device
+ this.addressPrefix = device.address + "api/" + hueApi.getUsername()
+ this.canReceiveRequest = false
+
+ updateDataRequest = getUpdateRequest()
+ updateHandler.setUpdateFunction {
+ if (canReceiveRequest && hueApi.readyForRequest) {
+ queue.add(updateDataRequest)
+ }
+ }
+
+ onStart()
+ }
+
+ fun onStart() {
+ canReceiveRequest = true
+ }
+
+ fun onStop() {
+ canReceiveRequest = false
+ }
+
+ fun onDestroy() {
+ updateHandler.stop()
+ }
+
+ override fun onColorChanged(color: Int) {
+ // Do nothing.
+ }
+
+ private fun getUpdateRequest() =
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/groups/$id",
+ null,
+ { response ->
+ lights = response.getJSONArray("lights")
+ val action = response.getJSONObject("action")
+ val light = LightStates.Light()
+
+ light.ct =
+ if (action.has("ct")) {
+ action.getInt("ct") - MIN_COLOR_TEMPERATURE
+ } else {
+ -1
+ }
+
+ if (action.has("hue") && action.has("sat")) {
+ light.hue = action.getInt("hue")
+ light.sat = action.getInt("sat")
+ } else {
+ light.hue = -1
+ light.sat = -1
+ }
+
+ light.on = response.getJSONObject("state").getBoolean("any_on")
+
+ lampData.state = light
+ },
+ {
+ canReceiveRequest = false
+ },
+ )
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/DeviceInfoActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/DeviceInfoActivity.kt
new file mode 100644
index 0000000..3b2f045
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/DeviceInfoActivity.kt
@@ -0,0 +1,238 @@
+package io.github.domi04151309.home.activities
+
+import android.os.Bundle
+import android.view.View
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.android.volley.Request
+import com.android.volley.RequestQueue
+import com.android.volley.toolbox.JsonObjectRequest
+import com.android.volley.toolbox.Volley
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.SimpleListAdapter
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.api.HueAPIParser
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+import org.json.JSONObject
+import java.util.Locale
+import java.util.concurrent.TimeUnit
+
+@Suppress("TooManyFunctions")
+class DeviceInfoActivity : BaseActivity(), RecyclerViewHelperInterface {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_devices)
+
+ val devices = Devices(this)
+ val id = intent.getStringExtra(Devices.INTENT_EXTRA_DEVICE) ?: ""
+ if (!devices.idExists(id)) {
+ finish()
+ return
+ }
+
+ val device = devices.getDeviceById(id)
+ val queue = Volley.newRequestQueue(this)
+ val recyclerView = findViewById(R.id.recyclerView)
+ val items = mutableListOf()
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ items.add(
+ SimpleListItem(
+ device.name,
+ device.address,
+ icon = device.iconId,
+ ),
+ )
+
+ when (device.mode) {
+ Global.HUE_API -> showHueInfo(device, queue, items, recyclerView)
+ Global.SHELLY_GEN_2 -> showShelly2Info(device, queue, items, recyclerView)
+ Global.SHELLY_GEN_3 -> showShelly2Info(device, queue, items, recyclerView)
+ }
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ // Do nothing.
+ }
+
+ private fun boolToString(bool: Boolean): String =
+ resources.getString(
+ if (bool) R.string.str_on else R.string.str_off,
+ )
+
+ @Suppress("MagicNumber")
+ private fun rssiToPercent(rssi: Int): Int =
+ if (rssi <= -100) {
+ 0
+ } else if (rssi >= -50) {
+ 100
+ } else {
+ 2 * (rssi + 100)
+ }
+
+ private fun formatUptime(uptime: Long) =
+ String.format(
+ Locale.getDefault(),
+ "%02d:%02d:%02d",
+ TimeUnit.SECONDS.toHours(uptime),
+ TimeUnit.SECONDS.toMinutes(uptime) -
+ TimeUnit.HOURS.toMinutes(
+ TimeUnit.SECONDS.toHours(
+ uptime,
+ ),
+ ),
+ TimeUnit.SECONDS.toSeconds(uptime) -
+ TimeUnit.MINUTES.toSeconds(
+ TimeUnit.SECONDS.toMinutes(
+ uptime,
+ ),
+ ),
+ )
+
+ private fun showHueInfo(
+ device: DeviceItem,
+ queue: RequestQueue,
+ items: MutableList,
+ recyclerView: RecyclerView,
+ ) {
+ val hueAPI = HueAPI(this, device.id)
+ val addressPrefix = device.address + "api/" + hueAPI.getUsername()
+
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/config",
+ null,
+ { response ->
+ items.addAll(HueAPIParser.parseHueConfig(resources, response))
+
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/sensors",
+ null,
+ { innerResponse ->
+ items.addAll(HueAPIParser.parseHueSensors(resources, innerResponse))
+
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/lights",
+ null,
+ { innerInnerResponse ->
+ items.addAll(HueAPIParser.parseHueLights(resources, innerInnerResponse))
+ recyclerView.adapter = SimpleListAdapter(items, this)
+ },
+ { },
+ ),
+ )
+ },
+ { },
+ ),
+ )
+ },
+ { },
+ ),
+ )
+ }
+
+ @Suppress("LongMethod")
+ private fun parseShelly2Info(response: JSONObject) =
+ listOf(
+ SimpleListItem(summary = resources.getString(R.string.device_config_info_status)),
+ SimpleListItem(
+ (response.optJSONObject("wifi") ?: JSONObject()).run {
+ optString("ssid") + " (" + rssiToPercent(optInt("rssi")) + " %)"
+ },
+ resources.getString(R.string.shelly_wifi),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ boolToString(
+ (
+ response.optJSONObject("mqtt")
+ ?: JSONObject()
+ ).optBoolean("connected"),
+ ),
+ resources.getString(R.string.shelly_mqtt),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ boolToString(
+ (
+ response.optJSONObject("cloud")
+ ?: JSONObject()
+ ).optBoolean("connected"),
+ ),
+ resources.getString(R.string.shelly_cloud),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ formatUptime((response.optJSONObject("sys") ?: JSONObject()).optLong("uptime")),
+ resources.getString(R.string.shelly_uptime),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ (response.optJSONObject("sys") ?: JSONObject()).run {
+ "${(optInt("fs_free") / optInt("fs_size").toFloat() * TO_PERCENT).toInt()} %"
+ },
+ resources.getString(R.string.shelly_storage),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ (response.optJSONObject("sys") ?: JSONObject()).run {
+ "${(optInt("ram_free") / optInt("ram_size").toFloat() * TO_PERCENT).toInt()} %"
+ },
+ resources.getString(R.string.shelly_ram),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ resources.getString(
+ if ((
+ (
+ response.optJSONObject("sys")
+ ?: JSONObject()
+ ).optJSONObject("available_updates")
+ ?: JSONObject()
+ ).has("stable")
+ ) {
+ R.string.str_yes
+ } else {
+ R.string.str_no
+ },
+ ),
+ resources.getString(R.string.shelly_update),
+ icon = R.drawable.ic_about_info,
+ ),
+ )
+
+ private fun showShelly2Info(
+ device: DeviceItem,
+ queue: RequestQueue,
+ items: MutableList,
+ recyclerView: RecyclerView,
+ ) {
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ device.address + "rpc/Shelly.GetStatus",
+ null,
+ { response ->
+ items.addAll(parseShelly2Info(response))
+ recyclerView.adapter = SimpleListAdapter(items, this)
+ },
+ { },
+ ),
+ )
+ }
+
+ companion object {
+ private const val TO_PERCENT = 100
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/DevicesActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/DevicesActivity.kt
new file mode 100644
index 0000000..52b3f05
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/DevicesActivity.kt
@@ -0,0 +1,152 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import androidx.recyclerview.widget.ItemTouchHelper
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.DeviceListAdapter
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterfaceAdvanced
+
+class DevicesActivity : BaseActivity(), RecyclerViewHelperInterfaceAdvanced {
+ private var reset = true
+ private lateinit var devices: Devices
+ private lateinit var recyclerView: RecyclerView
+ private lateinit var itemTouchHelper: ItemTouchHelper
+
+ private val itemTouchHelperCallback =
+ object : ItemTouchHelper.Callback() {
+ override fun getMovementFlags(
+ recyclerView: RecyclerView,
+ viewHolder: RecyclerView.ViewHolder,
+ ): Int =
+ if (
+ viewHolder.adapterPosition == (recyclerView.adapter?.itemCount ?: -1) - 1
+ ) {
+ makeMovementFlags(0, 0)
+ } else {
+ makeMovementFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0)
+ }
+
+ override fun onMove(
+ recyclerView: RecyclerView,
+ viewHolder: RecyclerView.ViewHolder,
+ target: RecyclerView.ViewHolder,
+ ): Boolean {
+ val adapter = recyclerView.adapter ?: return false
+ return if (target.adapterPosition == adapter.itemCount - 1) {
+ false
+ } else {
+ recyclerView.adapter?.notifyItemMoved(
+ viewHolder.adapterPosition,
+ target.adapterPosition,
+ )
+ devices.moveDevice(viewHolder.adapterPosition, target.adapterPosition)
+ true
+ }
+ }
+
+ override fun isLongPressDragEnabled(): Boolean = true
+
+ override fun onSwiped(
+ viewHolder: RecyclerView.ViewHolder,
+ direction: Int,
+ ) {
+ // Do nothing.
+ }
+
+ override fun clearView(
+ recyclerView: RecyclerView,
+ viewHolder: RecyclerView.ViewHolder,
+ ) {
+ super.clearView(recyclerView, viewHolder)
+ devices.saveChanges()
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_devices)
+
+ devices = Devices(this)
+ recyclerView = findViewById(R.id.recyclerView)
+ itemTouchHelper = ItemTouchHelper(itemTouchHelperCallback)
+
+ itemTouchHelper.attachToRecyclerView(recyclerView)
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ }
+
+ private fun loadDevices() {
+ val listItems: ArrayList = ArrayList(devices.length)
+ var currentDevice: DeviceItem
+ for (i in 0 until devices.length) {
+ currentDevice = devices.getDeviceByIndex(i)
+ listItems +=
+ SimpleListItem(
+ title = currentDevice.name,
+ summary =
+ if (currentDevice.hide) {
+ resources.getString(R.string.device_config_hidden) + " · " + currentDevice.address
+ } else {
+ currentDevice.address
+ },
+ hidden = "edit#${currentDevice.id}",
+ icon = currentDevice.iconId,
+ )
+ }
+ listItems +=
+ SimpleListItem(
+ title = resources.getString(R.string.pref_add),
+ summary = resources.getString(R.string.pref_add_summary),
+ hidden = "add",
+ icon = R.drawable.ic_add,
+ )
+
+ recyclerView.adapter = DeviceListAdapter(listItems, this)
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ val action = view.findViewById(R.id.hidden).text
+ if (action.contains("edit")) {
+ reset = true
+ startActivity(
+ Intent(this, EditDeviceActivity::class.java)
+ .putExtra("deviceId", action.substring(action.indexOf('#') + 1)),
+ )
+ } else if (action == "add") {
+ reset = true
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.pref_add_method)
+ .setItems(resources.getStringArray(R.array.pref_add_method_array)) { _, which ->
+ if (which == 0) {
+ startActivity(Intent(this, EditDeviceActivity::class.java))
+ } else if (which == 1) {
+ startActivity(Intent(this, SearchDevicesActivity::class.java))
+ }
+ }
+ .show()
+ }
+ }
+
+ override fun onItemHandleTouched(viewHolder: RecyclerView.ViewHolder) {
+ itemTouchHelper.startDrag(viewHolder)
+ }
+
+ override fun onStart() {
+ super.onStart()
+ if (reset) {
+ reset = false
+ loadDevices()
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/EditDeviceActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/EditDeviceActivity.kt
new file mode 100644
index 0000000..9abb9d2
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/EditDeviceActivity.kt
@@ -0,0 +1,387 @@
+package io.github.domi04151309.home.activities
+
+import android.content.ActivityNotFoundException
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Bundle
+import android.util.Log
+import android.view.View
+import android.widget.ArrayAdapter
+import android.widget.AutoCompleteTextView
+import android.widget.Button
+import android.widget.CheckBox
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.TextView
+import android.widget.Toast
+import androidx.core.net.toUri
+import com.google.android.material.appbar.MaterialToolbar
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.google.android.material.elevation.SurfaceColors
+import com.google.android.material.floatingactionbutton.FloatingActionButton
+import com.google.android.material.textfield.TextInputLayout
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.IconSpinnerAdapter
+import io.github.domi04151309.home.custom.TextWatcher
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.helpers.DeviceSecrets
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+
+class EditDeviceActivity : BaseActivity() {
+ private lateinit var devices: Devices
+ private lateinit var deviceId: String
+ private lateinit var deviceSecrets: DeviceSecrets
+ private lateinit var deviceIcon: ImageView
+ private lateinit var nameText: TextView
+ private lateinit var nameBox: TextInputLayout
+ private lateinit var addressBox: TextInputLayout
+ private lateinit var iconSpinner: AutoCompleteTextView
+ private lateinit var modeSpinner: AutoCompleteTextView
+ private lateinit var specialDivider: View
+ private lateinit var specialSection: LinearLayout
+ private lateinit var usernameBox: TextInputLayout
+ private lateinit var passwordBox: TextInputLayout
+ private lateinit var configHide: CheckBox
+ private lateinit var configDirectView: CheckBox
+ private lateinit var configButton: Button
+ private lateinit var infoButton: Button
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_edit_device)
+
+ window.statusBarColor = SurfaceColors.SURFACE_0.getColor(this)
+
+ devices = Devices(this)
+ var deviceId = intent.getStringExtra("deviceId")
+ val editing =
+ if (deviceId == null) {
+ deviceId = devices.generateNewId()
+ false
+ } else {
+ true
+ }
+ this.deviceId = deviceId
+
+ deviceSecrets = DeviceSecrets(this, deviceId)
+
+ deviceIcon = findViewById(R.id.deviceIcn)
+ nameText = findViewById(R.id.nameTxt)
+ nameBox = findViewById(R.id.nameBox)
+ addressBox = findViewById(R.id.addressBox)
+ iconSpinner = findViewById(R.id.iconSpinner).editText as AutoCompleteTextView
+ modeSpinner = findViewById(R.id.modeSpinner).editText as AutoCompleteTextView
+ specialDivider = findViewById(R.id.specialDivider)
+ specialSection = findViewById(R.id.specialSection)
+ usernameBox = findViewById(R.id.usernameBox)
+ passwordBox = findViewById(R.id.passwordBox)
+ configHide = findViewById(R.id.configHide)
+ configDirectView = findViewById(R.id.configDirectView)
+ configButton = findViewById(R.id.configBtn)
+ infoButton = findViewById(R.id.infoBtn)
+
+ findViewById(R.id.idTxt).text = resources.getString(R.string.pref_add_id, deviceId)
+
+ iconSpinner.addTextChangedListener(getIconTextWatcher())
+ modeSpinner.addTextChangedListener(getModeTextWatcher(editing))
+ nameBox.editText?.addTextChangedListener(getNameTextWatcher())
+
+ if (editing) {
+ onEditDevice()
+ } else {
+ onCreateDevice()
+ }
+
+ iconSpinner.setAdapter(IconSpinnerAdapter(resources.getStringArray(R.array.pref_icons)))
+ modeSpinner.setAdapter(
+ ArrayAdapter(
+ this,
+ R.layout.dropdown_item,
+ resources.getStringArray(R.array.pref_add_mode_array),
+ ),
+ )
+
+ findViewById(R.id.fab).setOnClickListener {
+ onFloatingActionButtonClicked()
+ }
+
+ findViewById(R.id.toolbar).apply {
+ setNavigationIcon(R.drawable.ic_arrow_back)
+ setNavigationOnClickListener {
+ onBackPressedDispatcher.onBackPressed()
+ }
+ }
+ }
+
+ private fun getIconTextWatcher() =
+ TextWatcher {
+ deviceIcon.setImageResource(Global.getIcon(it))
+ }
+
+ private fun showExternalInfoBasedOnMode(mode: String) {
+ configButton.visibility =
+ if (HAS_CONFIG.contains(mode)) {
+ View.VISIBLE
+ } else {
+ View.GONE
+ }
+ infoButton.visibility =
+ if (HAS_INFO.contains(mode)) {
+ View.VISIBLE
+ } else {
+ View.GONE
+ }
+ }
+
+ @Suppress("ComplexCondition")
+ private fun getModeTextWatcher(editing: Boolean) =
+ TextWatcher {
+ val specialVisibility =
+ if (
+ it == Global.FRITZ_AUTO_LOGIN ||
+ it == Global.GRAFANA_AUTO_LOGIN ||
+ it == Global.PI_HOLE_AUTO_LOGIN ||
+ it == Global.SHELLY_GEN_1
+ ) {
+ View.VISIBLE
+ } else {
+ View.GONE
+ }
+ val usernameVisibility =
+ if (
+ it == Global.GRAFANA_AUTO_LOGIN ||
+ it == Global.SHELLY_GEN_1
+ ) {
+ View.VISIBLE
+ } else {
+ View.GONE
+ }
+ specialDivider.visibility = specialVisibility
+ specialSection.visibility = specialVisibility
+ usernameBox.visibility = usernameVisibility
+
+ if (SUPPORTS_DIRECT_VIEW.contains(it)) {
+ configDirectView.isEnabled = true
+ } else {
+ configDirectView.isEnabled = false
+ configDirectView.isChecked = false
+ }
+
+ if (editing) {
+ showExternalInfoBasedOnMode(it)
+ }
+ }
+
+ private fun getNameTextWatcher() =
+ TextWatcher {
+ if (it == "") {
+ nameText.text = resources.getString(R.string.pref_add_name_empty)
+ } else {
+ nameText.text = it
+ }
+ }
+
+ private fun onEditDevice() {
+ val device = devices.getDeviceById(deviceId)
+ nameBox.editText?.setText(device.name)
+ addressBox.editText?.setText(device.address)
+ iconSpinner.setText(device.iconName)
+ modeSpinner.setText(device.mode)
+ usernameBox.editText?.setText(deviceSecrets.username)
+ passwordBox.editText?.setText(deviceSecrets.password)
+ configHide.isChecked = device.hide
+ configDirectView.isChecked = device.directView
+
+ configButton.setOnClickListener {
+ onConfigButtonClicked()
+ }
+
+ infoButton.setOnClickListener {
+ startActivity(Intent(this, DeviceInfoActivity::class.java).putExtra(Devices.INTENT_EXTRA_DEVICE, deviceId))
+ }
+
+ findViewById(R.id.shortcutBtn).setOnClickListener {
+ onShortcutButtonClicked(device)
+ }
+
+ findViewById(R.id.deleteBtn).setOnClickListener {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.str_delete)
+ .setMessage(R.string.pref_delete_device_question)
+ .setPositiveButton(R.string.str_delete) { _, _ ->
+ devices.deleteDevice(deviceId)
+ finish()
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ }
+ }
+
+ private fun onConfigButtonClicked() {
+ when (modeSpinner.text.toString()) {
+ Global.ESP_EASY, Global.SHELLY_GEN_1, Global.SHELLY_GEN_2, Global.SHELLY_GEN_3 -> {
+ startActivity(
+ Intent(this, WebActivity::class.java)
+ .putExtra("URI", addressBox.editText?.text.toString())
+ .putExtra("title", resources.getString(R.string.pref_device_config)),
+ )
+ }
+ Global.NODE_RED -> {
+ startActivity(
+ Intent(this, WebActivity::class.java)
+ .putExtra("URI", formatNodeREDAddress(addressBox.editText?.text.toString()))
+ .putExtra("title", resources.getString(R.string.pref_device_config)),
+ )
+ }
+ Global.HUE_API -> {
+ val huePackageName = "com.philips.lighting.hue2"
+ val launchIntent = packageManager.getLaunchIntentForPackage(huePackageName)
+ if (launchIntent == null) {
+ try {
+ startActivity(
+ Intent(
+ Intent.ACTION_VIEW,
+ "market://details?id=$huePackageName".toUri(),
+ ),
+ )
+ } catch (e: ActivityNotFoundException) {
+ Log.w(EditDeviceActivity::class.simpleName, e)
+ startActivity(
+ Intent(
+ Intent.ACTION_VIEW,
+ "https://play.google.com/store/apps/details?id=$huePackageName".toUri(),
+ ),
+ )
+ }
+ } else {
+ startActivity(launchIntent)
+ }
+ }
+ }
+ }
+
+ private fun onShortcutButtonClicked(device: DeviceItem) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val shortcutManager = this.getSystemService(ShortcutManager::class.java)
+ if (shortcutManager != null) {
+ if (shortcutManager.isRequestPinShortcutSupported) {
+ val shortcut =
+ ShortcutInfo.Builder(this, deviceId)
+ .setShortLabel(
+ device.name.ifEmpty {
+ resources.getString(R.string.pref_add_name_empty)
+ },
+ )
+ .setLongLabel(
+ device.name.ifEmpty {
+ resources.getString(R.string.pref_add_name_empty)
+ },
+ )
+ .setIcon(Icon.createWithResource(this, device.iconId))
+ .setIntent(
+ Intent(this, MainActivity::class.java)
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, deviceId)
+ .setAction(Intent.ACTION_MAIN)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
+ )
+ .build()
+ shortcutManager.requestPinShortcut(shortcut, null)
+ } else {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+ } else {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+
+ private fun onCreateDevice() {
+ iconSpinner.setText(resources.getStringArray(R.array.pref_icons)[0])
+ modeSpinner.setText(resources.getStringArray(R.array.pref_add_mode_array)[0])
+ findViewById(R.id.editDivider).visibility = View.GONE
+ findViewById(R.id.editSection).visibility = View.GONE
+ }
+
+ private fun onFloatingActionButtonClicked() {
+ val name = nameBox.editText?.text.toString()
+ if (name == "") {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.err_missing_name)
+ .setMessage(R.string.err_missing_name_summary)
+ .setPositiveButton(android.R.string.ok) { _, _ -> }
+ .show()
+ return
+ } else if (addressBox.editText?.text.toString() == "") {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.err_missing_address)
+ .setMessage(R.string.err_missing_address_summary)
+ .setPositiveButton(android.R.string.ok) { _, _ -> }
+ .show()
+ return
+ }
+
+ val tempAddress =
+ if (modeSpinner.text.toString() == Global.NODE_RED) {
+ formatNodeREDAddress(addressBox.editText?.text.toString())
+ } else {
+ addressBox.editText?.text.toString()
+ }
+
+ val newItem =
+ DeviceItem(
+ deviceId,
+ name,
+ modeSpinner.text.toString(),
+ iconSpinner.text.toString(),
+ configHide.isChecked,
+ configDirectView.isChecked,
+ )
+ newItem.address = tempAddress
+ devices.addDevice(newItem)
+ deviceSecrets.username = usernameBox.editText?.text.toString()
+ deviceSecrets.password = passwordBox.editText?.text.toString()
+ deviceSecrets.updateDeviceSecrets()
+ finish()
+ }
+
+ private fun formatNodeREDAddress(url: String): String {
+ var result = url
+ if (!result.contains(":1880")) {
+ if (result.endsWith('/')) result = result.dropLast(1)
+ result += ":1880/"
+ }
+ return result
+ }
+
+ companion object {
+ private val SUPPORTS_DIRECT_VIEW =
+ arrayOf(
+ Global.ESP_EASY,
+ Global.HUE_API,
+ Global.SHELLY_GEN_1,
+ Global.SHELLY_GEN_2,
+ Global.SHELLY_GEN_3,
+ Global.SIMPLE_HOME_API,
+ Global.TASMOTA,
+ )
+ private val HAS_CONFIG =
+ arrayOf(
+ Global.HUE_API,
+ Global.ESP_EASY,
+ Global.NODE_RED,
+ Global.SHELLY_GEN_1,
+ Global.SHELLY_GEN_2,
+ Global.SHELLY_GEN_3,
+ )
+ private val HAS_INFO =
+ arrayOf(
+ Global.HUE_API,
+ Global.SHELLY_GEN_2,
+ Global.SHELLY_GEN_3,
+ )
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/HueConnectActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/HueConnectActivity.kt
new file mode 100644
index 0000000..3eacc02
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/HueConnectActivity.kt
@@ -0,0 +1,76 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.os.Bundle
+import android.util.Log
+import android.widget.Button
+import android.widget.Toast
+import androidx.core.content.edit
+import androidx.preference.PreferenceManager
+import com.android.volley.Request
+import com.android.volley.RequestQueue
+import com.android.volley.toolbox.Volley
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.custom.CustomJsonArrayRequest
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.UpdateHandler
+import org.json.JSONObject
+
+class HueConnectActivity : BaseActivity() {
+ private val updateHandler = UpdateHandler()
+ private var success = false
+ private lateinit var queue: RequestQueue
+ private lateinit var requestToRegisterUser: CustomJsonArrayRequest
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_hue_connect)
+
+ queue = Volley.newRequestQueue(this)
+ val deviceId = intent.getStringExtra("deviceId") ?: ""
+ val jsonRequestObject = JSONObject("""{ "devicetype": "Home App#${android.os.Build.PRODUCT}" }""")
+ requestToRegisterUser =
+ CustomJsonArrayRequest(
+ Request.Method.POST, Devices(this).getDeviceById(deviceId).address + "api", jsonRequestObject,
+ { response ->
+ val responseObject = response.getJSONObject(0)
+ if (responseObject.has("success") && !success) {
+ success = true
+ val username = responseObject.getJSONObject("success").getString("username")
+ PreferenceManager.getDefaultSharedPreferences(this).edit {
+ putString(
+ deviceId,
+ username,
+ )
+ }
+ startActivity(
+ Intent(this, MainActivity::class.java)
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, deviceId)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
+ )
+ }
+ },
+ { error ->
+ Toast.makeText(this, R.string.err, Toast.LENGTH_LONG).show()
+ Log.e(Global.LOG_TAG, error.toString())
+ },
+ )
+
+ findViewById(R.id.cancel_btn).setOnClickListener {
+ finish()
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ updateHandler.setUpdateFunction {
+ if (!success) queue.add(requestToRegisterUser)
+ }
+ }
+
+ override fun onStop() {
+ super.onStop()
+ updateHandler.stop()
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/HueLampActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/HueLampActivity.kt
new file mode 100644
index 0000000..4d5b88d
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/HueLampActivity.kt
@@ -0,0 +1,266 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.content.res.ColorStateList
+import android.graphics.Color
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Bundle
+import android.view.MenuItem
+import android.view.View
+import android.widget.Button
+import android.widget.ImageView
+import android.widget.TextView
+import android.widget.Toast
+import androidx.appcompat.widget.Toolbar
+import androidx.core.content.res.ResourcesCompat
+import androidx.core.widget.ImageViewCompat
+import androidx.viewpager2.widget.ViewPager2
+import com.android.volley.Request
+import com.android.volley.RequestQueue
+import com.android.volley.toolbox.JsonObjectRequest
+import com.android.volley.toolbox.Volley
+import com.google.android.material.appbar.MaterialToolbar
+import com.google.android.material.elevation.SurfaceColors
+import com.google.android.material.slider.Slider
+import com.google.android.material.tabs.TabLayoutMediator
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.HueDetailsTabAdapter
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.LightStates
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.HueLightListener
+import io.github.domi04151309.home.helpers.HueUtils
+import io.github.domi04151309.home.helpers.HueUtils.MIN_COLOR_TEMPERATURE
+import io.github.domi04151309.home.helpers.SliderUtils
+import io.github.domi04151309.home.helpers.UpdateHandler
+import io.github.domi04151309.home.interfaces.HueRoomInterface
+import org.json.JSONArray
+
+class HueLampActivity : BaseActivity(), HueRoomInterface, Toolbar.OnMenuItemClickListener {
+ override var addressPrefix: String = ""
+ override var id: String = ""
+ override var lights: JSONArray? = null
+ override var canReceiveRequest: Boolean = false
+ override var lampData: HueLightListener = HueLightListener()
+ override lateinit var device: DeviceItem
+
+ private var lampName: String = ""
+ private var updateDataRequest: JsonObjectRequest? = null
+ private var updateHandler: UpdateHandler = UpdateHandler()
+
+ private lateinit var hueAPI: HueAPI
+ private lateinit var queue: RequestQueue
+ private lateinit var lampIcon: ImageView
+ private lateinit var nameText: TextView
+ private lateinit var brightnessText: TextView
+ private lateinit var brightnessBar: Slider
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_hue_lamp)
+
+ window.statusBarColor = SurfaceColors.SURFACE_0.getColor(this)
+
+ id = intent.getStringExtra("id") ?: "0"
+ if (intent.hasExtra(Devices.INTENT_EXTRA_DEVICE)) {
+ val extraDevice = intent.getStringExtra(Devices.INTENT_EXTRA_DEVICE) ?: ""
+ val devices = Devices(this)
+ if (devices.idExists(extraDevice)) {
+ device = devices.getDeviceById(extraDevice)
+ } else {
+ Toast.makeText(this, R.string.main_device_nonexistent, Toast.LENGTH_LONG).show()
+ finish()
+ return
+ }
+ }
+
+ hueAPI = HueAPI(this, device.id)
+ addressPrefix = device.address + "api/" + hueAPI.getUsername()
+ queue = Volley.newRequestQueue(this)
+ lampIcon = findViewById(R.id.lampIcon)
+ nameText = findViewById(R.id.nameTxt)
+ brightnessText = findViewById(R.id.briTxt)
+ brightnessBar = findViewById(R.id.briBar)
+
+ setupViews()
+
+ val viewPager = findViewById(R.id.viewPager)
+ viewPager.isUserInputEnabled = false
+ viewPager.adapter = HueDetailsTabAdapter(this, this)
+ viewPager.setCurrentItem(1, false)
+
+ val tabIcons =
+ arrayOf(
+ ResourcesCompat.getDrawable(resources, R.drawable.ic_color_palette, theme),
+ ResourcesCompat.getDrawable(resources, R.drawable.ic_scene_white, theme),
+ ResourcesCompat.getDrawable(resources, R.drawable.ic_device_lamp, theme),
+ )
+ TabLayoutMediator(findViewById(R.id.tabBar), viewPager) { tab, position ->
+ tab.icon = tabIcons[position]
+ }.attach()
+
+ updateDataRequest = getUpdateRequest()
+ updateHandler.setUpdateFunction {
+ if (canReceiveRequest && hueAPI.readyForRequest) {
+ queue.add(updateDataRequest)
+ }
+ }
+
+ findViewById(R.id.toolbar).apply {
+ setNavigationIcon(R.drawable.ic_arrow_back)
+ setNavigationOnClickListener {
+ onBackPressedDispatcher.onBackPressed()
+ }
+ inflateMenu(R.menu.activity_hue_lamp_actions)
+ setOnMenuItemClickListener(this@HueLampActivity)
+ }
+ }
+
+ private fun setupViews() {
+ // Slider labels
+ brightnessBar.setLabelFormatter { value: Float ->
+ HueUtils.briToPercent(value.toInt())
+ }
+
+ // Lamp tint
+ ImageViewCompat.setImageTintList(
+ lampIcon,
+ ColorStateList.valueOf(Color.WHITE),
+ )
+ lampData.addOnDataChangedListener {
+ ImageViewCompat.setImageTintList(
+ lampIcon,
+ ColorStateList.valueOf(
+ if (it.hue != -1 && it.sat != -1) {
+ HueUtils.hueSatToRGB(it.hue, it.sat)
+ } else if (it.ct != -1) {
+ HueUtils.ctToRGB(it.ct + MIN_COLOR_TEMPERATURE)
+ } else {
+ Color.WHITE
+ },
+ ),
+ )
+ }
+
+ findViewById(R.id.onBtn).setOnClickListener {
+ hueAPI.switchGroupById(id, true)
+ }
+
+ findViewById(R.id.offBtn).setOnClickListener {
+ hueAPI.switchGroupById(id, false)
+ }
+
+ brightnessBar.addOnSliderTouchListener(
+ object : Slider.OnSliderTouchListener {
+ override fun onStartTrackingTouch(slider: Slider) {
+ canReceiveRequest = false
+ }
+
+ override fun onStopTrackingTouch(slider: Slider) {
+ hueAPI.changeBrightnessOfGroup(id, slider.value.toInt())
+ canReceiveRequest = true
+ }
+ },
+ )
+ }
+
+ private fun getUpdateRequest() =
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/groups/$id",
+ null,
+ { response ->
+ lights = response.getJSONArray("lights")
+ lampName = response.getString("name")
+ nameText.text = lampName
+ val action = response.getJSONObject("action")
+ val light = LightStates.Light()
+
+ if (action.has("bri")) {
+ SliderUtils.setProgress(brightnessBar, action.getInt("bri"))
+ } else {
+ brightnessText.visibility = View.GONE
+ brightnessBar.visibility = View.GONE
+ }
+ light.ct =
+ if (action.has("ct")) {
+ action.getInt("ct") - MIN_COLOR_TEMPERATURE
+ } else {
+ -1
+ }
+
+ if (action.has("hue") && action.has("sat")) {
+ light.hue = action.getInt("hue")
+ light.sat = action.getInt("sat")
+ } else {
+ light.hue = -1
+ light.sat = -1
+ }
+
+ light.on = response.getJSONObject("state").getBoolean("any_on")
+ brightnessBar.isEnabled = light.on
+
+ lampData.state = light
+ },
+ {
+ canReceiveRequest = false
+ updateHandler.stop()
+ finish()
+ },
+ )
+
+ override fun onStart() {
+ super.onStart()
+ canReceiveRequest = true
+ }
+
+ override fun onStop() {
+ super.onStop()
+ canReceiveRequest = false
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ updateHandler.stop()
+ }
+
+ override fun onColorChanged(color: Int) {
+ ImageViewCompat.setImageTintList(
+ lampIcon,
+ ColorStateList.valueOf(color),
+ )
+ }
+
+ @Suppress("ReturnCount")
+ override fun onMenuItemClick(item: MenuItem): Boolean {
+ if (item.itemId != R.id.action_add_shortcut) return super.onOptionsItemSelected(item)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val shortcutManager = getSystemService(ShortcutManager::class.java) ?: return true
+ if (!shortcutManager.isRequestPinShortcutSupported) {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ return true
+ }
+ val shortcut =
+ ShortcutInfo.Builder(this, device.id + lampName)
+ .setShortLabel(lampName)
+ .setLongLabel(lampName)
+ .setIcon(Icon.createWithResource(this, device.iconId))
+ .setIntent(
+ Intent(this, HueLampActivity::class.java)
+ .putExtra("id", id)
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, device.id)
+ .setAction(Intent.ACTION_MAIN)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
+ )
+ .build()
+ shortcutManager.requestPinShortcut(shortcut, null)
+ } else {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ }
+ return true
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/HueSceneActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/HueSceneActivity.kt
new file mode 100644
index 0000000..22254df
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/HueSceneActivity.kt
@@ -0,0 +1,362 @@
+package io.github.domi04151309.home.activities
+
+import android.os.Bundle
+import android.text.Editable
+import android.text.TextWatcher
+import android.util.Log
+import android.view.View
+import android.widget.TextView
+import android.widget.Toast
+import androidx.core.graphics.toColorInt
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.android.volley.Request
+import com.android.volley.RequestQueue
+import com.android.volley.Response
+import com.android.volley.VolleyError
+import com.android.volley.toolbox.JsonObjectRequest
+import com.android.volley.toolbox.Volley
+import com.google.android.material.appbar.MaterialToolbar
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.google.android.material.elevation.SurfaceColors
+import com.google.android.material.floatingactionbutton.FloatingActionButton
+import com.google.android.material.slider.Slider
+import com.google.android.material.textfield.TextInputLayout
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.HueSceneLampListAdapter
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.custom.CustomJsonArrayRequest
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.LightStates
+import io.github.domi04151309.home.data.SceneListItem
+import io.github.domi04151309.home.fragments.HueColorSheet
+import io.github.domi04151309.home.fragments.HueScenesFragment
+import io.github.domi04151309.home.helpers.ColorUtils
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.HueUtils
+import io.github.domi04151309.home.helpers.HueUtils.MAX_BRIGHTNESS
+import io.github.domi04151309.home.helpers.SliderUtils
+import io.github.domi04151309.home.interfaces.HueAdvancedLampInterface
+import io.github.domi04151309.home.interfaces.SceneRecyclerViewHelperInterface
+import org.json.JSONArray
+import org.json.JSONObject
+
+@Suppress("TooManyFunctions")
+class HueSceneActivity :
+ BaseActivity(),
+ SceneRecyclerViewHelperInterface,
+ HueAdvancedLampInterface,
+ Response.Listener,
+ Response.ErrorListener {
+ private var editing = false
+ private val lightStates = LightStates()
+ private val listItems = mutableListOf()
+ private var groupId = "0"
+ private var sceneId = ""
+ private var defaultText = ""
+ private lateinit var hueAPI: HueAPI
+ private lateinit var adapter: HueSceneLampListAdapter
+ private lateinit var queue: RequestQueue
+ private lateinit var nameBox: TextInputLayout
+ private lateinit var briBar: Slider
+
+ override var id: String = ""
+ override var canReceiveRequest: Boolean = true
+ override lateinit var device: DeviceItem
+ override lateinit var addressPrefix: String
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_hue_scene)
+
+ window.statusBarColor = SurfaceColors.SURFACE_0.getColor(this)
+
+ val nameTxt = findViewById(R.id.nameTxt)
+
+ device = Devices(this).getDeviceById(intent.getStringExtra("deviceId") ?: "")
+ hueAPI = HueAPI(this, device.id)
+ addressPrefix = device.address +
+ "api/" + hueAPI.getUsername()
+ queue = Volley.newRequestQueue(this)
+ nameBox = findViewById(R.id.nameBox)
+ briBar = findViewById(R.id.briBar)
+
+ editing = intent.hasExtra("scene")
+ adapter = HueSceneLampListAdapter(listItems, this)
+ groupId = intent.getStringExtra("room") ?: "0"
+ sceneId = intent.getStringExtra("scene") ?: ""
+
+ findViewById(R.id.recyclerView).apply {
+ layoutManager = LinearLayoutManager(this@HueSceneActivity)
+ adapter = this@HueSceneActivity.adapter
+ }
+ briBar.setLabelFormatter { value: Float ->
+ HueUtils.briToPercent(value.toInt())
+ }
+
+ if (editing) {
+ onEditScene()
+ } else {
+ onCreateScene()
+ }
+
+ nameBox.editText?.addTextChangedListener(
+ object : TextWatcher {
+ override fun afterTextChanged(s: Editable) {
+ // Do nothing.
+ }
+
+ override fun beforeTextChanged(
+ s: CharSequence,
+ start: Int,
+ count: Int,
+ after: Int,
+ ) {
+ // Do nothing.
+ }
+
+ override fun onTextChanged(
+ s: CharSequence,
+ start: Int,
+ before: Int,
+ count: Int,
+ ) {
+ val string = s.toString()
+ if (string == "") {
+ nameTxt.text = defaultText
+ } else {
+ nameTxt.text = string
+ }
+ }
+ },
+ )
+
+ briBar.addOnSliderTouchListener(
+ object : Slider.OnSliderTouchListener {
+ override fun onStartTrackingTouch(slider: Slider) {
+ // Do nothing.
+ }
+
+ override fun onStopTrackingTouch(slider: Slider) {
+ hueAPI.changeBrightnessOfGroup(groupId, slider.value.toInt())
+ adapter.changeSceneBrightness(HueUtils.briToPercent(slider.value.toInt()))
+ lightStates.setSceneBrightness(slider.value.toInt())
+ }
+ },
+ )
+
+ findViewById(R.id.fab).setOnClickListener {
+ onFloatingActionButtonClicked()
+ }
+
+ findViewById(R.id.toolbar).apply {
+ setNavigationIcon(R.drawable.ic_arrow_back)
+ setNavigationOnClickListener {
+ onBackPressedDispatcher.onBackPressed()
+ }
+ }
+ }
+
+ private fun onEditScene() {
+ defaultText = resources.getString(R.string.hue_scene)
+ hueAPI.activateSceneOfGroup(groupId, sceneId)
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/scenes/$sceneId",
+ null,
+ { response ->
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/lights",
+ null,
+ { secondResponse ->
+ nameBox.editText?.setText(response.optString("name"))
+ val lights =
+ response.optJSONObject("lightstates") ?: JSONObject()
+ var lightObj: JSONObject
+ val brightness = Array(2) { 0 }
+ for (i in lights.keys()) {
+ lightObj = lights.getJSONObject(i)
+ lightStates.addLight(i, lightObj)
+ listItems +=
+ generateListItem(
+ i,
+ (secondResponse.optJSONObject(i) ?: JSONObject())
+ .optString("name"),
+ lightObj,
+ )
+ if (lightObj.has("bri")) {
+ brightness[0] += lightObj.getInt("bri")
+ brightness[1]++
+ }
+ }
+
+ SliderUtils.setProgress(
+ briBar,
+ if (brightness[1] > 0) brightness[0] / brightness[1] else 0,
+ )
+ listItems.sortBy { it.title }
+ adapter.notifyDataSetChanged()
+ },
+ this,
+ ),
+ )
+ },
+ this,
+ ),
+ )
+ }
+
+ private fun onCreateScene() {
+ defaultText = resources.getString(R.string.hue_new_scene)
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/groups/$groupId",
+ null,
+ { response ->
+ val lightIds = response.getJSONArray("lights")
+ SliderUtils.setProgress(
+ briBar,
+ (response.optJSONObject("action") ?: JSONObject()).optInt("bri"),
+ )
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "$addressPrefix/lights",
+ null,
+ { secondResponse ->
+ var lightObj: JSONObject
+ for (i in 0 until lightIds.length()) {
+ lightObj =
+ secondResponse.getJSONObject(lightIds.getString(i))
+ val state = lightObj.getJSONObject("state")
+ listItems +=
+ generateListItem(
+ lightIds.getString(i),
+ lightObj.getString("name"),
+ state,
+ )
+ }
+
+ listItems.sortBy { it.title }
+ adapter.notifyDataSetChanged()
+ },
+ this,
+ ),
+ )
+ },
+ this,
+ ),
+ )
+ }
+
+ private fun generateListItem(
+ id: String,
+ title: String,
+ state: JSONObject,
+ ): SceneListItem =
+ SceneListItem(
+ title,
+ id,
+ state.optBoolean("on"),
+ HueUtils.briToPercent(state.optInt("bri", MAX_BRIGHTNESS)),
+ if (state.has("xy")) {
+ val xyArray = state.getJSONArray("xy")
+ ColorUtils.xyToRGB(
+ xyArray.getDouble(0),
+ xyArray.getDouble(1),
+ )
+ } else if (state.has("hue") && state.has("sat")) {
+ HueUtils.hueSatToRGB(state.getInt("hue"), state.getInt("sat"))
+ } else if (state.has("ct")) {
+ HueUtils.ctToRGB(state.getInt("ct"))
+ } else {
+ "#FFFFFF".toColorInt()
+ },
+ )
+
+ private fun onFloatingActionButtonClicked() {
+ val name = nameBox.editText?.text.toString()
+ if (name == "") {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.err_missing_name)
+ .setMessage(R.string.err_missing_name_summary)
+ .setPositiveButton(android.R.string.ok) { _, _ -> }
+ .show()
+ return
+ }
+ queue.add(
+ if (editing) {
+ CustomJsonArrayRequest(
+ Request.Method.PUT,
+ "$addressPrefix/scenes/$sceneId",
+ JSONObject("""{ "name": "$name", "lightstates": $lightStates }"""),
+ this,
+ this,
+ )
+ } else {
+ CustomJsonArrayRequest(
+ Request.Method.POST,
+ "$addressPrefix/scenes",
+ JSONObject(
+ """{ "name": "$name", "recycle": false, "group": "$groupId", "type": "GroupScene" }""",
+ ),
+ this,
+ this,
+ )
+ },
+ )
+ }
+
+ override fun onResponse(response: JSONArray) {
+ HueScenesFragment.scenesChanged = true
+ finish()
+ }
+
+ override fun onErrorResponse(error: VolleyError) {
+ Toast.makeText(this, Global.volleyError(this, error), Toast.LENGTH_LONG).show()
+ Log.e(Global.LOG_TAG, error.toString())
+ }
+
+ override fun onItemClicked(
+ view: View,
+ data: SceneListItem,
+ ) {
+ id = data.hidden
+ HueColorSheet(this).show(supportFragmentManager, HueColorSheet::class.simpleName)
+ }
+
+ override fun onStateChanged(
+ view: View,
+ data: SceneListItem,
+ state: Boolean,
+ ) {
+ hueAPI.switchLightById(data.hidden, state)
+ lightStates.switchLight(data.hidden, state)
+ }
+
+ override fun onColorChanged(color: Int) {
+ adapter.updateColor(id, color)
+ }
+
+ override fun onBrightnessChanged(brightness: Int) {
+ lightStates.setLightBrightness(id, brightness)
+ adapter.updateBrightness(id, HueUtils.briToPercent(brightness))
+ }
+
+ override fun onHueSatChanged(
+ hue: Int,
+ sat: Int,
+ ) {
+ lightStates.setLightHue(id, hue)
+ lightStates.setLightSat(id, sat)
+ }
+
+ override fun onCtChanged(ct: Int) {
+ lightStates.setLightCt(id, ct)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/LibraryActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/LibraryActivity.kt
new file mode 100644
index 0000000..e835837
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/LibraryActivity.kt
@@ -0,0 +1,45 @@
+package io.github.domi04151309.home.activities
+
+import android.os.Bundle
+import androidx.core.content.res.ResourcesCompat
+import androidx.preference.Preference
+import androidx.preference.PreferenceFragmentCompat
+import io.github.domi04151309.home.R
+
+class LibraryActivity : BaseActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_settings)
+ supportFragmentManager
+ .beginTransaction()
+ .replace(R.id.settings, GeneralPreferenceFragment())
+ .commit()
+ }
+
+ class GeneralPreferenceFragment : PreferenceFragmentCompat() {
+ override fun onCreatePreferences(
+ savedInstanceState: Bundle?,
+ rootKey: String?,
+ ) {
+ addPreferencesFromResource(R.xml.pref_about_list)
+ preferenceScreen.removeAll()
+ val libraries = resources.getStringArray(R.array.about_libraries)
+ val licenses = resources.getStringArray(R.array.about_libraries_licenses)
+ if (libraries.size != licenses.size) error("Library array size does not match license array size.")
+ for (index in libraries.indices) {
+ preferenceScreen.addPreference(
+ Preference(requireContext()).apply {
+ icon =
+ ResourcesCompat.getDrawable(
+ requireContext().resources,
+ R.drawable.ic_about_library,
+ requireContext().theme,
+ )
+ title = libraries[index]
+ summary = licenses[index]
+ },
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/MainActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/MainActivity.kt
new file mode 100644
index 0000000..32aacf3
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/MainActivity.kt
@@ -0,0 +1,616 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.os.Bundle
+import android.text.TextUtils
+import android.util.DisplayMetrics
+import android.view.ContextMenu
+import android.view.Gravity
+import android.view.MenuItem
+import android.view.View
+import android.view.animation.AnimationUtils
+import android.widget.FrameLayout
+import android.widget.ImageSwitcher
+import android.widget.ImageView
+import android.widget.TextSwitcher
+import android.widget.TextView
+import android.widget.Toast
+import androidx.activity.addCallback
+import androidx.core.content.ContextCompat
+import androidx.preference.PreferenceManager
+import androidx.recyclerview.widget.GridLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.appbar.MaterialToolbar
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.google.android.material.elevation.SurfaceColors
+import com.google.android.material.floatingactionbutton.FloatingActionButton
+import com.google.android.material.snackbar.Snackbar
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.MainListAdapter
+import io.github.domi04151309.home.api.UnifiedAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.Global.checkNetwork
+import io.github.domi04151309.home.helpers.P
+import io.github.domi04151309.home.helpers.TasmotaHelper
+import io.github.domi04151309.home.helpers.UpdateHandler
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import kotlin.math.max
+import kotlin.math.min
+
+@Suppress("TooManyFunctions")
+class MainActivity : BaseActivity() {
+ private var tasmotaPosition: Int = 0
+ private var shouldReset: Boolean = false
+ private val updateHandler = UpdateHandler()
+ private var isDeviceSelected = false
+ private var canReceiveRequest = false
+ private var currentView: View? = null
+ internal lateinit var devices: Devices
+ internal lateinit var adapter: MainListAdapter
+ private lateinit var deviceIcon: ImageSwitcher
+ private lateinit var deviceName: TextSwitcher
+ private lateinit var fab: FloatingActionButton
+
+ private var columns: Int? = null
+
+ /*
+ * Unified callbacks
+ */
+ private var unified: UnifiedAPI? = null
+ private val unifiedRequestCallback =
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ if (holder.response != null) {
+ val device = devices.getDeviceById(holder.deviceId)
+ deviceIcon.setImageResource(device.iconId)
+ deviceName.setText(device.name)
+ adapter.updateData(holder.response, recyclerViewInterface)
+ fab.hide()
+ isDeviceSelected = true
+ } else {
+ if (currentView == null) {
+ loadDeviceList()
+ Toast.makeText(this@MainActivity, holder.errorMessage, Toast.LENGTH_LONG).show()
+ } else {
+ currentView?.findViewById(R.id.summary)?.text = holder.errorMessage
+ }
+ }
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ showExecutionResult(result)
+ if (shouldRefresh) unified?.loadList(this)
+ }
+ }
+ private val unifiedHelperInterface =
+ object : HomeRecyclerViewHelperInterface {
+ override fun onStateChanged(
+ view: View,
+ data: ListViewItem,
+ state: Boolean,
+ ) {
+ if (data.hidden.isEmpty()) return
+ unified?.changeSwitchState(data.hidden, state)
+ }
+
+ override fun onItemClicked(
+ view: View,
+ data: ListViewItem,
+ ) {
+ unified?.execute(data.hidden, unifiedRequestCallback)
+ }
+ }
+ private val unifiedRealTimeStatesCallback =
+ object : UnifiedAPI.RealTimeStatesCallback {
+ override fun onStatesLoaded(
+ states: List,
+ offset: Int,
+ ) {
+ for (i in states.indices) {
+ adapter.updateItem(
+ i + offset,
+ states[i],
+ )
+ }
+ }
+ }
+
+ /*
+ * Things related to Tasmota
+ */
+ private val tasmotaHelperInterface =
+ object : HomeRecyclerViewHelperInterface {
+ override fun onStateChanged(
+ view: View,
+ data: ListViewItem,
+ state: Boolean,
+ ) {
+ // Do nothing.
+ }
+
+ override fun onItemClicked(
+ view: View,
+ data: ListViewItem,
+ ) {
+ val helper = TasmotaHelper(this@MainActivity, unified ?: return)
+ when (data.hidden) {
+ "add" -> helper.addToList(unifiedRequestCallback)
+ "execute_once" -> helper.executeOnce(unifiedRequestCallback)
+ else ->
+ unified?.execute(
+ view.findViewById(R.id.summary).text.toString(),
+ unifiedRequestCallback,
+ )
+ }
+ }
+ }
+
+ /*
+ * Things related to the main menu
+ */
+ private val mainHelperInterface =
+ object : HomeRecyclerViewHelperInterface {
+ override fun onStateChanged(
+ view: View,
+ data: ListViewItem,
+ state: Boolean,
+ ) {
+ if (data.hidden.isEmpty()) return
+
+ val deviceId = data.hidden.substring(0, data.hidden.indexOf('@'))
+ Global.getCorrectAPI(
+ this@MainActivity,
+ devices.getDeviceById(deviceId).mode,
+ deviceId,
+ ).changeSwitchState(data.hidden.substring(deviceId.length + 1), state)
+ }
+
+ override fun onItemClicked(
+ view: View,
+ data: ListViewItem,
+ ) {
+ currentView = view
+ if (data.title == resources.getString(R.string.main_no_devices)) {
+ startActivityAndReset(Intent(this@MainActivity, DevicesActivity::class.java))
+ } else if (data.title == resources.getString(R.string.err_wrong_format)) {
+ startActivityAndReset(Intent(this@MainActivity, SettingsActivity::class.java))
+ } else if (data.hidden.contains('@')) {
+ val deviceId = data.hidden.substring(0, data.hidden.indexOf('@'))
+ val api = Global.getCorrectAPI(this@MainActivity, devices.getDeviceById(deviceId).mode, deviceId)
+ api.execute(
+ data.hidden.substring(deviceId.length + 1),
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ // Do nothing.
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ showExecutionResult(result)
+ if (shouldRefresh) {
+ api.loadList(
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ adapter.updateDirectView(
+ deviceId,
+ holder.response ?: listOf(),
+ adapter.getDirectViewPos(deviceId),
+ )
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ // Do nothing.
+ }
+ },
+ )
+ }
+ }
+ },
+ )
+ } else {
+ if (checkNetwork(this@MainActivity)) {
+ view.findViewById(R.id.summary).text =
+ resources.getString(R.string.main_connecting)
+ selectDevice(data.hidden)
+ } else {
+ view.findViewById(R.id.summary).text =
+ resources.getString(R.string.main_network_not_secure)
+ }
+ }
+ }
+ }
+
+ private fun getColumns(): Int? =
+ (
+ PreferenceManager.getDefaultSharedPreferences(this)
+ .getString(P.PREF_COLUMNS, P.PREF_COLUMNS_DEFAULT)
+ ?: P.PREF_COLUMNS_DEFAULT
+ ).toIntOrNull()
+
+ /*
+ * Activity methods
+ */
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_main)
+
+ window.statusBarColor = SurfaceColors.SURFACE_0.getColor(this)
+
+ val recyclerView = findViewById(R.id.recyclerView)
+ devices = Devices(this)
+ deviceIcon = findViewById(R.id.deviceIcon)
+ deviceName = findViewById(R.id.deviceName)
+ fab = findViewById(R.id.fab)
+ columns = getColumns()
+
+ setupHeader()
+
+ adapter = MainListAdapter(recyclerView)
+ recyclerView.layoutManager = GridLayoutManager(this, numberOfRows())
+ recyclerView.adapter = adapter
+
+ fab.setOnClickListener {
+ startActivityAndReset(Intent(this, DevicesActivity::class.java))
+ }
+
+ findViewById(R.id.toolbar).setOnMenuItemClickListener {
+ startActivity(
+ Intent(
+ this@MainActivity,
+ SettingsActivity::class.java,
+ ),
+ )
+ true
+ }
+
+ // Handle shortcut
+ if (intent.hasExtra(Devices.INTENT_EXTRA_DEVICE)) {
+ val deviceId = intent.getStringExtra(Devices.INTENT_EXTRA_DEVICE) ?: ""
+ if (devices.idExists(deviceId)) {
+ if (checkNetwork(this)) {
+ val device = devices.getDeviceById(deviceId)
+ deviceIcon.setImageResource(device.iconId)
+ deviceName.setText(device.name)
+ selectDevice(deviceId)
+ } else {
+ loadDeviceList()
+ Toast.makeText(this, R.string.main_network_not_secure, Toast.LENGTH_LONG)
+ .show()
+ }
+ } else {
+ loadDeviceList()
+ Toast.makeText(this, R.string.main_device_nonexistent, Toast.LENGTH_LONG).show()
+ }
+ } else {
+ loadDeviceList()
+ }
+
+ onBackPressedDispatcher.addCallback {
+ if (isDeviceSelected) {
+ loadDeviceList()
+ } else {
+ finish()
+ }
+ }
+ }
+
+ private fun setupHeader() {
+ deviceIcon.setFactory {
+ val view = ImageView(this@MainActivity)
+ view.layoutParams =
+ FrameLayout.LayoutParams(
+ FrameLayout.LayoutParams.MATCH_PARENT,
+ FrameLayout.LayoutParams.MATCH_PARENT,
+ )
+ view
+ }
+ deviceName.setFactory {
+ val view = TextView(this@MainActivity)
+ view.layoutParams =
+ FrameLayout.LayoutParams(
+ FrameLayout.LayoutParams.MATCH_PARENT,
+ FrameLayout.LayoutParams.MATCH_PARENT,
+ )
+ view.setTextAppearance(androidx.appcompat.R.style.TextAppearance_AppCompat_Large)
+ view.setTextColor(ContextCompat.getColor(this, android.R.color.white))
+ view.gravity = Gravity.CENTER_VERTICAL
+ view.ellipsize = TextUtils.TruncateAt.END
+ view.maxLines = 1
+ view
+ }
+
+ val inAnimation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in)
+ val outAnimation = AnimationUtils.loadAnimation(this, android.R.anim.fade_out)
+ inAnimation.duration /= 2
+ outAnimation.duration /= 2
+ deviceIcon.inAnimation = inAnimation
+ deviceIcon.outAnimation = outAnimation
+ deviceName.inAnimation = inAnimation
+ deviceName.outAnimation = outAnimation
+ }
+
+ override fun onCreateContextMenu(
+ menu: ContextMenu?,
+ v: View?,
+ menuInfo: ContextMenu.ContextMenuInfo?,
+ ) {
+ super.onCreateContextMenu(menu, v, menuInfo)
+ val hidden = v?.findViewById(R.id.hidden)?.text ?: return
+ if (hidden.contains("tasmota_command")) {
+ tasmotaPosition = hidden.substring(hidden.lastIndexOf('#') + 1).toInt()
+ menuInflater.inflate(R.menu.activity_main_tasmota_context, menu)
+ }
+ }
+
+ override fun onContextItemSelected(item: MenuItem): Boolean {
+ val helper = TasmotaHelper(this, unified ?: return super.onContextItemSelected(item))
+ return when (item.title) {
+ resources.getString(R.string.str_edit) -> {
+ helper.updateItem(unifiedRequestCallback, tasmotaPosition)
+ true
+ }
+ resources.getString(R.string.str_delete) -> {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.str_delete)
+ .setMessage(R.string.tasmota_delete_command)
+ .setPositiveButton(R.string.str_delete) { _, _ ->
+ helper.removeFromList(unifiedRequestCallback, tasmotaPosition)
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ true
+ }
+ else -> {
+ super.onContextItemSelected(item)
+ }
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ if (getColumns() != columns) {
+ columns = getColumns()
+ recreate()
+ }
+ if (shouldReset) {
+ loadDeviceList()
+ shouldReset = false
+ }
+ canReceiveRequest = true
+ }
+
+ override fun onStop() {
+ super.onStop()
+ canReceiveRequest = false
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ updateHandler.stop()
+ }
+
+ private fun numberOfRows(): Int {
+ if (columns != null) return columns ?: 1
+ val displayMetrics: DisplayMetrics = resources.displayMetrics
+ val horizontal: Int =
+ (
+ displayMetrics.widthPixels / displayMetrics.density / COLUMN_COUNT_FRACTION
+ ).toInt()
+ val vertical: Int =
+ (
+ displayMetrics.heightPixels / displayMetrics.density / COLUMN_COUNT_FRACTION
+ ).toInt()
+ return max(1, min(horizontal, vertical))
+ }
+
+ internal fun selectDevice(deviceId: String) {
+ val deviceObj = devices.getDeviceById(deviceId)
+ when {
+ WEB_MODES.contains(deviceObj.mode) -> {
+ val intent =
+ Intent(this, WebActivity::class.java)
+ .putExtra("title", deviceObj.name)
+
+ when (deviceObj.mode) {
+ Global.FRITZ_AUTO_LOGIN -> {
+ intent.putExtra("URI", deviceObj.address)
+ intent.putExtra("fritz_auto_login", deviceObj.id)
+ }
+ Global.GRAFANA_AUTO_LOGIN -> {
+ intent.putExtra("URI", deviceObj.address)
+ intent.putExtra("grafana_auto_login", deviceObj.id)
+ }
+ Global.PI_HOLE_AUTO_LOGIN -> {
+ intent.putExtra("URI", deviceObj.address)
+ intent.putExtra("pi_hole_auto_login", deviceObj.id)
+ }
+ Global.NODE_RED -> {
+ intent.putExtra("URI", deviceObj.address + "ui/")
+ }
+ Global.WEBSITE -> {
+ intent.putExtra("URI", deviceObj.address)
+ }
+ }
+ startActivityAndReset(intent)
+ }
+ Global.UNIFIED_MODES.contains(deviceObj.mode) -> {
+ unified =
+ Global.getCorrectAPI(
+ this,
+ deviceObj.mode,
+ deviceId,
+ unifiedHelperInterface,
+ tasmotaHelperInterface,
+ )
+ unified?.loadList(unifiedRequestCallback, true)
+ updateHandler.setUpdateFunction {
+ if (canReceiveRequest && unified?.needsRealTimeData == true) {
+ unified?.loadStates(unifiedRealTimeStatesCallback, 0)
+ }
+ }
+ }
+ else -> {
+ Toast.makeText(this, R.string.main_unknown_mode, Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+
+ private fun onDirectView(
+ currentDevice: DeviceItem,
+ position: Int,
+ registeredForUpdates: HashMap,
+ ) {
+ val api = Global.getCorrectAPI(this, currentDevice.mode, currentDevice.id)
+ api.loadList(
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ if (holder.response != null) {
+ Thread {
+ while (!updateHandler.running) Thread.sleep(TINY_DELAY)
+ runOnUiThread {
+ adapter.updateDirectView(
+ currentDevice.id,
+ holder.response,
+ position,
+ )
+ }
+ registeredForUpdates[position] = api
+ }.start()
+ }
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ // Do nothing.
+ }
+ },
+ )
+ }
+
+ private fun getDeviceItem(device: DeviceItem) =
+ ListViewItem(
+ title = device.name,
+ summary = resources.getString(R.string.main_tap_to_connect),
+ hidden = device.id,
+ icon = device.iconId,
+ )
+
+ private fun updateStates(registeredForUpdates: HashMap) {
+ if (canReceiveRequest) {
+ for (i in registeredForUpdates.keys) {
+ if (registeredForUpdates[i]?.needsRealTimeData == true) {
+ registeredForUpdates[i]?.loadStates(
+ unifiedRealTimeStatesCallback,
+ adapter.getOffset(i),
+ )
+ }
+ }
+ }
+ }
+
+ internal fun loadDeviceList() {
+ updateHandler.stop()
+ val registeredForUpdates: HashMap = hashMapOf()
+ val listItems: ArrayList = ArrayList(devices.length)
+
+ if (devices.length == 0) {
+ listItems +=
+ ListViewItem(
+ title = resources.getString(R.string.main_no_devices),
+ summary = resources.getString(R.string.main_no_devices_summary),
+ icon = R.drawable.ic_info,
+ )
+ }
+ var actualPosition = 0
+ for (i in 0 until devices.length) {
+ val currentDevice = devices.getDeviceByIndex(i)
+ if (!currentDevice.hide) {
+ if (
+ currentDevice.directView &&
+ Global.UNIFIED_MODES.contains(currentDevice.mode) &&
+ checkNetwork(this)
+ ) {
+ onDirectView(currentDevice, actualPosition, registeredForUpdates)
+ }
+ listItems += getDeviceItem(currentDevice)
+ actualPosition++
+ }
+ }
+
+ adapter.updateData(listItems, mainHelperInterface)
+ deviceIcon.setImageResource(R.drawable.ic_home_white)
+ deviceName.setText(resources.getString(R.string.main_device_name))
+ fab.show()
+ isDeviceSelected = false
+ updateHandler.setUpdateFunction {
+ updateStates(registeredForUpdates)
+ }
+ unified = null
+ }
+
+ internal fun startActivityAndReset(intent: Intent) {
+ shouldReset = true
+ startActivity(intent)
+ }
+
+ internal fun showExecutionResult(result: String) {
+ if (result.length < MAX_RESPONSE_LENGTH) {
+ Toast.makeText(this, result, Toast.LENGTH_LONG).show()
+ } else {
+ Snackbar
+ .make(
+ findViewById(android.R.id.content),
+ R.string.main_execution_completed,
+ Snackbar.LENGTH_LONG,
+ )
+ .setAction(R.string.str_show) {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.main_execution_completed)
+ .setMessage(result)
+ .setPositiveButton(android.R.string.ok) { _, _ -> }
+ .show()
+ }
+ .show()
+ }
+ }
+
+ companion object {
+ private val WEB_MODES =
+ arrayOf(
+ Global.FRITZ_AUTO_LOGIN,
+ Global.GRAFANA_AUTO_LOGIN,
+ Global.PI_HOLE_AUTO_LOGIN,
+ Global.NODE_RED,
+ Global.WEBSITE,
+ )
+ private const val TINY_DELAY = 100L
+ private const val COLUMN_COUNT_FRACTION = 240
+ private const val MAX_RESPONSE_LENGTH = 64
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/SearchDevicesActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/SearchDevicesActivity.kt
new file mode 100644
index 0000000..dbdd011
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/SearchDevicesActivity.kt
@@ -0,0 +1,118 @@
+package io.github.domi04151309.home.activities
+
+import android.net.nsd.NsdManager
+import android.net.wifi.WifiManager
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.rine.upnpdiscovery.UPnPDiscovery
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.DeviceDiscoveryListAdapter
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.discovery.NetworkServiceDiscoveryListener
+import io.github.domi04151309.home.discovery.NetworkServiceResolveListener
+import io.github.domi04151309.home.discovery.UPnPListener
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class SearchDevicesActivity : BaseActivity(), RecyclerViewHelperInterface {
+ private lateinit var adapter: DeviceDiscoveryListAdapter
+ private lateinit var devices: Devices
+ private lateinit var nsdManager: NsdManager
+ private lateinit var discoveryListenerHttp: NsdManager.DiscoveryListener
+ private lateinit var discoveryListenerSimpleHome: NsdManager.DiscoveryListener
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_devices)
+
+ val recyclerView = findViewById(R.id.recyclerView)
+ adapter =
+ DeviceDiscoveryListAdapter(
+ mutableListOf(
+ ListViewItem(
+ title = resources.getString(R.string.pref_add_search),
+ summary = resources.getString(R.string.pref_add_search_summary),
+ icon = R.drawable.ic_search,
+ ),
+ ),
+ this,
+ )
+ devices = Devices(this)
+
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ recyclerView.adapter = adapter
+
+ // Device variables
+ val manager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
+ val routerIp = intToIp(manager.dhcpInfo.gateway)
+
+ Thread {
+ // Add Router
+ adapter.add(
+ ListViewItem(
+ title = resources.getString(R.string.pref_device_router),
+ summary = routerIp,
+ hidden = "Website#Router",
+ icon = R.drawable.ic_device_router,
+ state = devices.addressExists(routerIp),
+ ),
+ )
+
+ // Get compatible devices
+ UPnPDiscovery.discoveryDevices(
+ this,
+ UPnPListener(this, adapter),
+ )
+ }.start()
+
+ val resolveListener = NetworkServiceResolveListener(this, adapter)
+ nsdManager = getSystemService(NSD_SERVICE) as NsdManager
+ discoveryListenerHttp = NetworkServiceDiscoveryListener(this, resolveListener)
+ discoveryListenerSimpleHome = NetworkServiceDiscoveryListener(this, resolveListener)
+ nsdManager.discoverServices("_http._tcp", NsdManager.PROTOCOL_DNS_SD, discoveryListenerHttp)
+ nsdManager.discoverServices("_simplehome._tcp", NsdManager.PROTOCOL_DNS_SD, discoveryListenerSimpleHome)
+ }
+
+ @Suppress("MagicNumber")
+ private fun intToIp(address: Int): String =
+ (address and 0xFF).toString() + "." + (address shr 8 and 0xFF) + "." +
+ (address shr 16 and 0xFF) + "." + (address shr 24 and 0xFF)
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ val name = view.findViewById(R.id.title).text.toString()
+ val hidden = view.findViewById(R.id.hidden).text.toString()
+ if (hidden != "") {
+ MaterialAlertDialogBuilder(this)
+ .setTitle(R.string.pref_add_dialog)
+ .setMessage(resources.getString(R.string.pref_add_dialog_message, name))
+ .setPositiveButton(R.string.str_add) { _, _ ->
+ val newItem =
+ DeviceItem(
+ devices.generateNewId(),
+ name,
+ hidden.substring(0, hidden.indexOf('#')),
+ hidden.substring(hidden.lastIndexOf('#') + 1),
+ )
+ newItem.address = view.findViewById(R.id.summary).text.toString()
+ devices.addDevice(newItem)
+ adapter.changeState(position, true)
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ }
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ nsdManager.stopServiceDiscovery(discoveryListenerHttp)
+ nsdManager.stopServiceDiscovery(discoveryListenerSimpleHome)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/SettingsActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/SettingsActivity.kt
new file mode 100644
index 0000000..7a12359
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/SettingsActivity.kt
@@ -0,0 +1,82 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.os.Build
+import android.os.Bundle
+import android.widget.Toast
+import androidx.core.content.edit
+import androidx.core.net.toUri
+import androidx.preference.Preference
+import androidx.preference.PreferenceFragmentCompat
+import androidx.preference.PreferenceManager
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.P
+
+class SettingsActivity : BaseActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_settings)
+ supportFragmentManager
+ .beginTransaction()
+ .replace(R.id.settings, GeneralPreferenceFragment())
+ .commit()
+ }
+
+ class GeneralPreferenceFragment : PreferenceFragmentCompat() {
+ override fun onCreatePreferences(
+ savedInstanceState: Bundle?,
+ rootKey: String?,
+ ) {
+ addPreferencesFromResource(R.xml.pref_general)
+ findPreference(P.PREF_CONTROLS_AUTH)?.isVisible =
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
+ findPreference("devices")?.setOnPreferenceClickListener {
+ startActivity(Intent(context, DevicesActivity::class.java))
+ true
+ }
+ findPreference("devices_json")?.setOnPreferenceClickListener {
+ Devices.reloadFromPreferences()
+ true
+ }
+ findPreference("reset_json")?.setOnPreferenceClickListener {
+ MaterialAlertDialogBuilder(requireContext())
+ .setTitle(R.string.pref_reset)
+ .setMessage(R.string.pref_reset_question)
+ .setPositiveButton(R.string.str_delete) { _, _ ->
+ PreferenceManager.getDefaultSharedPreferences(requireContext()).edit {
+ putString("devices_json", Global.DEFAULT_JSON)
+ }
+ Toast.makeText(context, R.string.pref_reset_toast, Toast.LENGTH_LONG).show()
+ Devices.reloadFromPreferences()
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ true
+ }
+ findPreference("about")?.setOnPreferenceClickListener {
+ startActivity(Intent(context, AboutActivity::class.java))
+ true
+ }
+ findPreference("wiki")?.setOnPreferenceClickListener {
+ val uri = "https://github.com/Domi04151309/HomeApp/wiki"
+ startActivity(
+ Intent(context, WebActivity::class.java).putExtra("URI", uri)
+ .putExtra("title", resources.getString(R.string.pref_info_wiki)),
+ )
+ true
+ }
+ findPreference("header")?.setOnPreferenceClickListener {
+ startActivity(
+ Intent(
+ Intent.ACTION_VIEW,
+ "https://unsplash.com/photos/mx4mSkK9zeo".toUri(),
+ ),
+ )
+ true
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ShortcutDeviceActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutDeviceActivity.kt
new file mode 100644
index 0000000..8603a5a
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutDeviceActivity.kt
@@ -0,0 +1,82 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Bundle
+import android.view.View
+import android.widget.Toast
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.SimpleListAdapter
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class ShortcutDeviceActivity : BaseActivity(), RecyclerViewHelperInterface {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_devices)
+
+ val devices = Devices(this)
+ val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
+ val listItems: ArrayList = ArrayList(devices.length)
+ var currentDevice: DeviceItem
+ for (i in 0 until devices.length) {
+ currentDevice = devices.getDeviceByIndex(i)
+ listItems +=
+ SimpleListItem(
+ title = currentDevice.name,
+ summary = currentDevice.address,
+ hidden = currentDevice.id,
+ icon = currentDevice.iconId,
+ )
+ }
+
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ recyclerView.adapter = SimpleListAdapter(listItems, this)
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ val device = Devices(this).getDeviceByIndex(position)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val shortcutManager = this.getSystemService(ShortcutManager::class.java)
+ if (shortcutManager != null) {
+ setResult(
+ RESULT_OK,
+ shortcutManager.createShortcutResultIntent(
+ ShortcutInfo.Builder(this, device.id)
+ .setShortLabel(
+ device.name.ifEmpty {
+ resources.getString(R.string.pref_add_name_empty)
+ },
+ )
+ .setLongLabel(
+ device.name.ifEmpty {
+ resources.getString(R.string.pref_add_name_empty)
+ },
+ )
+ .setIcon(Icon.createWithResource(this, device.iconId))
+ .setIntent(
+ Intent(this, MainActivity::class.java)
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, device.id)
+ .setAction(Intent.ACTION_MAIN)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
+ )
+ .build(),
+ ),
+ )
+ finish()
+ }
+ } else {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueRoomActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueRoomActivity.kt
new file mode 100644
index 0000000..880ce7b
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueRoomActivity.kt
@@ -0,0 +1,122 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import android.widget.Toast
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.SimpleListAdapter
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.api.UnifiedAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class ShortcutHueRoomActivity : BaseActivity(), RecyclerViewHelperInterface {
+ private var deviceId: String? = null
+ private lateinit var recyclerView: RecyclerView
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_devices)
+
+ recyclerView = findViewById(R.id.recyclerView)
+
+ val devices = Devices(this)
+ val listItems: ArrayList = ArrayList(devices.length)
+ var currentDevice: DeviceItem
+ for (i in 0 until devices.length) {
+ currentDevice = devices.getDeviceByIndex(i)
+ if (currentDevice.mode == Global.HUE_API) {
+ listItems +=
+ SimpleListItem(
+ title = currentDevice.name,
+ summary = currentDevice.address,
+ hidden = currentDevice.id,
+ icon = currentDevice.iconId,
+ )
+ }
+ }
+
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ recyclerView.adapter = SimpleListAdapter(listItems, this)
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ if (deviceId == null) {
+ deviceId = view.findViewById(R.id.hidden).text.toString()
+ HueAPI(this, deviceId ?: error("Impossible state.")).loadList(
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ if (holder.response != null) {
+ recyclerView.adapter =
+ SimpleListAdapter(
+ holder.response as List,
+ this@ShortcutHueRoomActivity,
+ )
+ } else {
+ deviceId = null
+ Toast.makeText(
+ this@ShortcutHueRoomActivity,
+ holder.errorMessage,
+ Toast.LENGTH_LONG,
+ ).show()
+ }
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ // Do nothing.
+ }
+ },
+ )
+ } else {
+ val device = Devices(this).getDeviceById(deviceId ?: error("Impossible state."))
+ val lampName = view.findViewById(R.id.title).text
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val shortcutManager = this.getSystemService(ShortcutManager::class.java)
+ if (shortcutManager != null) {
+ setResult(
+ RESULT_OK,
+ shortcutManager.createShortcutResultIntent(
+ ShortcutInfo.Builder(this, device.id + lampName)
+ .setShortLabel(lampName)
+ .setLongLabel(lampName)
+ .setIcon(Icon.createWithResource(this, device.iconId))
+ .setIntent(
+ Intent(this, HueLampActivity::class.java)
+ .putExtra("id", view.findViewById(R.id.hidden).text)
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, device.id)
+ .setAction(Intent.ACTION_MAIN)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
+ )
+ .build(),
+ ),
+ )
+ finish()
+ }
+ } else {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueSceneActionActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueSceneActionActivity.kt
new file mode 100644
index 0000000..00d08d9
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueSceneActionActivity.kt
@@ -0,0 +1,26 @@
+package io.github.domi04151309.home.activities
+
+import android.os.Bundle
+import androidx.appcompat.app.AppCompatActivity
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.helpers.Devices
+
+class ShortcutHueSceneActionActivity : AppCompatActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (intent.hasExtra("scene") && intent.hasExtra("group") && intent.hasExtra(Devices.INTENT_EXTRA_DEVICE)) {
+ HueAPI(
+ this,
+ intent.getStringExtra(Devices.INTENT_EXTRA_DEVICE) ?: error(IMPOSSIBLE_STATE),
+ ).activateSceneOfGroup(
+ intent.getStringExtra("group") ?: error(IMPOSSIBLE_STATE),
+ intent.getStringExtra("scene") ?: error(IMPOSSIBLE_STATE),
+ )
+ }
+ finish()
+ }
+
+ companion object {
+ private const val IMPOSSIBLE_STATE = "Impossible state."
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueSceneActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueSceneActivity.kt
new file mode 100644
index 0000000..8990e06
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutHueSceneActivity.kt
@@ -0,0 +1,181 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import android.widget.Toast
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.android.volley.Request
+import com.android.volley.toolbox.JsonObjectRequest
+import com.android.volley.toolbox.Volley
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.SimpleListAdapter
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.api.UnifiedAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+import org.json.JSONObject
+
+class ShortcutHueSceneActivity : BaseActivity(), RecyclerViewHelperInterface {
+ private var deviceId: String? = null
+ private var group: String? = null
+ private lateinit var recyclerView: RecyclerView
+
+ private val device: DeviceItem
+ get() = Devices(this).getDeviceById(deviceId ?: error("Device ID is null."))
+
+ private val api: HueAPI
+ get() = HueAPI(this, deviceId ?: error("Device ID is null."))
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_devices)
+
+ recyclerView = findViewById(R.id.recyclerView)
+
+ val devices = Devices(this)
+ val listItems: ArrayList = ArrayList(devices.length)
+ var currentDevice: DeviceItem
+ for (i in 0 until devices.length) {
+ currentDevice = devices.getDeviceByIndex(i)
+ if (currentDevice.mode == Global.HUE_API) {
+ listItems +=
+ SimpleListItem(
+ title = currentDevice.name,
+ summary = currentDevice.address,
+ hidden = currentDevice.id,
+ icon = currentDevice.iconId,
+ )
+ }
+ }
+
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ recyclerView.adapter = SimpleListAdapter(listItems, this)
+ }
+
+ private fun loadDevice(view: View) {
+ deviceId = view.findViewById(R.id.hidden).text.toString()
+ api.loadList(
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ if (holder.response != null) {
+ recyclerView.adapter =
+ SimpleListAdapter(
+ holder.response as List,
+ this@ShortcutHueSceneActivity,
+ )
+ } else {
+ deviceId = null
+ Toast.makeText(
+ this@ShortcutHueSceneActivity,
+ holder.errorMessage,
+ Toast.LENGTH_LONG,
+ ).show()
+ }
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ // Do nothing.
+ }
+ },
+ )
+ }
+
+ private fun loadGroup(view: View) {
+ group = view.findViewById(R.id.hidden).text.toString()
+ Volley.newRequestQueue(this).add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ device.address + "api/" + api.getUsername() + "/scenes/",
+ null,
+ { response ->
+ val listItems: ArrayList = ArrayList(response.length() / 2)
+ var currentObject: JSONObject
+ for (i in response.keys()) {
+ currentObject = response.getJSONObject(i)
+ if (currentObject.optString("group") == group) {
+ listItems.add(
+ SimpleListItem(
+ currentObject.optString("name"),
+ resources.getString(R.string.hue_tap),
+ i,
+ R.drawable.ic_scene,
+ ),
+ )
+ }
+ }
+ listItems.sortBy { it.title }
+ recyclerView.adapter = SimpleListAdapter(listItems, this)
+ },
+ { error ->
+ group = null
+ Toast.makeText(this, Global.volleyError(this, error), Toast.LENGTH_LONG)
+ .show()
+ },
+ ),
+ )
+ }
+
+ private fun createShortcut(view: View) {
+ val lampName = view.findViewById(R.id.title).text
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val shortcutManager = this.getSystemService(ShortcutManager::class.java)
+ if (shortcutManager != null) {
+ setResult(
+ RESULT_OK,
+ shortcutManager.createShortcutResultIntent(
+ ShortcutInfo.Builder(this, device.id + lampName)
+ .setShortLabel(view.findViewById(R.id.title).text)
+ .setLongLabel(view.findViewById(R.id.title).text)
+ .setIcon(Icon.createWithResource(this, device.iconId))
+ .setIntent(
+ Intent(this, ShortcutHueSceneActionActivity::class.java)
+ .putExtra(
+ "scene",
+ view.findViewById(R.id.hidden).text,
+ )
+ .putExtra("group", group)
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, device.id)
+ .setAction(Intent.ACTION_MAIN)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
+ )
+ .build(),
+ ),
+ )
+ finish()
+ }
+ } else {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ if (deviceId == null) {
+ loadDevice(view)
+ } else if (group == null) {
+ loadGroup(view)
+ } else {
+ createShortcut(view)
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ShortcutTasmotaActionActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutTasmotaActionActivity.kt
new file mode 100644
index 0000000..ab027f5
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutTasmotaActionActivity.kt
@@ -0,0 +1,45 @@
+package io.github.domi04151309.home.activities
+
+import android.os.Bundle
+import android.widget.Toast
+import androidx.appcompat.app.AppCompatActivity
+import io.github.domi04151309.home.api.Tasmota
+import io.github.domi04151309.home.api.UnifiedAPI
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+
+class ShortcutTasmotaActionActivity : AppCompatActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (intent.hasExtra("command") && intent.hasExtra(Devices.INTENT_EXTRA_DEVICE)) {
+ Tasmota(
+ this,
+ intent.getStringExtra(Devices.INTENT_EXTRA_DEVICE) ?: error("Impossible state."),
+ null,
+ ).execute(
+ intent.getStringExtra("command") ?: error("Impossible state."),
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ // Do nothing.
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ Toast.makeText(
+ this@ShortcutTasmotaActionActivity,
+ result,
+ Toast.LENGTH_LONG,
+ ).show()
+ }
+ },
+ )
+ }
+ finish()
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/ShortcutTasmotaActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutTasmotaActivity.kt
new file mode 100644
index 0000000..5d4ee0d
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/ShortcutTasmotaActivity.kt
@@ -0,0 +1,125 @@
+package io.github.domi04151309.home.activities
+
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.Icon
+import android.os.Build
+import android.os.Bundle
+import android.view.View
+import android.widget.TextView
+import android.widget.Toast
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.SimpleListAdapter
+import io.github.domi04151309.home.api.Tasmota
+import io.github.domi04151309.home.api.UnifiedAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class ShortcutTasmotaActivity : BaseActivity(), RecyclerViewHelperInterface {
+ private var deviceId: String? = null
+ private lateinit var recyclerView: RecyclerView
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_devices)
+
+ recyclerView = findViewById(R.id.recyclerView)
+
+ val devices = Devices(this)
+ val listItems: ArrayList = ArrayList(devices.length)
+ var currentDevice: DeviceItem
+ for (i in 0 until devices.length) {
+ currentDevice = devices.getDeviceByIndex(i)
+ if (currentDevice.mode == Global.TASMOTA) {
+ listItems +=
+ SimpleListItem(
+ title = currentDevice.name,
+ summary = currentDevice.address,
+ hidden = currentDevice.id,
+ icon = currentDevice.iconId,
+ )
+ }
+ }
+
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ recyclerView.adapter = SimpleListAdapter(listItems, this)
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ if (deviceId == null) {
+ deviceId = view.findViewById(R.id.hidden).text.toString()
+ Tasmota(this, deviceId ?: error("Impossible state."), null).loadList(
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ if (holder.response != null) {
+ recyclerView.adapter =
+ SimpleListAdapter(
+ holder.response as List,
+ this@ShortcutTasmotaActivity,
+ )
+ } else {
+ deviceId = null
+ Toast.makeText(
+ this@ShortcutTasmotaActivity,
+ holder.errorMessage,
+ Toast.LENGTH_LONG,
+ ).show()
+ }
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ // Do nothing.
+ }
+ },
+ )
+ } else {
+ val device = Devices(this).getDeviceById(deviceId ?: error("Impossible state."))
+ val lampName = view.findViewById(R.id.title).text
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val shortcutManager = this.getSystemService(ShortcutManager::class.java)
+ if (shortcutManager != null) {
+ setResult(
+ RESULT_OK,
+ shortcutManager.createShortcutResultIntent(
+ ShortcutInfo.Builder(this, device.id + lampName)
+ .setShortLabel(lampName)
+ .setLongLabel(lampName)
+ .setIcon(Icon.createWithResource(this, device.iconId))
+ .setIntent(
+ Intent(this, ShortcutTasmotaActionActivity::class.java)
+ .putExtra(
+ "command",
+ view.findViewById(R.id.summary).text,
+ )
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, device.id)
+ .setAction(Intent.ACTION_MAIN)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
+ )
+ .build(),
+ ),
+ )
+ finish()
+ }
+ } else {
+ Toast.makeText(this, R.string.pref_add_shortcut_failed, Toast.LENGTH_LONG).show()
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/WebActivity.kt b/app/src/main/java/io/github/domi04151309/home/activities/WebActivity.kt
new file mode 100644
index 0000000..c68c6d1
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/WebActivity.kt
@@ -0,0 +1,154 @@
+package io.github.domi04151309.home.activities
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.app.DownloadManager
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Bundle
+import android.os.Environment
+import android.view.KeyEvent
+import android.view.Menu
+import android.view.MenuItem
+import android.webkit.ValueCallback
+import android.webkit.WebChromeClient
+import android.webkit.WebView
+import android.widget.ProgressBar
+import androidx.activity.result.ActivityResultLauncher
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.core.app.ActivityCompat
+import androidx.core.net.toUri
+import io.github.domi04151309.home.R
+
+class WebActivity : BaseActivity() {
+ private var valueCallback: ValueCallback>? = null
+ private lateinit var webView: WebView
+ private lateinit var webViewClient: WebActivityWebViewClient
+ private lateinit var resultLauncher: ActivityResultLauncher
+
+ @SuppressLint("SetJavaScriptEnabled")
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_web)
+
+ webViewClient =
+ WebActivityWebViewClient(
+ this,
+ intent,
+ findViewById(R.id.progressBar),
+ findViewById(R.id.error),
+ )
+
+ webView = findViewById(R.id.webView)
+ webView.settings.javaScriptEnabled = true
+ webView.settings.domStorageEnabled = true
+ webView.webViewClient = webViewClient
+
+ resultLauncher =
+ registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
+ if (result.resultCode == RESULT_OK) {
+ val path = result.data?.data
+ valueCallback?.onReceiveValue(
+ if (path == null) {
+ arrayOf()
+ } else {
+ arrayOf(path)
+ },
+ )
+ }
+ }
+
+ webView.webChromeClient =
+ object : WebChromeClient() {
+ override fun onShowFileChooser(
+ webView: WebView?,
+ filePathCallback: ValueCallback>?,
+ fileChooserParams: FileChooserParams?,
+ ): Boolean = showFileChooser(filePathCallback)
+ }
+
+ webView.setDownloadListener { url, _, _, _, _ ->
+ onDownload(url)
+ }
+
+ webView.loadUrl(intent.getStringExtra("URI") ?: ABOUT_BLANK)
+ title = intent.getStringExtra("title")
+ }
+
+ internal fun showFileChooser(filePathCallback: ValueCallback>?): Boolean {
+ valueCallback = filePathCallback
+ resultLauncher.launch(
+ Intent(Intent.ACTION_CHOOSER)
+ .putExtra(
+ Intent.EXTRA_INTENT,
+ Intent(Intent.ACTION_GET_CONTENT).apply {
+ addCategory(Intent.CATEGORY_OPENABLE)
+ type = "*/*"
+ },
+ )
+ .putExtra(Intent.EXTRA_TITLE, "Image Chooser"),
+ )
+ return true
+ }
+
+ private fun onDownload(url: String) {
+ if (ActivityCompat.checkSelfPermission(
+ this,
+ Manifest.permission.READ_EXTERNAL_STORAGE,
+ ) != PackageManager.PERMISSION_GRANTED ||
+ ActivityCompat.checkSelfPermission(
+ this,
+ Manifest.permission.WRITE_EXTERNAL_STORAGE,
+ ) != PackageManager.PERMISSION_GRANTED
+ ) {
+ ActivityCompat.requestPermissions(
+ this,
+ arrayOf(
+ Manifest.permission.READ_EXTERNAL_STORAGE,
+ Manifest.permission.WRITE_EXTERNAL_STORAGE,
+ ),
+ 1,
+ )
+ }
+
+ val uri = url.toUri()
+ (getSystemService(DOWNLOAD_SERVICE) as DownloadManager).enqueue(
+ DownloadManager.Request(uri).apply {
+ setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
+ setDestinationInExternalPublicDir(
+ Environment.DIRECTORY_DOWNLOADS,
+ uri.lastPathSegment,
+ )
+ },
+ )
+ }
+
+ override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ menuInflater.inflate(R.menu.activity_web_actions, menu)
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ if (item.itemId == R.id.action_open) {
+ startActivity(Intent(Intent.ACTION_VIEW, webView.url?.toUri()))
+ return true
+ }
+ return super.onOptionsItemSelected(item)
+ }
+
+ override fun onKeyDown(
+ keyCode: Int,
+ event: KeyEvent,
+ ): Boolean {
+ if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && !webViewClient.hasError) {
+ webView.goBack()
+ return true
+ }
+ return super.onKeyDown(keyCode, event)
+ }
+
+ companion object {
+ private const val ABOUT_BLANK = "about:blank"
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/activities/WebActivityWebViewClient.kt b/app/src/main/java/io/github/domi04151309/home/activities/WebActivityWebViewClient.kt
new file mode 100644
index 0000000..0496211
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/activities/WebActivityWebViewClient.kt
@@ -0,0 +1,191 @@
+package io.github.domi04151309.home.activities
+
+import android.annotation.SuppressLint
+import android.content.Context
+import android.content.Intent
+import android.net.http.SslError
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.webkit.HttpAuthHandler
+import android.webkit.SslErrorHandler
+import android.webkit.WebResourceError
+import android.webkit.WebResourceRequest
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import android.widget.EditText
+import android.widget.Toast
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.helpers.DeviceSecrets
+
+class WebActivityWebViewClient(
+ private val context: Context,
+ private val intent: Intent,
+ private val progressView: View,
+ private val errorView: View,
+) :
+ WebViewClient() {
+ var hasError: Boolean = false
+ private set
+
+ private var isFirstLoad: Boolean = true
+ private val nullParent: ViewGroup? = null
+
+ override fun onPageFinished(
+ view: WebView,
+ url: String,
+ ) {
+ if (url == ABOUT_BLANK) {
+ view.visibility = View.GONE
+ return
+ }
+ if (isFirstLoad) {
+ if (intent.hasExtra("fritz_auto_login")) {
+ injectFritzLogin(
+ view,
+ DeviceSecrets(
+ context,
+ intent.getStringExtra("fritz_auto_login") ?: "",
+ ).password,
+ )
+ } else if (intent.hasExtra("grafana_auto_login")) {
+ val secrets =
+ DeviceSecrets(
+ context,
+ intent.getStringExtra("grafana_auto_login") ?: "",
+ )
+ injectGrafanaLogin(
+ view,
+ secrets.username,
+ secrets.password,
+ )
+ } else if (intent.hasExtra("pi_hole_auto_login")) {
+ injectPiHoleLogin(
+ view,
+ DeviceSecrets(
+ context,
+ intent.getStringExtra("pi_hole_auto_login") ?: "",
+ ).password,
+ )
+ }
+ isFirstLoad = false
+ }
+
+ progressView.visibility = View.GONE
+ view.visibility = View.VISIBLE
+ super.onPageFinished(view, url)
+ }
+
+ override fun onReceivedHttpAuthRequest(
+ view: WebView,
+ handler: HttpAuthHandler,
+ host: String,
+ realm: String,
+ ) {
+ val dialogView =
+ LayoutInflater.from(context)
+ .inflate(R.layout.dialog_web_authentication, nullParent, false)
+ MaterialAlertDialogBuilder(context)
+ .setTitle(R.string.webView_authentication)
+ .setView(dialogView)
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ handler.proceed(
+ dialogView.findViewById(R.id.username).text.toString(),
+ dialogView.findViewById(R.id.password).text.toString(),
+ )
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ }
+
+ @SuppressLint("WebViewClientOnReceivedSslError")
+ override fun onReceivedSslError(
+ view: WebView,
+ handler: SslErrorHandler,
+ error: SslError,
+ ) {
+ Toast.makeText(context, R.string.webView_ssl_error, Toast.LENGTH_LONG)
+ .show()
+ handler.proceed()
+ }
+
+ override fun onReceivedError(
+ view: WebView,
+ request: WebResourceRequest,
+ error: WebResourceError,
+ ) {
+ view.loadUrl(ABOUT_BLANK)
+ hasError = true
+ progressView.visibility = View.GONE
+ errorView.visibility = View.VISIBLE
+ }
+
+ private fun injectFritzLogin(
+ webView: WebView,
+ password: String,
+ ) {
+ webView.evaluateJavascript(
+ """
+ document.getElementById('uiPass').value = '$password';
+ document.getElementById('submitLoginBtn').click();
+ """,
+ ) {}
+ }
+
+ private fun injectGrafanaLogin(
+ webView: WebView,
+ username: String,
+ password: String,
+ ) {
+ webView.evaluateJavascript(
+ """
+ function setNativeValue(element, value) {
+ const proto = Object.getPrototypeOf(element);
+ const descriptor = Object.getOwnPropertyDescriptor(proto, 'value');
+ const setter = descriptor && descriptor.set;
+
+ if (setter) {
+ setter.call(element, value);
+ } else {
+ element.value = value;
+ }
+ }
+
+ const check = setInterval(() => {
+ const username = document.querySelector('input[name=user]');
+ const password = document.querySelector('input[name=password]');
+ if (username && password) {
+ clearInterval(check);
+
+ setNativeValue(username, '$username');
+ setNativeValue(password, '$password');
+
+ ['input', 'change'].forEach(eventName => {
+ username.dispatchEvent(new Event(eventName, { bubbles: true }));
+ password.dispatchEvent(new Event(eventName, { bubbles: true }));
+ });
+
+ document.querySelector('button[type=submit]').click();
+ }
+ }, 100);
+ """,
+ ) {}
+ }
+
+ private fun injectPiHoleLogin(
+ webView: WebView,
+ password: String,
+ ) {
+ webView.evaluateJavascript(
+ """
+ document.getElementById('current-password').value = '$password';
+ document.querySelector('button[type=submit]').click();
+ """,
+ ) {}
+ }
+
+ companion object {
+ private const val ABOUT_BLANK = "about:blank"
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/DeviceDiscoveryListAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/DeviceDiscoveryListAdapter.kt
new file mode 100644
index 0000000..2f12026
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/DeviceDiscoveryListAdapter.kt
@@ -0,0 +1,76 @@
+package io.github.domi04151309.home.adapters
+
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.recyclerview.widget.RecyclerView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class DeviceDiscoveryListAdapter(
+ private val items: MutableList,
+ private val helperInterface: RecyclerViewHelperInterface,
+) : RecyclerView.Adapter() {
+ override fun onCreateViewHolder(
+ parent: ViewGroup,
+ viewType: Int,
+ ): ViewHolder =
+ ViewHolder(
+ LayoutInflater
+ .from(parent.context)
+ .inflate(R.layout.list_item_device_discovery, parent, false),
+ )
+
+ override fun onBindViewHolder(
+ holder: ViewHolder,
+ position: Int,
+ ) {
+ holder.drawable.setImageResource(items[position].icon)
+ holder.title.text = items[position].title
+ holder.summary.text = items[position].summary
+ holder.hidden.text = items[position].hidden
+ holder.stateDrawable.setImageResource(
+ if (items[position].state == true) {
+ R.drawable.ic_done
+ } else {
+ android.R.color.transparent
+ },
+ )
+ holder.itemView.setOnClickListener { helperInterface.onItemClicked(holder.itemView, position) }
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ fun add(item: ListViewItem): Int {
+ items.add(item)
+ notifyItemInserted(items.size - 1)
+ return items.size - 1
+ }
+
+ fun changeState(
+ i: Int,
+ state: Boolean,
+ ) {
+ items[i].state = state
+ notifyItemChanged(i)
+ }
+
+ fun changeTitle(
+ i: Int,
+ title: String,
+ ) {
+ items[i].title = title
+ notifyItemChanged(i)
+ }
+
+ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ val drawable: ImageView = view.findViewById(R.id.drawable)
+ val title: TextView = view.findViewById(R.id.title)
+ val summary: TextView = view.findViewById(R.id.summary)
+ val hidden: TextView = view.findViewById(R.id.hidden)
+ val stateDrawable: ImageView = view.findViewById(R.id.state)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/DeviceListAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/DeviceListAdapter.kt
new file mode 100644
index 0000000..ee2c569
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/DeviceListAdapter.kt
@@ -0,0 +1,60 @@
+package io.github.domi04151309.home.adapters
+
+import android.annotation.SuppressLint
+import android.view.LayoutInflater
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.recyclerview.widget.RecyclerView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterfaceAdvanced
+
+class DeviceListAdapter(
+ private val items: List,
+ private val helperInterface: RecyclerViewHelperInterfaceAdvanced,
+) : RecyclerView.Adapter() {
+ override fun onCreateViewHolder(
+ parent: ViewGroup,
+ viewType: Int,
+ ): ViewHolder =
+ ViewHolder(
+ LayoutInflater
+ .from(parent.context)
+ .inflate(R.layout.list_item_devices, parent, false),
+ )
+
+ @SuppressLint("ClickableViewAccessibility")
+ override fun onBindViewHolder(
+ holder: ViewHolder,
+ position: Int,
+ ) {
+ holder.drawable.setImageResource(items[position].icon)
+ holder.title.text = items[position].title
+ holder.summary.text = items[position].summary
+ holder.hidden.text = items[position].hidden
+ holder.itemView.setOnClickListener { helperInterface.onItemClicked(holder.itemView, position) }
+ if (position == itemCount - 1) {
+ holder.handle.visibility = View.GONE
+ } else {
+ holder.handle.setOnTouchListener { view, event ->
+ if (event.actionMasked == MotionEvent.ACTION_DOWN) {
+ helperInterface.onItemHandleTouched(holder)
+ }
+ view.performClick()
+ }
+ }
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ val drawable: ImageView = view.findViewById(R.id.drawable)
+ val title: TextView = view.findViewById(R.id.title)
+ val summary: TextView = view.findViewById(R.id.summary)
+ val hidden: TextView = view.findViewById(R.id.hidden)
+ val handle: ImageView = view.findViewById(R.id.handle)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/HueDetailsTabAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/HueDetailsTabAdapter.kt
new file mode 100644
index 0000000..8d82bd1
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/HueDetailsTabAdapter.kt
@@ -0,0 +1,24 @@
+package io.github.domi04151309.home.adapters
+
+import androidx.fragment.app.Fragment
+import androidx.fragment.app.FragmentActivity
+import androidx.viewpager2.adapter.FragmentStateAdapter
+import io.github.domi04151309.home.fragments.HueColorFragment
+import io.github.domi04151309.home.fragments.HueLampsFragment
+import io.github.domi04151309.home.fragments.HueScenesFragment
+import io.github.domi04151309.home.interfaces.HueRoomInterface
+
+class HueDetailsTabAdapter(
+ activity: FragmentActivity,
+ private val lampInterface: HueRoomInterface,
+) : FragmentStateAdapter(activity) {
+ override fun createFragment(position: Int): Fragment =
+ when (position) {
+ 0 -> HueColorFragment(lampInterface)
+ 1 -> HueScenesFragment(lampInterface)
+ 2 -> HueLampsFragment(lampInterface)
+ else -> Fragment()
+ }
+
+ override fun getItemCount(): Int = 3
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/HueLampListAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/HueLampListAdapter.kt
new file mode 100644
index 0000000..dbfe44c
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/HueLampListAdapter.kt
@@ -0,0 +1,110 @@
+package io.github.domi04151309.home.adapters
+
+import android.annotation.SuppressLint
+import android.graphics.drawable.LayerDrawable
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.CompoundButton
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.core.content.ContextCompat
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.materialswitch.MaterialSwitch
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class HueLampListAdapter(
+ private val stateListener: CompoundButton.OnCheckedChangeListener,
+ private val helperInterface: RecyclerViewHelperInterface,
+) : RecyclerView.Adapter() {
+ private var items: List = mutableListOf()
+ private var colors: List = mutableListOf()
+
+ override fun onCreateViewHolder(
+ parent: ViewGroup,
+ viewType: Int,
+ ): ViewHolder =
+ ViewHolder(
+ LayoutInflater
+ .from(parent.context)
+ .inflate(R.layout.list_item, parent, false),
+ )
+
+ override fun onBindViewHolder(
+ holder: ViewHolder,
+ position: Int,
+ ) {
+ val context = holder.itemView.context
+ val finalDrawable =
+ LayerDrawable(
+ arrayOf(
+ ContextCompat.getDrawable(context, R.drawable.ic_hue_lamp_base),
+ ContextCompat.getDrawable(context, R.drawable.ic_hue_lamp_color),
+ ),
+ )
+ finalDrawable.getDrawable(1).setTint(colors[position])
+ holder.drawable.setImageDrawable(finalDrawable)
+ holder.title.text = items[position].title
+ holder.summary.text = items[position].summary
+ holder.hidden.text = items[position].hidden
+ holder.stateSwitch.isChecked = items[position].state == true
+ holder.stateSwitch.setOnCheckedChangeListener(stateListener)
+ holder.itemView.setOnClickListener { helperInterface.onItemClicked(holder.itemView, position) }
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ @SuppressLint("NotifyDataSetChanged")
+ fun updateData(
+ recyclerView: RecyclerView,
+ newItems: List,
+ newColors: List,
+ ) {
+ if (newItems.size != items.size) {
+ items = newItems
+ colors = newColors
+ notifyDataSetChanged()
+ return
+ }
+
+ val changed = mutableListOf()
+ for (i in items.indices) {
+ if (items[i].hidden != newItems[i].hidden) {
+ changed.add(i)
+ } else {
+ val holder = (recyclerView.findViewHolderForAdapterPosition(i) ?: return) as ViewHolder
+ if (items[i].summary != newItems[i].summary) {
+ holder.summary.text = newItems[i].summary
+ }
+ if (items[i].state != newItems[i].state) {
+ holder.stateSwitch.isChecked = newItems[i].state == true
+ }
+ if (colors[i] != newColors[i]) {
+ val context = holder.itemView.context
+ val finalDrawable =
+ LayerDrawable(
+ arrayOf(
+ ContextCompat.getDrawable(context, R.drawable.ic_hue_lamp_base),
+ ContextCompat.getDrawable(context, R.drawable.ic_hue_lamp_color),
+ ),
+ )
+ finalDrawable.getDrawable(1).setTint(newColors[i])
+ holder.drawable.setImageDrawable(finalDrawable)
+ }
+ }
+ }
+ items = newItems
+ colors = newColors
+ changed.forEach(::notifyItemChanged)
+ }
+
+ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ val drawable: ImageView = view.findViewById(R.id.drawable)
+ val title: TextView = view.findViewById(R.id.title)
+ val summary: TextView = view.findViewById(R.id.summary)
+ val hidden: TextView = view.findViewById(R.id.hidden)
+ val stateSwitch: MaterialSwitch = view.findViewById(R.id.state)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/HueSceneGridAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/HueSceneGridAdapter.kt
new file mode 100644
index 0000000..3aefd5e
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/HueSceneGridAdapter.kt
@@ -0,0 +1,79 @@
+package io.github.domi04151309.home.adapters
+
+import android.annotation.SuppressLint
+import android.graphics.Color
+import android.graphics.drawable.LayerDrawable
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.core.content.ContextCompat
+import androidx.recyclerview.widget.RecyclerView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.SceneGridItem
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class HueSceneGridAdapter(
+ private val contextMenuListener: View.OnCreateContextMenuListener,
+ private val helperInterface: RecyclerViewHelperInterface,
+) : RecyclerView.Adapter() {
+ private var items: MutableList = mutableListOf()
+
+ override fun onCreateViewHolder(
+ parent: ViewGroup,
+ viewType: Int,
+ ): ViewHolder =
+ ViewHolder(
+ LayoutInflater
+ .from(parent.context)
+ .inflate(R.layout.grid_item, parent, false),
+ )
+
+ override fun onBindViewHolder(
+ holder: ViewHolder,
+ position: Int,
+ ) {
+ val context = holder.itemView.context
+ holder.title.text = items[position].name
+ holder.hidden.text = items[position].hidden
+ if (items[position].color == null) {
+ holder.drawable.setImageResource(R.drawable.ic_hue_scene_add)
+ } else {
+ val finalDrawable =
+ LayerDrawable(
+ arrayOf(
+ ContextCompat.getDrawable(context, R.drawable.ic_hue_scene_base),
+ ContextCompat.getDrawable(context, R.drawable.ic_hue_scene_color),
+ ),
+ )
+ finalDrawable.getDrawable(1).setTint(items[position].color ?: Color.WHITE)
+ holder.drawable.setImageDrawable(finalDrawable)
+ }
+ holder.itemView.setOnClickListener { helperInterface.onItemClicked(holder.itemView, position) }
+ holder.itemView.setOnCreateContextMenuListener(contextMenuListener)
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ @SuppressLint("NotifyDataSetChanged")
+ fun updateData(newItems: MutableList) {
+ if (newItems.size != items.size) {
+ items = newItems
+ notifyDataSetChanged()
+ } else {
+ val changed = mutableListOf()
+ for (i in items.indices) {
+ if (items[i] != newItems[i]) changed.add(i)
+ }
+ items = newItems
+ changed.forEach(::notifyItemChanged)
+ }
+ }
+
+ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ val drawable: ImageView = view.findViewById(R.id.drawable)
+ val title: TextView = view.findViewById(R.id.title)
+ val hidden: TextView = view.findViewById(R.id.hidden)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/HueSceneLampListAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/HueSceneLampListAdapter.kt
new file mode 100644
index 0000000..2db7796
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/HueSceneLampListAdapter.kt
@@ -0,0 +1,115 @@
+package io.github.domi04151309.home.adapters
+
+import android.annotation.SuppressLint
+import android.content.res.ColorStateList
+import android.content.res.Resources
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.core.widget.ImageViewCompat
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.materialswitch.MaterialSwitch
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.SceneListItem
+import io.github.domi04151309.home.interfaces.SceneRecyclerViewHelperInterface
+
+class HueSceneLampListAdapter(
+ private var items: List,
+ private var helperInterface: SceneRecyclerViewHelperInterface,
+) : RecyclerView.Adapter() {
+ init {
+ setHasStableIds(true)
+ }
+
+ override fun getItemId(position: Int): Long =
+ (position.toString() + '#' + items[position].hidden)
+ .hashCode()
+ .toLong()
+
+ override fun onCreateViewHolder(
+ parent: ViewGroup,
+ viewType: Int,
+ ): ViewHolder =
+ ViewHolder(
+ LayoutInflater
+ .from(parent.context)
+ .inflate(R.layout.list_item, parent, false),
+ )
+
+ @SuppressLint("SetTextI18n")
+ override fun onBindViewHolder(
+ holder: ViewHolder,
+ position: Int,
+ ) {
+ val id = getItemId(position)
+ holder.drawable.setImageResource(R.drawable.ic_circle)
+ holder.title.text = items[position].title
+ holder.summary.text = generateSummary(holder.itemView.resources, items[position])
+ holder.hidden.text = items[position].hidden
+ holder.stateSwitch.isChecked = items[position].state
+ holder.stateSwitch.setOnCheckedChangeListener { compoundButton, b ->
+ items[getPosFromId(id)].state = b
+ holder.summary.text = generateSummary(holder.itemView.resources, items[getPosFromId(id)])
+ if (compoundButton.isPressed) {
+ helperInterface.onStateChanged(
+ holder.itemView,
+ items[getPosFromId(id)],
+ b,
+ )
+ }
+ }
+ ImageViewCompat.setImageTintList(
+ holder.drawable,
+ ColorStateList.valueOf(items[position].color),
+ )
+ holder.itemView.setOnClickListener {
+ helperInterface.onItemClicked(holder.itemView, items[getPosFromId(id)])
+ }
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ fun changeSceneBrightness(brightness: String) {
+ for (i in items.indices) {
+ items[i].brightness = brightness
+ if (items[i].state) notifyItemChanged(i)
+ }
+ }
+
+ fun updateBrightness(
+ id: String,
+ brightness: String,
+ ) {
+ val i = items.indexOfFirst { it.hidden == id }
+ items[i].brightness = brightness
+ if (items[i].state) notifyItemChanged(i)
+ }
+
+ fun updateColor(
+ id: String,
+ color: Int,
+ ) {
+ val i = items.indexOfFirst { it.hidden == id }
+ items[i].color = color
+ notifyItemChanged(i)
+ }
+
+ private fun generateSummary(
+ resources: Resources,
+ item: SceneListItem,
+ ): String =
+ resources.getString(R.string.hue_brightness) +
+ ": " + if (item.state) item.brightness else "0 %"
+
+ private fun getPosFromId(id: Long): Int = items.indices.indexOfFirst { getItemId(it) == id }
+
+ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ val drawable: ImageView = view.findViewById(R.id.drawable)
+ val title: TextView = view.findViewById(R.id.title)
+ val summary: TextView = view.findViewById(R.id.summary)
+ val hidden: TextView = view.findViewById(R.id.hidden)
+ val stateSwitch: MaterialSwitch = view.findViewById(R.id.state)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/IconSpinnerAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/IconSpinnerAdapter.kt
new file mode 100644
index 0000000..3f2c826
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/IconSpinnerAdapter.kt
@@ -0,0 +1,62 @@
+package io.github.domi04151309.home.adapters
+
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.BaseAdapter
+import android.widget.Filter
+import android.widget.Filterable
+import android.widget.ImageView
+import android.widget.TextView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.helpers.Global
+
+internal class IconSpinnerAdapter(
+ private var itemArray: Array,
+) : BaseAdapter(), Filterable {
+ override fun getCount(): Int = itemArray.size
+
+ override fun getItem(position: Int): String = itemArray[position]
+
+ override fun getItemId(position: Int): Long = position.toLong()
+
+ override fun getFilter(): Filter = ItemFilter()
+
+ override fun getView(
+ position: Int,
+ convertView: View?,
+ parent: ViewGroup,
+ ): View {
+ val vi: View =
+ convertView
+ ?: LayoutInflater.from(parent.context).inflate(R.layout.icon_dropdown_item, parent, false)
+ vi.findViewById(R.id.drawable).setImageResource(Global.getIcon(itemArray[position]))
+ vi.findViewById(R.id.title).text = itemArray[position]
+ return vi
+ }
+
+ inner class ItemFilter : Filter() {
+ override fun performFiltering(constraint: CharSequence): FilterResults {
+ val results = FilterResults()
+ val search = constraint.toString().lowercase()
+
+ val items: ArrayList = ArrayList(itemArray.size)
+
+ for (i in itemArray.indices) {
+ if (itemArray[i].lowercase().contains(search)) items.add(itemArray[i])
+ }
+
+ results.values = items.toArray()
+ results.count = items.size
+ return results
+ }
+
+ override fun publishResults(
+ constraint: CharSequence,
+ results: FilterResults,
+ ) {
+ itemArray = (results.values as Array<*>).filterIsInstance().toTypedArray()
+ notifyDataSetChanged()
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/MainListAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/MainListAdapter.kt
new file mode 100644
index 0000000..baf5cd7
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/MainListAdapter.kt
@@ -0,0 +1,209 @@
+package io.github.domi04151309.home.adapters
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.util.Log
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.view.animation.AlphaAnimation
+import android.view.animation.Animation
+import android.view.animation.AnimationSet
+import android.view.animation.TranslateAnimation
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.recyclerview.widget.RecyclerView
+import com.google.android.material.materialswitch.MaterialSwitch
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+
+@Suppress("TooManyFunctions")
+class MainListAdapter(private var attachedTo: RecyclerView) : RecyclerView.Adapter() {
+ private var items: MutableList = mutableListOf()
+ private var helperInterface: HomeRecyclerViewHelperInterface? = null
+ private var animate: Boolean = true
+ private var offsets: IntArray = intArrayOf()
+
+ init {
+ setHasStableIds(true)
+ }
+
+ override fun getItemId(position: Int): Long =
+ (position.toString() + '#' + items[position].hidden)
+ .hashCode()
+ .toLong()
+
+ override fun onCreateViewHolder(
+ parent: ViewGroup,
+ viewType: Int,
+ ): ViewHolder =
+ ViewHolder(
+ LayoutInflater
+ .from(parent.context)
+ .inflate(R.layout.list_item, parent, false),
+ )
+
+ override fun onBindViewHolder(
+ holder: ViewHolder,
+ position: Int,
+ ) {
+ holder.drawable.setImageResource(items[position].icon)
+ holder.title.text = items[position].title
+ holder.summary.text = items[position].summary
+ holder.hidden.text = items[position].hidden
+
+ val id = getItemId(position)
+ if (items[position].state != null) {
+ holder.stateSwitch.isChecked = items[position].state == true
+ holder.stateSwitch.setOnCheckedChangeListener { compoundButton, b ->
+ if (compoundButton.isPressed) {
+ helperInterface?.onStateChanged(
+ holder.itemView,
+ items[getPosFromId(id)],
+ b,
+ )
+ }
+ }
+ } else {
+ holder.stateSwitch.visibility = View.GONE
+ }
+ holder.itemView.setOnClickListener {
+ helperInterface?.onItemClicked(holder.itemView, items[getPosFromId(id)])
+ }
+
+ holder.itemView.setOnCreateContextMenuListener(holder.itemView.context as Activity)
+ if (animate) playAnimation(holder.itemView)
+ }
+
+ override fun onViewRecycled(holder: ViewHolder) {
+ holder.stateSwitch.visibility = View.VISIBLE
+ super.onViewRecycled(holder)
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
+ super.onAttachedToRecyclerView(recyclerView)
+ attachedTo = recyclerView
+ }
+
+ @SuppressLint("NotifyDataSetChanged")
+ fun updateData(
+ newItems: List,
+ newHelperInterface: HomeRecyclerViewHelperInterface? = null,
+ preferredAnimationState: Boolean? = null,
+ ) {
+ offsets = IntArray(newItems.size) { 1 }
+ if (newHelperInterface != null) {
+ attachedTo.layoutManager?.scrollToPosition(0)
+ animate = preferredAnimationState != false
+ items.clear()
+ items.addAll(newItems)
+ helperInterface = newHelperInterface
+ notifyDataSetChanged()
+ } else {
+ animate = preferredAnimationState == true
+ val changed = mutableListOf()
+ items.clear()
+ for (i in 0 until items.size) {
+ if (items[i] != newItems[i]) changed.add(i)
+ items.add(newItems[i])
+ }
+ changed.forEach(::notifyItemChanged)
+ }
+ }
+
+ fun updateItem(
+ position: Int,
+ item: ListViewItem,
+ ) {
+ if (position > items.size - 1) {
+ Log.w(Global.LOG_TAG, "The position $position is larger than the item count")
+ return
+ }
+
+ if (items[position].summary == item.summary && items[position].state == item.state) {
+ return
+ }
+
+ items[position].summary = item.summary
+ items[position].state = item.state
+
+ val viewHolder = attachedTo.findViewHolderForAdapterPosition(position) as? ViewHolder
+ if (viewHolder == null) {
+ notifyItemChanged(position)
+ } else {
+ viewHolder.summary.text = item.summary
+ viewHolder.stateSwitch.isChecked = item.state == true
+ }
+ }
+
+ fun getOffset(pos: Int): Int = offsets.copyOfRange(0, pos).sum()
+
+ fun updateDirectView(
+ id: String,
+ newItems: List,
+ directViewPos: Int,
+ ) {
+ newItems.forEach { it.hidden = id + '@' + it.hidden }
+
+ val correctOffset = getOffset(directViewPos)
+ val directViewSize = offsets[directViewPos]
+ for (i in 0 until directViewSize) {
+ items.removeAt(correctOffset)
+ notifyItemRemoved(correctOffset)
+ }
+ offsets[directViewPos] = newItems.size
+ items.addAll(correctOffset, newItems)
+ notifyItemRangeInserted(correctOffset, newItems.size)
+ }
+
+ private fun getPosFromId(id: Long): Int = items.indices.indexOfFirst { getItemId(it) == id }
+
+ fun getDirectViewPos(deviceId: String): Int {
+ var currentPos = 0
+ for (i in offsets.indices) {
+ if (items[currentPos].hidden.contains(deviceId)) return i
+ currentPos += offsets[i]
+ }
+ return -1
+ }
+
+ private fun playAnimation(v: View) {
+ val set = AnimationSet(true)
+
+ val firstAnimation: Animation = AlphaAnimation(0.0f, 1.0f)
+ firstAnimation.duration = ANIMATION_DURATION
+ set.addAnimation(firstAnimation)
+
+ val secondAnimation =
+ TranslateAnimation(
+ Animation.RELATIVE_TO_SELF,
+ -1.0f,
+ Animation.RELATIVE_TO_SELF,
+ 0.0f,
+ Animation.RELATIVE_TO_SELF,
+ 0.0f,
+ Animation.RELATIVE_TO_SELF,
+ 0.0f,
+ )
+ secondAnimation.duration = ANIMATION_DURATION
+ set.addAnimation(secondAnimation)
+
+ v.startAnimation(set)
+ }
+
+ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ val drawable: ImageView = view.findViewById(R.id.drawable)
+ val title: TextView = view.findViewById(R.id.title)
+ val summary: TextView = view.findViewById(R.id.summary)
+ val hidden: TextView = view.findViewById(R.id.hidden)
+ val stateSwitch: MaterialSwitch = view.findViewById(R.id.state)
+ }
+
+ companion object {
+ private const val ANIMATION_DURATION = 300L
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/adapters/SimpleListAdapter.kt b/app/src/main/java/io/github/domi04151309/home/adapters/SimpleListAdapter.kt
new file mode 100644
index 0000000..efeea65
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/adapters/SimpleListAdapter.kt
@@ -0,0 +1,48 @@
+package io.github.domi04151309.home.adapters
+
+import android.annotation.SuppressLint
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.recyclerview.widget.RecyclerView
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+
+class SimpleListAdapter(
+ private val items: List,
+ private val helperInterface: RecyclerViewHelperInterface,
+) : RecyclerView.Adapter() {
+ override fun onCreateViewHolder(
+ parent: ViewGroup,
+ viewType: Int,
+ ): ViewHolder =
+ ViewHolder(
+ LayoutInflater
+ .from(parent.context)
+ .inflate(R.layout.list_item_simple, parent, false),
+ )
+
+ @SuppressLint("ClickableViewAccessibility")
+ override fun onBindViewHolder(
+ holder: ViewHolder,
+ position: Int,
+ ) {
+ holder.drawable.setImageResource(items[position].icon)
+ holder.title.text = items[position].title
+ holder.summary.text = items[position].summary
+ holder.hidden.text = items[position].hidden
+ holder.itemView.setOnClickListener { helperInterface.onItemClicked(holder.itemView, position) }
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ val drawable: ImageView = view.findViewById(R.id.drawable)
+ val title: TextView = view.findViewById(R.id.title)
+ val summary: TextView = view.findViewById(R.id.summary)
+ val hidden: TextView = view.findViewById(R.id.hidden)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/EspEasyAPI.kt b/app/src/main/java/io/github/domi04151309/home/api/EspEasyAPI.kt
new file mode 100644
index 0000000..1f551c0
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/EspEasyAPI.kt
@@ -0,0 +1,86 @@
+package io.github.domi04151309.home.api
+
+import android.content.Context
+import android.util.Log
+import com.android.volley.Request
+import com.android.volley.toolbox.JsonObjectRequest
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+
+class EspEasyAPI(
+ c: Context,
+ deviceId: String,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+) : UnifiedAPI(c, deviceId, recyclerViewInterface) {
+ private val parser = EspEasyAPIParser(c.resources, this)
+
+ override fun loadList(
+ callback: CallbackInterface,
+ extended: Boolean,
+ ) {
+ super.loadList(callback, extended)
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "json",
+ null,
+ { infoResponse ->
+ val listItems = parser.parseResponse(infoResponse)
+ updateCache(listItems)
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ listItems,
+ deviceId,
+ ),
+ recyclerViewInterface,
+ )
+ },
+ { error ->
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ null,
+ deviceId,
+ Global.volleyError(c, error),
+ ),
+ null,
+ )
+ },
+ )
+ queue.add(jsonObjectRequest)
+ }
+
+ override fun loadStates(
+ callback: RealTimeStatesCallback,
+ offset: Int,
+ ) {
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "json",
+ null,
+ { infoResponse ->
+ callback.onStatesLoaded(
+ parser.parseResponse(infoResponse),
+ offset,
+ )
+ },
+ { },
+ )
+ queue.add(jsonObjectRequest)
+ }
+
+ override fun changeSwitchState(
+ id: String,
+ state: Boolean,
+ ) {
+ val switchUrl = url + "control?cmd=GPIO," + id + "," + if (state) "1" else "0"
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ switchUrl,
+ { },
+ { e -> Log.e(Global.LOG_TAG, e.toString()) },
+ )
+ queue.add(jsonObjectRequest)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/EspEasyAPIParser.kt b/app/src/main/java/io/github/domi04151309/home/api/EspEasyAPIParser.kt
new file mode 100644
index 0000000..34d57e8
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/EspEasyAPIParser.kt
@@ -0,0 +1,118 @@
+package io.github.domi04151309.home.api
+
+import android.content.res.Resources
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import org.json.JSONArray
+import org.json.JSONObject
+
+class EspEasyAPIParser(resources: Resources, api: UnifiedAPI?) : UnifiedAPI.Parser(resources, api) {
+ override fun parseResponse(response: JSONObject): List {
+ val listItems = mutableListOf()
+
+ // sensors
+ val sensors = response.optJSONArray("Sensors") ?: JSONArray()
+ for (sensorId in 0 until sensors.length()) {
+ val currentSensor = sensors.getJSONObject(sensorId)
+ if (currentSensor.optString("TaskEnabled", FALSE).equals(FALSE)) {
+ continue
+ }
+
+ val type = currentSensor.optString("Type")
+ if (type.startsWith("Environment")) {
+ listItems.addAll(parseEnvironment(type, currentSensor))
+ } else if (type.startsWith("Switch")) {
+ listItems.addAll(parseSwitch(type, currentSensor))
+ }
+ }
+
+ return listItems
+ }
+
+ private fun parseEnvironment(
+ type: String,
+ currentSensor: JSONObject,
+ ): List {
+ val listItems = mutableListOf()
+ var taskIcons = intArrayOf()
+ when (type) {
+ "Environment - BMx280" -> {
+ taskIcons += R.drawable.ic_device_thermometer
+ taskIcons += R.drawable.ic_device_hygrometer
+ taskIcons += R.drawable.ic_device_gauge
+ }
+ "Environment - DHT11/12/22 SONOFF2301/7021" -> {
+ taskIcons += R.drawable.ic_device_thermometer
+ taskIcons += R.drawable.ic_device_hygrometer
+ }
+ "Environment - DS18b20" -> {
+ taskIcons += R.drawable.ic_device_thermometer
+ }
+ }
+
+ val taskName = currentSensor.getString("TaskName")
+ for (taskId in taskIcons.indices) {
+ val currentTask = currentSensor.getJSONArray(TASK_VALUES).getJSONObject(taskId)
+ val currentValue = currentTask.getString(VALUE)
+ if (!currentValue.equals("nan")) {
+ val suffix =
+ when (taskIcons[taskId]) {
+ R.drawable.ic_device_thermometer -> " °C"
+ R.drawable.ic_device_hygrometer -> " %"
+ R.drawable.ic_device_gauge -> " hPa"
+ else -> ""
+ }
+ listItems +=
+ ListViewItem(
+ title = currentValue + suffix,
+ summary = taskName + ": " + currentTask.getString("Name"),
+ icon = taskIcons[taskId],
+ )
+ }
+ }
+ return listItems
+ }
+
+ private fun parseSwitch(
+ type: String,
+ currentSensor: JSONObject,
+ ): List {
+ val listItems = mutableListOf()
+ when (type) {
+ "Switch input - Switch" -> {
+ val currentState = currentSensor.getJSONArray(TASK_VALUES).getJSONObject(0).getInt(VALUE) > 0
+ var taskName = currentSensor.getString("TaskName")
+ var gpioId = ""
+ val gpioFinder = Regex("~GPIO~([0-9]+)$")
+ val matchResult = gpioFinder.find(taskName)
+ if (matchResult != null && matchResult.groupValues.size > 1) {
+ gpioId = matchResult.groupValues[1]
+ taskName = taskName.replace("~GPIO~$gpioId", "")
+ }
+ listItems +=
+ ListViewItem(
+ title = taskName,
+ summary =
+ resources.getString(
+ if (currentState) {
+ R.string.switch_summary_on
+ } else {
+ R.string.switch_summary_off
+ },
+ ),
+ hidden = gpioId,
+ state = currentState,
+ icon = R.drawable.ic_do,
+ )
+ api?.needsRealTimeData = true
+ }
+ }
+ return listItems
+ }
+
+ companion object {
+ private const val FALSE = "false"
+ private const val TASK_VALUES = "TaskValues"
+ private const val VALUE = "Value"
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/HueAPI.kt b/app/src/main/java/io/github/domi04151309/home/api/HueAPI.kt
new file mode 100644
index 0000000..ad52c26
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/HueAPI.kt
@@ -0,0 +1,275 @@
+package io.github.domi04151309.home.api
+
+import android.content.Context
+import android.content.Intent
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import androidx.preference.PreferenceManager
+import com.android.volley.ParseError
+import com.android.volley.Request
+import com.android.volley.toolbox.JsonObjectRequest
+import io.github.domi04151309.home.activities.HueConnectActivity
+import io.github.domi04151309.home.activities.HueLampActivity
+import io.github.domi04151309.home.custom.CustomJsonArrayRequest
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.Global.volleyError
+import io.github.domi04151309.home.helpers.HueUtils
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import org.json.JSONArray
+import org.json.JSONObject
+
+@Suppress("TooManyFunctions")
+class HueAPI(
+ c: Context,
+ deviceId: String,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface? = null,
+) : UnifiedAPI(c, deviceId, recyclerViewInterface) {
+ private val parser = HueAPIParser(c.resources)
+ var readyForRequest: Boolean = true
+
+ init {
+ needsRealTimeData = true
+ }
+
+ interface RequestCallback {
+ fun onLightsLoaded(response: JSONObject?)
+ }
+
+ fun getUsername(): String =
+ PreferenceManager.getDefaultSharedPreferences(c)
+ .getString(deviceId, "")
+ ?: ""
+
+ // For unified API
+ override fun loadList(
+ callback: CallbackInterface,
+ extended: Boolean,
+ ) {
+ super.loadList(callback, extended)
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "api/${getUsername()}/groups",
+ null,
+ { response ->
+ val listItems = parser.parseResponse(response)
+ updateCache(listItems)
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ listItems,
+ deviceId,
+ ),
+ recyclerViewInterface,
+ )
+ },
+ { error ->
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ null,
+ deviceId,
+ volleyError(c, error),
+ ),
+ null,
+ )
+ if (error is ParseError) {
+ c.startActivity(
+ Intent(
+ c,
+ HueConnectActivity::class.java,
+ ).putExtra("deviceId", deviceId),
+ )
+ }
+ },
+ )
+ queue.add(jsonObjectRequest)
+ }
+
+ override fun loadStates(
+ callback: RealTimeStatesCallback,
+ offset: Int,
+ ) {
+ if (!readyForRequest) return
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "api/${getUsername()}/groups",
+ null,
+ { response ->
+ callback.onStatesLoaded(parser.parseResponse(response), offset)
+ },
+ { },
+ )
+ queue.add(jsonObjectRequest)
+ }
+
+ override fun execute(
+ path: String,
+ callback: CallbackInterface,
+ ) {
+ c.startActivity(
+ Intent(c, HueLampActivity::class.java)
+ .putExtra("id", path)
+ .putExtra(Devices.INTENT_EXTRA_DEVICE, deviceId),
+ )
+ }
+
+ override fun changeSwitchState(
+ id: String,
+ state: Boolean,
+ ) {
+ switchGroupById(id, state)
+ }
+
+ override fun changePercentage(
+ id: String,
+ percentage: Float,
+ ) {
+ changeBrightnessOfGroup(id, (percentage / MAX_PERCENTAGE * HueUtils.MAX_BRIGHTNESS).toInt())
+ }
+
+ fun loadLightsByIds(
+ lightIds: JSONArray,
+ callback: RequestCallback,
+ ) {
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "api/${getUsername()}/lights",
+ null,
+ { response ->
+ val returnObject = JSONObject()
+ var lightId: String
+ for (i in 0 until lightIds.length()) {
+ lightId = lightIds.getString(i)
+ returnObject.put(lightId, response.getJSONObject(lightId))
+ }
+ callback.onLightsLoaded(returnObject)
+ },
+ { callback.onLightsLoaded(null) },
+ )
+ queue.add(jsonObjectRequest)
+ }
+
+ fun switchLightById(
+ lightId: String,
+ on: Boolean,
+ ) {
+ putObject(getLightPath(lightId), "{\"on\":$on}")
+ }
+
+ fun changeBrightness(
+ lightId: String,
+ bri: Int,
+ ) {
+ putObject(getLightPath(lightId), "{\"bri\":$bri}")
+ }
+
+ fun changeColorTemperature(
+ lightId: String,
+ ct: Int,
+ ) {
+ putObject(getLightPath(lightId), "{\"ct\":$ct}")
+ }
+
+ fun changeHue(
+ lightId: String,
+ hue: Int,
+ ) {
+ putObject(getLightPath(lightId), "{\"hue\":$hue}")
+ }
+
+ fun changeSaturation(
+ lightId: String,
+ sat: Int,
+ ) {
+ putObject(getLightPath(lightId), "{\"sat\":$sat}")
+ }
+
+ fun changeHueSat(
+ lightId: String,
+ hue: Int,
+ sat: Int,
+ ) {
+ putObject(getLightPath(lightId), """{ "hue": $hue, "sat": $sat }""")
+ }
+
+ fun switchGroupById(
+ groupId: String,
+ on: Boolean,
+ ) {
+ putObject(getGroupPath(groupId), "{\"on\":$on}")
+ }
+
+ fun changeBrightnessOfGroup(
+ groupId: String,
+ bri: Int,
+ ) {
+ putObject(getGroupPath(groupId), "{\"bri\":$bri}")
+ }
+
+ fun changeColorTemperatureOfGroup(
+ groupId: String,
+ ct: Int,
+ ) {
+ putObject(getGroupPath(groupId), "{\"ct\":$ct}")
+ }
+
+ fun changeHueOfGroup(
+ groupId: String,
+ hue: Int,
+ ) {
+ putObject(getGroupPath(groupId), "{\"hue\":$hue}")
+ }
+
+ fun changeSaturationOfGroup(
+ groupId: String,
+ sat: Int,
+ ) {
+ putObject(getGroupPath(groupId), "{\"sat\":$sat}")
+ }
+
+ fun changeHueSatOfGroup(
+ groupId: String,
+ hue: Int,
+ sat: Int,
+ ) {
+ putObject(getGroupPath(groupId), """{ "hue": $hue, "sat": $sat }""")
+ }
+
+ fun activateSceneOfGroup(
+ groupId: String,
+ scene: String,
+ ) {
+ putObject(getGroupPath(groupId), """{ "scene": $scene }""")
+ }
+
+ private fun getLightPath(lightId: String) = "/lights/$lightId/state"
+
+ private fun getGroupPath(groupId: String) = "/groups/$groupId/action"
+
+ private fun putObject(
+ address: String,
+ requestObject: String,
+ ) {
+ val request =
+ CustomJsonArrayRequest(
+ Request.Method.PUT,
+ url + "api/${getUsername()}$address",
+ JSONObject(requestObject),
+ { },
+ { e -> Log.e(Global.LOG_TAG, e.toString()) },
+ )
+ if (readyForRequest) {
+ readyForRequest = false
+ queue.add(request)
+ Handler(Looper.getMainLooper()).postDelayed({ readyForRequest = true }, UPDATE_DELAY)
+ }
+ }
+
+ companion object {
+ private const val UPDATE_DELAY = 100L
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/HueAPIParser.kt b/app/src/main/java/io/github/domi04151309/home/api/HueAPIParser.kt
new file mode 100644
index 0000000..a04802a
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/HueAPIParser.kt
@@ -0,0 +1,174 @@
+package io.github.domi04151309.home.api
+
+import android.content.res.Resources
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.data.SimpleListItem
+import io.github.domi04151309.home.helpers.HueUtils
+import org.json.JSONObject
+import java.util.TreeMap
+import kotlin.collections.ArrayList
+
+class HueAPIParser(resources: Resources) : UnifiedAPI.Parser(resources) {
+ override fun parseResponse(response: JSONObject): List {
+ val listItems: ArrayList = ArrayList(response.length())
+ val rooms: TreeMap> = TreeMap()
+ val zones: TreeMap> = TreeMap()
+ var currentObject: JSONObject
+ for (i in response.keys()) {
+ currentObject = response.getJSONObject(i)
+ when (currentObject.getString("type")) {
+ "Room" -> rooms[currentObject.getString("name")] = Pair(i, currentObject)
+ "Zone" -> zones[currentObject.getString("name")] = Pair(i, currentObject)
+ }
+ }
+ for (i in rooms.keys) listItems.add(
+ parseGroupObj(
+ rooms[i] ?: error("Room $i does not exist."),
+ false,
+ ),
+ )
+ for (i in zones.keys) listItems.add(
+ parseGroupObj(
+ zones[i] ?: error("Zone $i does not exist."),
+ true,
+ ),
+ )
+ return listItems
+ }
+
+ private fun parseGroupObj(
+ pair: Pair,
+ isZone: Boolean,
+ ): ListViewItem {
+ val state = pair.second.optJSONObject(STATE)?.optBoolean(ANY_ON)
+ val value =
+ pair.second.optJSONObject(ACTION)?.optInt(
+ BRI,
+ HueUtils.MAX_BRIGHTNESS,
+ ) ?: HueUtils.MAX_BRIGHTNESS
+ return ListViewItem(
+ title = pair.second.getString("name"),
+ summary =
+ resources.getString(R.string.hue_brightness) +
+ ": " + if (state == true) HueUtils.briToPercent(value) else "0 %",
+ hidden = pair.first,
+ icon = if (isZone) R.drawable.ic_zone else R.drawable.ic_room,
+ state = state,
+ percentage = (value / HueUtils.MAX_BRIGHTNESS.toFloat() * 100).toInt(),
+ )
+ }
+
+ companion object {
+ private const val STATE = "state"
+ private const val ANY_ON = "any_on"
+
+ private const val ACTION = "action"
+ private const val BRI = "bri"
+
+ fun parseHueConfig(
+ resources: Resources,
+ response: JSONObject,
+ ): List =
+ listOf(
+ SimpleListItem(summary = resources.getString(R.string.hue_bridge)),
+ SimpleListItem(
+ response.optString("name"),
+ resources.getString(R.string.hue_bridge_name),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ response.optString("modelid"),
+ resources.getString(R.string.hue_bridge_model),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ response.optString("bridgeid"),
+ resources.getString(R.string.hue_bridge_id),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ response.optString("swversion"),
+ resources.getString(R.string.hue_bridge_software),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ response.optString("zigbeechannel"),
+ resources.getString(R.string.hue_bridge_zigbee),
+ icon = R.drawable.ic_about_info,
+ ),
+ SimpleListItem(
+ response.optString("timezone"),
+ resources.getString(R.string.hue_bridge_time_zone),
+ icon = R.drawable.ic_about_info,
+ ),
+ )
+
+ fun parseHueSensors(
+ resources: Resources,
+ response: JSONObject,
+ ): List {
+ val sensorItems = mutableListOf()
+ for (i in response.keys()) {
+ val current = response.optJSONObject(i) ?: JSONObject()
+ val config = current.optJSONObject("config") ?: JSONObject()
+ if (config.has("battery")) {
+ sensorItems.add(
+ SimpleListItem(
+ current.optString("name"),
+ config.optString("battery") + "%",
+ icon =
+ if (config.optBoolean("reachable")) {
+ R.drawable.ic_device_raspberry_pi
+ } else {
+ R.drawable.ic_warning
+ },
+ ),
+ )
+ }
+ }
+ val items = mutableListOf(SimpleListItem(summary = resources.getString(R.string.hue_controls)))
+ items.addAll(sensorItems.sortedBy { it.title })
+ return items
+ }
+
+ fun parseHueLights(
+ resources: Resources,
+ response: JSONObject,
+ ): List {
+ val lightItems = mutableListOf()
+ for (i in response.keys()) {
+ val current =
+ response.optJSONObject(i)
+ ?: JSONObject()
+ val state =
+ current.optJSONObject(STATE) ?: JSONObject()
+ lightItems.add(
+ SimpleListItem(
+ current.optString("name"),
+ (
+ if (state.optBoolean("on")) {
+ resources.getString(
+ R.string.str_on,
+ )
+ } else {
+ resources.getString(R.string.str_off)
+ }
+ ) +
+ " · " +
+ current.optString("productname"),
+ icon =
+ if (state.optBoolean("reachable")) {
+ R.drawable.ic_device_lamp
+ } else {
+ R.drawable.ic_warning
+ },
+ ),
+ )
+ }
+ val items = mutableListOf(SimpleListItem(summary = resources.getString(R.string.hue_lights)))
+ items.addAll(lightItems.sortedBy { it.title })
+ return items
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/ShellyAPI.kt b/app/src/main/java/io/github/domi04151309/home/api/ShellyAPI.kt
new file mode 100644
index 0000000..3e5b21b
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/ShellyAPI.kt
@@ -0,0 +1,244 @@
+package io.github.domi04151309.home.api
+
+import android.content.Context
+import android.util.Log
+import com.android.volley.Request
+import com.android.volley.Response
+import com.android.volley.toolbox.JsonObjectRequest
+import io.github.domi04151309.home.custom.JsonObjectRequestAuth
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.DeviceSecrets
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+
+class ShellyAPI(
+ c: Context,
+ deviceId: String,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ private val version: Int,
+) : UnifiedAPI(c, deviceId, recyclerViewInterface) {
+ private val secrets = DeviceSecrets(c, deviceId)
+ private val parser = ShellyAPIParser(c.resources, version)
+
+ init {
+ needsRealTimeData = true
+ }
+
+ override fun loadList(
+ callback: CallbackInterface,
+ extended: Boolean,
+ ) {
+ super.loadList(callback, extended)
+ val jsonObjectRequest =
+ when (version) {
+ 1 -> listRequestV1(callback)
+ 2 -> listRequestV2(callback)
+ else -> null
+ }
+ queue.add(jsonObjectRequest)
+ }
+
+ private fun listRequestV1(callback: CallbackInterface) =
+ JsonObjectRequestAuth(
+ Request.Method.GET,
+ url + SETTINGS,
+ secrets,
+ null,
+ { settingsResponse ->
+ queue.add(
+ JsonObjectRequestAuth(
+ Request.Method.GET,
+ url + "status",
+ secrets,
+ null,
+ { statusResponse ->
+ val listItems = parser.parseResponse(settingsResponse, statusResponse)
+ updateCache(listItems)
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ listItems,
+ deviceId,
+ ),
+ recyclerViewInterface,
+ )
+ },
+ { error ->
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ null,
+ deviceId,
+ Global.volleyError(c, error),
+ ),
+ null,
+ )
+ },
+ ),
+ )
+ },
+ { error ->
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ null,
+ deviceId,
+ Global.volleyError(c, error),
+ ),
+ null,
+ )
+ },
+ )
+
+ private fun listRequestV2(callback: CallbackInterface) =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "rpc/Shelly.GetConfig",
+ null,
+ { configResponse ->
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "rpc/Shelly.GetStatus",
+ null,
+ { statusResponse ->
+ val listItems = parser.parseResponse(configResponse, statusResponse)
+ updateCache(listItems)
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ listItems,
+ deviceId,
+ ),
+ recyclerViewInterface,
+ )
+ },
+ { error ->
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ null,
+ deviceId,
+ Global.volleyError(c, error),
+ ),
+ null,
+ )
+ },
+ ),
+ )
+ },
+ { error ->
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ null,
+ deviceId,
+ Global.volleyError(c, error),
+ ),
+ null,
+ )
+ },
+ )
+
+ override fun loadStates(
+ callback: RealTimeStatesCallback,
+ offset: Int,
+ ) {
+ val jsonObjectRequest =
+ when (version) {
+ 1 ->
+ JsonObjectRequestAuth(
+ Request.Method.GET,
+ url + SETTINGS,
+ secrets,
+ null,
+ { settingsResponse ->
+ queue.add(
+ JsonObjectRequestAuth(
+ Request.Method.GET,
+ url + "status",
+ secrets,
+ null,
+ { statusResponse ->
+ callback.onStatesLoaded(
+ parser.parseResponse(settingsResponse, statusResponse),
+ offset,
+ )
+ },
+ { },
+ ),
+ )
+ },
+ { },
+ )
+ 2 ->
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "rpc/Shelly.GetConfig",
+ null,
+ { configResponse ->
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "rpc/Shelly.GetStatus",
+ null,
+ { statusResponse ->
+ callback.onStatesLoaded(
+ parser.parseResponse(configResponse, statusResponse),
+ offset,
+ )
+ },
+ { },
+ ),
+ )
+ },
+ { },
+ )
+ else -> null
+ }
+ queue.add(jsonObjectRequest)
+ }
+
+ override fun changeSwitchState(
+ id: String,
+ state: Boolean,
+ ) {
+ val requestUrl = url + "relay/$id?turn=" + if (state) "on" else "off"
+ val jsonObjectRequest =
+ when (version) {
+ 1 ->
+ JsonObjectRequestAuth(
+ Request.Method.GET,
+ requestUrl,
+ secrets,
+ null,
+ { },
+ { e -> Log.e(Global.LOG_TAG, e.toString()) },
+ )
+ 2 ->
+ JsonObjectRequest(
+ Request.Method.GET,
+ requestUrl,
+ null,
+ { },
+ { e -> Log.e(Global.LOG_TAG, e.toString()) },
+ )
+ else -> null
+ }
+ queue.add(jsonObjectRequest)
+ }
+
+ companion object {
+ private const val SETTINGS = "settings"
+
+ /**
+ * Detect the name of the shelly device during discovery.
+ */
+ fun loadName(
+ url: String,
+ version: Int,
+ listener: Response.Listener,
+ ): JsonObjectRequest =
+ JsonObjectRequest(
+ url + if (version == 1) SETTINGS else "shelly",
+ { statusResponse ->
+ listener.onResponse(if (statusResponse.isNull("name")) "" else statusResponse.optString("name"))
+ },
+ {},
+ )
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/ShellyAPIParser.kt b/app/src/main/java/io/github/domi04151309/home/api/ShellyAPIParser.kt
new file mode 100644
index 0000000..3d7e5ad
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/ShellyAPIParser.kt
@@ -0,0 +1,233 @@
+package io.github.domi04151309.home.api
+
+import android.content.res.Resources
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.helpers.Global
+import org.json.JSONArray
+import org.json.JSONObject
+import java.text.DecimalFormat
+
+class ShellyAPIParser(resources: Resources, private val version: Int) :
+ UnifiedAPI.Parser(resources) {
+ fun parseResponse(
+ config: JSONObject,
+ status: JSONObject,
+ ): List =
+ if (version == 1) {
+ parseResponseV1(config, status)
+ } else {
+ parseResponseV2(config, status)
+ }
+
+ private fun parseResponseV1(
+ settings: JSONObject,
+ status: JSONObject,
+ ): List {
+ val listItems = mutableListOf()
+ listItems.addAll(parseSwitchesAndMetersV1(settings, status))
+ listItems.addAll(parseTemperatureSensorsV1(status))
+ listItems.addAll(parseHumiditySensorsV1(status))
+ return listItems
+ }
+
+ private fun parseSwitchesAndMetersV1(
+ settings: JSONObject,
+ status: JSONObject,
+ ): List {
+ val listItems = mutableListOf()
+
+ // switches
+ val relays = settings.optJSONArray("relays") ?: JSONArray()
+ var currentRelay: JSONObject
+ var currentState: Boolean
+ var hideMeters = false
+ for (relayId in 0 until relays.length()) {
+ currentRelay = relays.getJSONObject(relayId)
+ currentState = currentRelay.getBoolean("ison")
+
+ listItems +=
+ ListViewItem(
+ title =
+ nameOrDefault(
+ if (currentRelay.isNull("name")) "" else currentRelay.optString("name"),
+ relayId,
+ ),
+ summary =
+ resources.getString(
+ if (currentState) {
+ R.string.switch_summary_on
+ } else {
+ R.string.switch_summary_off
+ },
+ ),
+ hidden = relayId.toString(),
+ state = currentState,
+ icon = Global.getIcon(currentRelay.optString("appliance_type"), R.drawable.ic_do),
+ )
+ // Shelly1 has the "user power constant" setting, but no actual meter
+ hideMeters = currentRelay.has("power")
+ }
+
+ // power meters
+ val meters = if (hideMeters) JSONArray() else status.optJSONArray("meters") ?: JSONArray()
+ var currentMeter: JSONObject
+ for (meterId in 0 until meters.length()) {
+ currentMeter = meters.getJSONObject(meterId)
+ listItems +=
+ ListViewItem(
+ title = "${currentMeter.getDouble("power")} W",
+ summary = resources.getString(R.string.shelly_powermeter_summary),
+ icon = R.drawable.ic_device_electricity,
+ )
+ }
+
+ return listItems
+ }
+
+ private fun parseTemperatureSensorsV1(status: JSONObject): List {
+ val listItems = mutableListOf()
+ val tempSensors = status.optJSONObject("ext_temperature") ?: JSONObject()
+ for (sensorId in tempSensors.keys()) {
+ val currentSensor = tempSensors.getJSONObject(sensorId)
+ listItems +=
+ ListViewItem(
+ title = "${currentSensor.getDouble("tC")} °C",
+ summary = resources.getString(R.string.shelly_temperature_sensor_summary),
+ icon = R.drawable.ic_device_thermometer,
+ )
+ }
+ return listItems
+ }
+
+ private fun parseHumiditySensorsV1(status: JSONObject): List {
+ val listItems = mutableListOf()
+ val humSensors = status.optJSONObject("ext_humidity") ?: JSONObject()
+ for (sensorId in humSensors.keys()) {
+ val currentSensor = humSensors.getJSONObject(sensorId)
+ listItems +=
+ ListViewItem(
+ title = "${currentSensor.getDouble("hum")}%",
+ summary = resources.getString(R.string.shelly_humidity_sensor_summary),
+ icon = R.drawable.ic_device_hygrometer,
+ )
+ }
+ return listItems
+ }
+
+ private fun parseResponseV2(
+ config: JSONObject,
+ status: JSONObject,
+ ): List {
+ val listItems = mutableListOf()
+ for (switchKey in config.keys()) {
+ if (switchKey.startsWith("switch:")) {
+ listItems.addAll(
+ parseSwitchV2(
+ config.getJSONObject(switchKey),
+ status.getJSONObject(switchKey),
+ config,
+ ),
+ )
+ } else if (switchKey.startsWith("pm1:")) {
+ listItems.addAll(parsePowermeter1V2(config.getJSONObject(switchKey), status.getJSONObject(switchKey)))
+ }
+ }
+ return listItems
+ }
+
+ private fun parsePowermeter1V2(
+ pm1Config: JSONObject,
+ pm1Status: JSONObject,
+ ): List {
+ val listItems = mutableListOf()
+ val currentId = pm1Config.getInt("id").toString()
+ val format = DecimalFormat("#.###")
+
+ listItems +=
+ ListViewItem(
+ title = "${format.format(pm1Status.getDouble("apower"))} W",
+ summary = resources.getString(R.string.shelly_powermeter_summary),
+ hidden = currentId,
+ icon = R.drawable.ic_device_electricity,
+ )
+ listItems +=
+ ListViewItem(
+ title = "${format.format(pm1Status.getDouble("current"))} A",
+ summary = resources.getString(R.string.shelly_powermeter_current),
+ hidden = currentId + "c",
+ )
+ listItems +=
+ ListViewItem(
+ title = "${format.format(pm1Status.getDouble("voltage"))} V",
+ summary = resources.getString(R.string.shelly_powermeter_voltage),
+ hidden = currentId + "v",
+ )
+ listItems +=
+ ListViewItem(
+ title = "${format.format(pm1Status.getJSONObject("aenergy").getDouble("total") / KILO)} kWh",
+ summary = resources.getString(R.string.shelly_powermeter_energy),
+ hidden = currentId + "e",
+ )
+ listItems +=
+ ListViewItem(
+ title = "${format.format(pm1Status.getJSONObject("ret_aenergy").getDouble("total") / KILO)} kWh",
+ summary = resources.getString(R.string.shelly_powermeter_return_energy),
+ hidden = currentId + "rete",
+ )
+
+ return listItems
+ }
+
+ private fun parseSwitchV2(
+ switchConfig: JSONObject,
+ switchStatus: JSONObject,
+ config: JSONObject,
+ ): List {
+ val listItems = mutableListOf()
+ val currentId = switchConfig.getInt("id")
+ val currentState = switchStatus.getBoolean("output")
+
+ listItems +=
+ ListViewItem(
+ title =
+ nameOrDefault(
+ if (switchConfig.isNull("name")) "" else switchConfig.getString("name"),
+ currentId,
+ ),
+ summary =
+ resources.getString(
+ if (currentState) {
+ R.string.switch_summary_on
+ } else {
+ R.string.switch_summary_off
+ },
+ ),
+ hidden = currentId.toString(),
+ state = currentState,
+ icon =
+ Global.getIcon(
+ config.optJSONObject("sys")?.optJSONObject("ui_data")
+ ?.optJSONArray("consumption_types")
+ ?.getString(currentId)
+ ?: "",
+ R.drawable.ic_do,
+ ),
+ )
+ return listItems
+ }
+
+ private fun nameOrDefault(
+ name: String,
+ id: Int,
+ ): String =
+ if (name.trim().isEmpty()) {
+ resources.getString(R.string.shelly_switch_title, id + 1)
+ } else {
+ name
+ }
+
+ companion object {
+ private const val KILO = 1000
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/SimpleHomeAPI.kt b/app/src/main/java/io/github/domi04151309/home/api/SimpleHomeAPI.kt
new file mode 100644
index 0000000..a251c51
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/SimpleHomeAPI.kt
@@ -0,0 +1,137 @@
+package io.github.domi04151309.home.api
+
+import android.content.Context
+import android.util.Log
+import android.view.LayoutInflater
+import android.view.ViewGroup
+import android.widget.EditText
+import com.android.volley.Request
+import com.android.volley.toolbox.JsonObjectRequest
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.Global.volleyError
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import java.net.URLEncoder
+
+class SimpleHomeAPI(
+ c: Context,
+ deviceId: String,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+) : UnifiedAPI(c, deviceId, recyclerViewInterface) {
+ private val parser = SimpleHomeAPIParser(c.resources, this)
+
+ override fun loadList(
+ callback: CallbackInterface,
+ extended: Boolean,
+ ) {
+ super.loadList(callback, extended)
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "commands",
+ null,
+ { response ->
+ val listItems = parser.parseResponse(response)
+ updateCache(listItems)
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(
+ listItems,
+ deviceId,
+ ),
+ recyclerViewInterface,
+ )
+ },
+ { error ->
+ callback.onItemsLoaded(UnifiedRequestCallback(null, deviceId, volleyError(c, error)), null)
+ },
+ )
+ queue.add(jsonObjectRequest)
+ }
+
+ override fun loadStates(
+ callback: RealTimeStatesCallback,
+ offset: Int,
+ ) {
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + "commands",
+ null,
+ { infoResponse ->
+ callback.onStatesLoaded(
+ parser.parseResponse(infoResponse),
+ offset,
+ )
+ },
+ { },
+ )
+ queue.add(jsonObjectRequest)
+ }
+
+ override fun execute(
+ path: String,
+ callback: CallbackInterface,
+ ) {
+ val splitCharPos = path.lastIndexOf('@')
+ val realPath = path.substring(splitCharPos + 1)
+ when (path.substring(0, splitCharPos)) {
+ "none", "switch" -> { }
+ "input" -> {
+ val nullParent: ViewGroup? = null
+ val view = LayoutInflater.from(c).inflate(R.layout.dialog_input, nullParent, false)
+ val input = view.findViewById(R.id.input)
+ MaterialAlertDialogBuilder(c)
+ .setTitle(R.string.input_title)
+ .setView(view)
+ .setPositiveButton(R.string.str_send) { _, _ ->
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + realPath + "?input=" + URLEncoder.encode(input.text.toString(), "utf-8"),
+ null,
+ { },
+ { e -> Log.e(Global.LOG_TAG, e.toString()) },
+ )
+ queue.add(jsonObjectRequest)
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ }
+ else -> {
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + realPath,
+ null,
+ { response ->
+ callback.onExecuted(
+ response.optString("toast", c.resources.getString(R.string.main_execution_completed)),
+ response.optBoolean("refresh", false),
+ )
+ },
+ { error ->
+ callback.onExecuted(volleyError(c, error))
+ },
+ )
+ queue.add(jsonObjectRequest)
+ }
+ }
+ }
+
+ override fun changeSwitchState(
+ id: String,
+ state: Boolean,
+ ) {
+ val jsonObjectRequest =
+ JsonObjectRequest(
+ Request.Method.GET,
+ url + id.substring(id.lastIndexOf('@') + 1) + "?input=" + if (state) 1 else 0,
+ null,
+ { },
+ { e -> Log.e(Global.LOG_TAG, e.toString()) },
+ )
+ queue.add(jsonObjectRequest)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/SimpleHomeAPIParser.kt b/app/src/main/java/io/github/domi04151309/home/api/SimpleHomeAPIParser.kt
new file mode 100644
index 0000000..9ac9bd8
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/SimpleHomeAPIParser.kt
@@ -0,0 +1,34 @@
+package io.github.domi04151309.home.api
+
+import android.content.res.Resources
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.helpers.Global
+import org.json.JSONObject
+
+class SimpleHomeAPIParser(resources: Resources, api: UnifiedAPI?) : UnifiedAPI.Parser(resources, api) {
+ override fun parseResponse(response: JSONObject): List {
+ val listItems: ArrayList = ArrayList(response.length())
+ val commands = response.optJSONObject("commands") ?: return listItems
+ var currentObject: JSONObject
+ var currentMode: String
+ for (i in commands.keys()) {
+ currentObject = commands.getJSONObject(i)
+ currentMode = currentObject.optString("mode", "action")
+ listItems +=
+ ListViewItem(
+ title = currentObject.optString("title"),
+ summary = currentObject.optString("summary"),
+ hidden = "$currentMode@$i",
+ icon = Global.getIcon(currentObject.optString("icon"), R.drawable.ic_do),
+ state = if (currentMode == SWITCH) currentObject.optBoolean("data", false) else null,
+ )
+ if (currentMode == SWITCH) api?.needsRealTimeData = true
+ }
+ return listItems
+ }
+
+ companion object {
+ private const val SWITCH = "switch"
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/Tasmota.kt b/app/src/main/java/io/github/domi04151309/home/api/Tasmota.kt
new file mode 100644
index 0000000..8710b5c
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/Tasmota.kt
@@ -0,0 +1,97 @@
+package io.github.domi04151309.home.api
+
+import android.content.Context
+import android.util.Log
+import android.widget.Toast
+import androidx.preference.PreferenceManager
+import com.android.volley.Request
+import com.android.volley.toolbox.StringRequest
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.TasmotaHelper
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import org.json.JSONArray
+import org.json.JSONException
+import org.json.JSONObject
+
+class Tasmota(
+ c: Context,
+ deviceId: String,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+) : UnifiedAPI(c, deviceId, recyclerViewInterface) {
+ private val prefs = PreferenceManager.getDefaultSharedPreferences(c)
+
+ override fun loadList(
+ callback: CallbackInterface,
+ extended: Boolean,
+ ) {
+ super.loadList(callback, extended)
+ val list = JSONArray(prefs.getString(deviceId, TasmotaHelper.EMPTY_ARRAY))
+ val listItems: ArrayList = ArrayList(list.length())
+ if (list.length() == 0) {
+ listItems +=
+ ListViewItem(
+ title = c.resources.getString(R.string.tasmota_empty_list),
+ summary = c.resources.getString(R.string.tasmota_empty_list_summary),
+ icon = R.drawable.ic_warning,
+ )
+ } else {
+ var currentItem: JSONObject
+ for (i in 0 until list.length()) {
+ try {
+ currentItem = list.optJSONObject(i) ?: JSONObject()
+ listItems +=
+ ListViewItem(
+ title = currentItem.optString("title"),
+ summary = currentItem.optString("command"),
+ hidden = "tasmota_command#$i",
+ icon = R.drawable.ic_do,
+ )
+ } catch (e: JSONException) {
+ Log.e(Global.LOG_TAG, e.toString())
+ }
+ }
+ }
+
+ if (extended) {
+ listItems +=
+ ListViewItem(
+ title = c.resources.getString(R.string.tasmota_add_command),
+ summary = c.resources.getString(R.string.tasmota_add_command_summary),
+ icon = R.drawable.ic_add,
+ hidden = "add",
+ )
+
+ listItems +=
+ ListViewItem(
+ title = c.resources.getString(R.string.tasmota_execute_once),
+ summary = c.resources.getString(R.string.tasmota_execute_once_summary),
+ icon = R.drawable.ic_edit,
+ hidden = "execute_once",
+ )
+ }
+
+ updateCache(listItems)
+ callback.onItemsLoaded(UnifiedRequestCallback(listItems, deviceId), recyclerViewInterface)
+ }
+
+ override fun execute(
+ path: String,
+ callback: CallbackInterface,
+ ) {
+ val request =
+ StringRequest(
+ Request.Method.GET,
+ url + path,
+ { response ->
+ callback.onExecuted(response)
+ },
+ { error ->
+ Toast.makeText(c, Global.volleyError(c, error), Toast.LENGTH_LONG).show()
+ },
+ )
+ queue.add(request)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/api/UnifiedAPI.kt b/app/src/main/java/io/github/domi04151309/home/api/UnifiedAPI.kt
new file mode 100644
index 0000000..8948aa3
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/api/UnifiedAPI.kt
@@ -0,0 +1,89 @@
+package io.github.domi04151309.home.api
+
+import android.content.Context
+import android.content.res.Resources
+import com.android.volley.RequestQueue
+import com.android.volley.toolbox.Volley
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import org.json.JSONObject
+
+open class UnifiedAPI(
+ protected val c: Context,
+ val deviceId: String,
+ protected val recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+) {
+ interface CallbackInterface {
+ fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ )
+
+ fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean = false,
+ )
+ }
+
+ interface RealTimeStatesCallback {
+ fun onStatesLoaded(
+ states: List,
+ offset: Int,
+ )
+ }
+
+ var needsRealTimeData: Boolean = false
+
+ protected val url: String = Devices(c).getDeviceById(deviceId).address
+ protected val queue: RequestQueue = Volley.newRequestQueue(c)
+
+ protected fun updateCache(items: List) {
+ listCache[deviceId] = Pair(System.currentTimeMillis(), items)
+ }
+
+ open fun loadList(
+ callback: CallbackInterface,
+ extended: Boolean = false,
+ ) {
+ if (System.currentTimeMillis() - (listCache[deviceId]?.first ?: 0) < LIST_REQUEST_TIMEOUT) {
+ callback.onItemsLoaded(
+ UnifiedRequestCallback(listCache[deviceId]?.second, deviceId),
+ recyclerViewInterface,
+ )
+ return
+ }
+ }
+
+ open fun loadStates(
+ callback: RealTimeStatesCallback,
+ offset: Int,
+ ) {}
+
+ open fun execute(
+ path: String,
+ callback: CallbackInterface,
+ ) {}
+
+ open fun changeSwitchState(
+ id: String,
+ state: Boolean,
+ ) {}
+
+ open fun changePercentage(
+ id: String,
+ percentage: Float,
+ ) {}
+
+ open class Parser(protected val resources: Resources, protected val api: UnifiedAPI? = null) {
+ open fun parseResponse(response: JSONObject): List = listOf()
+ }
+
+ companion object {
+ private const val LIST_REQUEST_TIMEOUT = 1000
+ private val listCache: MutableMap>> = mutableMapOf()
+
+ protected const val MAX_PERCENTAGE = 100f
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/custom/CustomJsonArrayRequest.kt b/app/src/main/java/io/github/domi04151309/home/custom/CustomJsonArrayRequest.kt
new file mode 100644
index 0000000..3df8287
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/custom/CustomJsonArrayRequest.kt
@@ -0,0 +1,33 @@
+package io.github.domi04151309.home.custom
+
+import com.android.volley.NetworkResponse
+import com.android.volley.ParseError
+import com.android.volley.Response
+import com.android.volley.toolbox.HttpHeaderParser
+import com.android.volley.toolbox.JsonRequest
+import org.json.JSONArray
+import org.json.JSONException
+import org.json.JSONObject
+import java.io.UnsupportedEncodingException
+import java.nio.charset.Charset
+
+class CustomJsonArrayRequest(
+ method: Int,
+ url: String,
+ jsonRequest: JSONObject?,
+ listener: Response.Listener,
+ errorListener: Response.ErrorListener,
+) : JsonRequest(method, url, jsonRequest?.toString(), listener, errorListener) {
+ override fun parseNetworkResponse(response: NetworkResponse): Response =
+ try {
+ val jsonString = String(response.data, Charset.forName(HttpHeaderParser.parseCharset(response.headers)))
+ Response.success(
+ JSONArray(jsonString),
+ HttpHeaderParser.parseCacheHeaders(response),
+ )
+ } catch (e: UnsupportedEncodingException) {
+ Response.error(ParseError(e))
+ } catch (e: JSONException) {
+ Response.error(ParseError(e))
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/custom/JsonObjectRequestAuth.kt b/app/src/main/java/io/github/domi04151309/home/custom/JsonObjectRequestAuth.kt
new file mode 100644
index 0000000..c4aae74
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/custom/JsonObjectRequestAuth.kt
@@ -0,0 +1,26 @@
+package io.github.domi04151309.home.custom
+
+import android.util.Base64
+import com.android.volley.Response
+import com.android.volley.toolbox.JsonObjectRequest
+import io.github.domi04151309.home.helpers.DeviceSecrets
+import org.json.JSONObject
+
+class JsonObjectRequestAuth(
+ method: Int,
+ url: String,
+ private val secrets: DeviceSecrets,
+ jsonRequest: JSONObject?,
+ listener: Response.Listener,
+ errorListener: Response.ErrorListener,
+) : JsonObjectRequest(method, url, jsonRequest, listener, errorListener) {
+ override fun getHeaders(): MutableMap {
+ val params = HashMap()
+ params["Authorization"] = "Basic " +
+ Base64.encodeToString(
+ "${secrets.username}:${secrets.password}".toByteArray(),
+ Base64.NO_WRAP,
+ )
+ return params
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/custom/TextWatcher.kt b/app/src/main/java/io/github/domi04151309/home/custom/TextWatcher.kt
new file mode 100644
index 0000000..c29b2eb
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/custom/TextWatcher.kt
@@ -0,0 +1,28 @@
+package io.github.domi04151309.home.custom
+
+import android.text.Editable
+import android.text.TextWatcher
+
+class TextWatcher(private val lambda: (text: String) -> Unit) : TextWatcher {
+ override fun beforeTextChanged(
+ p0: CharSequence,
+ p1: Int,
+ p2: Int,
+ p3: Int,
+ ) {
+ // Do nothing.
+ }
+
+ override fun onTextChanged(
+ p0: CharSequence,
+ p1: Int,
+ p2: Int,
+ p3: Int,
+ ) {
+ // Do nothing.
+ }
+
+ override fun afterTextChanged(text: Editable) {
+ lambda(text.toString())
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/data/DeviceItem.kt b/app/src/main/java/io/github/domi04151309/home/data/DeviceItem.kt
new file mode 100644
index 0000000..39b34d7
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/data/DeviceItem.kt
@@ -0,0 +1,31 @@
+package io.github.domi04151309.home.data
+
+import io.github.domi04151309.home.helpers.Global
+
+class DeviceItem(
+ val id: String,
+ val name: String = "Device",
+ val mode: String = "Default",
+ val iconName: String = "Lamp",
+ val hide: Boolean = false,
+ val directView: Boolean = false,
+) {
+ var address: String = "http://127.0.0.1/"
+ set(value) {
+ field = formatAddress(value)
+ }
+ val iconId: Int get() = Global.getIcon(iconName)
+
+ companion object {
+ fun formatAddress(address: String): String {
+ var url = address
+ if (!(url.startsWith("https://") || url.startsWith("http://"))) {
+ url = "http://$url"
+ }
+ if (!url.endsWith("/")) {
+ url += "/"
+ }
+ return url
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/data/LightStates.kt b/app/src/main/java/io/github/domi04151309/home/data/LightStates.kt
new file mode 100644
index 0000000..fb21bc6
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/data/LightStates.kt
@@ -0,0 +1,92 @@
+package io.github.domi04151309.home.data
+
+import org.json.JSONArray
+import org.json.JSONObject
+
+class LightStates {
+ private val lights: MutableMap = mutableMapOf()
+
+ fun addLight(
+ id: String,
+ state: JSONObject,
+ ) {
+ lights[id] =
+ Light(
+ state.optBoolean("on"),
+ if (state.has("bri")) state.getInt("bri") else -1,
+ if (state.has("xy")) state.getJSONArray("xy") else null,
+ ct = if (state.has("ct")) state.getInt("ct") else -1,
+ )
+ }
+
+ fun setSceneBrightness(bri: Int) {
+ for (i in lights) {
+ i.value.bri = bri
+ }
+ }
+
+ fun setLightBrightness(
+ id: String,
+ bri: Int,
+ ) {
+ lights[id]?.bri = bri
+ }
+
+ fun setLightHue(
+ id: String,
+ hue: Int,
+ ) {
+ lights[id]?.xy = null
+ lights[id]?.hue = hue
+ }
+
+ fun setLightSat(
+ id: String,
+ sat: Int,
+ ) {
+ lights[id]?.xy = null
+ lights[id]?.sat = sat
+ }
+
+ fun setLightCt(
+ id: String,
+ ct: Int,
+ ) {
+ lights[id]?.xy = null
+ lights[id]?.ct = ct
+ }
+
+ fun switchLight(
+ id: String,
+ on: Boolean,
+ ) {
+ lights[id]?.on = on
+ }
+
+ override fun toString(): String {
+ val json = JSONObject()
+ for ((key, value) in lights) {
+ val light = JSONObject()
+ light.put("on", value.on)
+ if (value.bri != -1) light.put("bri", value.bri)
+ if (value.xy != null) light.put("xy", value.xy)
+ if (value.hue != -1 && value.sat != -1) {
+ light.put("hue", value.hue)
+ light.put("sat", value.sat)
+ } else if (value.ct != -1) {
+ light.put("ct", value.ct)
+ }
+ json.put(key, light)
+ }
+ return json.toString()
+ }
+
+ class Light(
+ var on: Boolean = false,
+ var bri: Int = -1,
+ var xy: JSONArray? = null,
+ var hue: Int = -1,
+ var sat: Int = -1,
+ var ct: Int = -1,
+ )
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/data/ListViewItem.kt b/app/src/main/java/io/github/domi04151309/home/data/ListViewItem.kt
new file mode 100644
index 0000000..efe3a11
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/data/ListViewItem.kt
@@ -0,0 +1,19 @@
+package io.github.domi04151309.home.data
+
+class ListViewItem(
+ title: String = "",
+ summary: String = "",
+ hidden: String = "",
+ icon: Int = 0,
+ var state: Boolean? = null,
+ var percentage: Int? = null,
+) : SimpleListItem(title, summary, hidden, icon) {
+ override fun toString(): String =
+ """
+ title: $title,
+ summary: $summary,
+ hidden: $hidden,
+ state: $state,
+ percentage: $percentage
+ """.trimIndent()
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/data/SceneGridItem.kt b/app/src/main/java/io/github/domi04151309/home/data/SceneGridItem.kt
new file mode 100644
index 0000000..8befd68
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/data/SceneGridItem.kt
@@ -0,0 +1,7 @@
+package io.github.domi04151309.home.data
+
+data class SceneGridItem(
+ val name: String,
+ val hidden: String = "",
+ val color: Int? = null,
+)
diff --git a/app/src/main/java/io/github/domi04151309/home/data/SceneListItem.kt b/app/src/main/java/io/github/domi04151309/home/data/SceneListItem.kt
new file mode 100644
index 0000000..a9102e8
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/data/SceneListItem.kt
@@ -0,0 +1,9 @@
+package io.github.domi04151309.home.data
+
+class SceneListItem(
+ val title: String = "",
+ val hidden: String = "",
+ var state: Boolean = false,
+ var brightness: String = "",
+ var color: Int = 0,
+)
diff --git a/app/src/main/java/io/github/domi04151309/home/data/SimpleListItem.kt b/app/src/main/java/io/github/domi04151309/home/data/SimpleListItem.kt
new file mode 100644
index 0000000..8fe890b
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/data/SimpleListItem.kt
@@ -0,0 +1,8 @@
+package io.github.domi04151309.home.data
+
+open class SimpleListItem(
+ var title: String = "",
+ var summary: String = "",
+ var hidden: String = "",
+ var icon: Int = 0,
+)
diff --git a/app/src/main/java/io/github/domi04151309/home/data/UnifiedRequestCallback.kt b/app/src/main/java/io/github/domi04151309/home/data/UnifiedRequestCallback.kt
new file mode 100644
index 0000000..c46c6ca
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/data/UnifiedRequestCallback.kt
@@ -0,0 +1,7 @@
+package io.github.domi04151309.home.data
+
+data class UnifiedRequestCallback(
+ val response: List?,
+ val deviceId: String,
+ val errorMessage: String = "",
+)
diff --git a/app/src/main/java/io/github/domi04151309/home/discovery/NetworkServiceDiscoveryListener.kt b/app/src/main/java/io/github/domi04151309/home/discovery/NetworkServiceDiscoveryListener.kt
new file mode 100644
index 0000000..df69306
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/discovery/NetworkServiceDiscoveryListener.kt
@@ -0,0 +1,57 @@
+package io.github.domi04151309.home.discovery
+
+import android.content.Context
+import android.net.nsd.NsdManager
+import android.net.nsd.NsdServiceInfo
+import androidx.appcompat.app.AppCompatActivity
+
+class NetworkServiceDiscoveryListener(
+ context: Context,
+ private val resolveListener: NetworkServiceResolveListener,
+) : NsdManager.DiscoveryListener {
+ private val nsdManager = context.getSystemService(AppCompatActivity.NSD_SERVICE) as NsdManager
+
+ override fun onStartDiscoveryFailed(
+ p0: String?,
+ p1: Int,
+ ) {
+ nsdManager.stopServiceDiscovery(this)
+ }
+
+ override fun onStopDiscoveryFailed(
+ p0: String?,
+ p1: Int,
+ ) {
+ nsdManager.stopServiceDiscovery(this)
+ }
+
+ override fun onDiscoveryStarted(p0: String?) {
+ // Do nothing.
+ }
+
+ override fun onDiscoveryStopped(p0: String?) {
+ // Do nothing.
+ }
+
+ override fun onServiceFound(service: NsdServiceInfo) {
+ val serviceName = service.serviceName.lowercase()
+ if ((serviceName.startsWith("shelly") && !serviceName.startsWith("shellybutton1")) ||
+ service.serviceType.equals("_simplehome._tcp.")
+ ) {
+ if (resolveListener.isBusy.compareAndSet(false, true)) {
+ nsdManager.resolveService(service, resolveListener)
+ } else {
+ resolveListener.pendingServices.add(service)
+ }
+ }
+ }
+
+ override fun onServiceLost(service: NsdServiceInfo) {
+ val iterator = resolveListener.pendingServices.iterator()
+ while (iterator.hasNext()) {
+ if (iterator.next().serviceName == service.serviceName) {
+ iterator.remove()
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/discovery/NetworkServiceResolveListener.kt b/app/src/main/java/io/github/domi04151309/home/discovery/NetworkServiceResolveListener.kt
new file mode 100644
index 0000000..e989de9
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/discovery/NetworkServiceResolveListener.kt
@@ -0,0 +1,84 @@
+package io.github.domi04151309.home.discovery
+
+import android.app.Activity
+import android.net.nsd.NsdManager
+import android.net.nsd.NsdServiceInfo
+import androidx.appcompat.app.AppCompatActivity
+import com.android.volley.toolbox.Volley
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.DeviceDiscoveryListAdapter
+import io.github.domi04151309.home.api.ShellyAPI
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.helpers.Devices
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicBoolean
+
+class NetworkServiceResolveListener(
+ private val activity: Activity,
+ private val adapter: DeviceDiscoveryListAdapter,
+) : NsdManager.ResolveListener {
+ private val devices = Devices(activity)
+ private val queue = Volley.newRequestQueue(activity)
+ private val nsdManager = activity.getSystemService(AppCompatActivity.NSD_SERVICE) as NsdManager
+
+ var isBusy: AtomicBoolean = AtomicBoolean(false)
+ var pendingServices: ConcurrentLinkedQueue = ConcurrentLinkedQueue()
+
+ override fun onResolveFailed(
+ service: NsdServiceInfo,
+ p1: Int,
+ ) {
+ resolveNextInQueue()
+ }
+
+ override fun onServiceResolved(service: NsdServiceInfo) {
+ activity.runOnUiThread {
+ if (service.serviceType.equals("._simplehome._tcp")) {
+ val url =
+ service.attributes["url"]?.decodeToString()
+ ?: service.host.hostAddress
+ adapter.add(
+ ListViewItem(
+ title = service.serviceName,
+ summary = url,
+ hidden = "SimpleHome API#Raspberry Pi",
+ icon = R.drawable.ic_device_raspberry_pi,
+ state = devices.addressExists(url),
+ ),
+ )
+ } else {
+ val pos =
+ adapter.add(
+ ListViewItem(
+ title = service.serviceName,
+ summary = service.host.hostAddress ?: "",
+ hidden = "Shelly Gen ${
+ service.attributes["gen"]?.decodeToString() ?: "1"
+ }#Lamp",
+ icon = R.drawable.ic_device_lamp,
+ state = devices.addressExists(service.host.hostAddress ?: ""),
+ ),
+ )
+
+ queue.add(
+ ShellyAPI.loadName(
+ "http://" + service.host.hostAddress + "/",
+ service.attributes["gen"]?.decodeToString()?.toInt() ?: 1,
+ ) { name ->
+ if (name.isNotEmpty()) adapter.changeTitle(pos, name)
+ },
+ )
+ }
+ }
+ resolveNextInQueue()
+ }
+
+ private fun resolveNextInQueue() {
+ val nextNsdService = pendingServices.poll()
+ if (nextNsdService != null) {
+ nsdManager.resolveService(nextNsdService, this)
+ } else {
+ isBusy.set(false)
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/discovery/UPnPListener.kt b/app/src/main/java/io/github/domi04151309/home/discovery/UPnPListener.kt
new file mode 100644
index 0000000..c40ba5a
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/discovery/UPnPListener.kt
@@ -0,0 +1,69 @@
+package io.github.domi04151309.home.discovery
+
+import android.content.Context
+import android.util.Log
+import com.rine.upnpdiscovery.UPnPDevice
+import com.rine.upnpdiscovery.UPnPDiscovery
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.DeviceDiscoveryListAdapter
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.helpers.Devices
+
+class UPnPListener(
+ context: Context,
+ private val adapter: DeviceDiscoveryListAdapter,
+) : UPnPDiscovery.OnDiscoveryListener {
+ private val devices = Devices(context)
+ private val addresses = mutableListOf()
+
+ override fun onStart() {
+ // Do nothing.
+ }
+
+ override fun onFoundNewDevice(device: UPnPDevice) {
+ if (device.server.contains("IpBridge") && !addresses.contains(device.hostAddress)) {
+ adapter.add(
+ ListViewItem(
+ title = device.friendlyName,
+ summary = device.hostAddress,
+ hidden = "Hue API#Lamp",
+ icon = R.drawable.ic_device_lamp,
+ state = devices.addressExists(device.hostAddress),
+ ),
+ )
+ addresses += device.hostAddress
+ }
+ if (device.friendlyName.startsWith("FRITZ!") && !addresses.contains(device.hostAddress)) {
+ adapter.add(
+ ListViewItem(
+ title = device.friendlyName,
+ summary = device.hostAddress,
+ hidden = "Website#Router",
+ icon = R.drawable.ic_device_router,
+ state = devices.addressExists(device.hostAddress),
+ ),
+ )
+ addresses += device.hostAddress
+ }
+ if (device.server.contains("SimpleHome") && !addresses.contains(device.hostAddress)) {
+ adapter.add(
+ ListViewItem(
+ title = device.friendlyName,
+ summary = device.hostAddress,
+ hidden = "SimpleHome API#Raspberry Pi",
+ icon = R.drawable.ic_device_raspberry_pi,
+ state = devices.addressExists(device.hostAddress),
+ ),
+ )
+ addresses += device.hostAddress
+ }
+ }
+
+ override fun onFinish(devices: HashSet) {
+ // Do nothing.
+ }
+
+ override fun onError(e: Exception) {
+ Log.e(this::class.simpleName, e.toString())
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/fragments/ControlInfoFragment.kt b/app/src/main/java/io/github/domi04151309/home/fragments/ControlInfoFragment.kt
new file mode 100644
index 0000000..d6deb28
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/fragments/ControlInfoFragment.kt
@@ -0,0 +1,33 @@
+package io.github.domi04151309.home.fragments
+
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.fragment.app.Fragment
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.helpers.Global
+
+class ControlInfoFragment(
+ private val device: DeviceItem,
+ private val title: String,
+) : Fragment(R.layout.fragment_control_info) {
+ override fun onCreateView(
+ inflater: LayoutInflater,
+ container: ViewGroup?,
+ savedInstanceState: Bundle?,
+ ): View? {
+ val view =
+ super.onCreateView(inflater, container, savedInstanceState)
+ ?: error("View does not exist yet.")
+
+ view.findViewById(R.id.deviceIcon).setImageResource(Global.getIcon(device.iconName))
+ view.findViewById(R.id.titleText).text = title
+ view.findViewById(R.id.subTitleText).text = device.name
+
+ return view
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/fragments/HueColorFragment.kt b/app/src/main/java/io/github/domi04151309/home/fragments/HueColorFragment.kt
new file mode 100644
index 0000000..4c6b626
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/fragments/HueColorFragment.kt
@@ -0,0 +1,238 @@
+package io.github.domi04151309.home.fragments
+
+import android.annotation.SuppressLint
+import android.graphics.Color
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.view.LayoutInflater
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import androidx.core.graphics.toColorInt
+import androidx.fragment.app.Fragment
+import com.google.android.material.slider.Slider
+import com.skydoves.colorpickerview.ColorPickerView
+import com.skydoves.colorpickerview.listeners.ColorListener
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.data.LightStates
+import io.github.domi04151309.home.helpers.HueUtils
+import io.github.domi04151309.home.helpers.HueUtils.MIN_COLOR_TEMPERATURE
+import io.github.domi04151309.home.helpers.SliderUtils
+import io.github.domi04151309.home.interfaces.HueRoomInterface
+
+class HueColorFragment(private var lampInterface: HueRoomInterface) : Fragment(R.layout.fragment_hue_color) {
+ private lateinit var hueAPI: HueAPI
+ private lateinit var colorPickerView: ColorPickerView
+ private lateinit var ctText: TextView
+ private lateinit var ctBar: Slider
+ private lateinit var hueSatText: TextView
+ private lateinit var hueBar: Slider
+ private lateinit var satBar: Slider
+
+ private class OnSliderTouchListener(
+ private val fragment: HueColorFragment,
+ private val action: (slider: Slider) -> Unit,
+ ) : Slider.OnSliderTouchListener {
+ override fun onStartTrackingTouch(slider: Slider) {
+ fragment.pauseUpdates()
+ }
+
+ override fun onStopTrackingTouch(slider: Slider) {
+ action(slider)
+ fragment.resumeUpdates()
+ }
+ }
+
+ override fun onCreateView(
+ inflater: LayoutInflater,
+ container: ViewGroup?,
+ savedInstanceState: Bundle?,
+ ): View {
+ hueAPI = HueAPI(requireContext(), lampInterface.device.id)
+
+ val view =
+ super.onCreateView(inflater, container, savedInstanceState)
+ ?: error("View does not exist yet.")
+ colorPickerView = view.findViewById(R.id.colorPickerView)
+ ctText = view.findViewById(R.id.ctTxt)
+ ctBar = view.findViewById(R.id.ctBar)
+ hueSatText = view.findViewById(R.id.hueSatTxt)
+ hueBar = view.findViewById(R.id.hueBar)
+ satBar = view.findViewById(R.id.satBar)
+
+ val availableInputs = arrayOf(colorPickerView, ctBar, hueBar, satBar)
+ val ctViews = arrayOf(ctText, ctBar)
+ val hueSatViews = arrayOf(colorPickerView, hueSatText, hueBar, satBar)
+
+ setupColorControls(hueAPI)
+ setupTemperatureControls(hueAPI)
+
+ fun updateFunction(data: LightStates.Light) {
+ if (lampInterface.canReceiveRequest) {
+ if (data.ct == -1) {
+ ctViews.forEach {
+ it.visibility = View.GONE
+ }
+ } else {
+ ctViews.forEach {
+ it.visibility = View.VISIBLE
+ }
+ SliderUtils.setProgress(ctBar, data.ct)
+ }
+ if (data.hue == -1 || data.sat == -1) {
+ hueSatViews.forEach {
+ it.visibility = View.GONE
+ }
+ } else {
+ hueSatViews.forEach {
+ it.visibility = View.VISIBLE
+ }
+ colorPickerView.selectByHsvColor(HueUtils.hueSatToRGB(data.hue, data.sat))
+ SliderUtils.setProgress(hueBar, data.hue)
+ SliderUtils.setProgress(satBar, data.sat)
+ }
+ availableInputs.forEach {
+ it.isEnabled = data.on
+ }
+ }
+ }
+
+ view.post {
+ view.postDelayed({
+ colorPickerView.selectByHsvColor(
+ HueUtils.hueSatToRGB(
+ lampInterface.lampData.state.hue,
+ lampInterface.lampData.state.sat,
+ ),
+ )
+ }, LOADING_DELAY)
+ updateFunction(lampInterface.lampData.state)
+ lampInterface.lampData.addOnDataChangedListener(::updateFunction)
+ }
+
+ return view
+ }
+
+ internal fun pauseUpdates() {
+ lampInterface.canReceiveRequest = false
+ }
+
+ internal fun resumeUpdates() {
+ Handler(Looper.getMainLooper()).postDelayed({
+ lampInterface.canReceiveRequest = true
+ }, UPDATE_DELAY)
+ }
+
+ @SuppressLint("ClickableViewAccessibility")
+ private fun setupColorPicker(hueAPI: HueAPI) {
+ colorPickerView.setColorListener(
+ ColorListener { color, fromUser ->
+ if (fromUser) {
+ val hueSat = HueUtils.rgbToHueSat(color)
+ hueBar.value = hueSat[0].toFloat()
+ satBar.value = hueSat[1].toFloat()
+ lampInterface.onColorChanged(color)
+ }
+ },
+ )
+ colorPickerView.setOnTouchListener { innerView, event ->
+ if (event.action == MotionEvent.ACTION_DOWN) {
+ pauseUpdates()
+ } else if (event.action == MotionEvent.ACTION_UP) {
+ val hueSat = HueUtils.rgbToHueSat(colorPickerView.color)
+ hueAPI.changeHueSatOfGroup(lampInterface.id, hueSat[0], hueSat[1])
+ resumeUpdates()
+ }
+ innerView.performClick()
+ }
+ }
+
+ private fun setupColorControls(hueAPI: HueAPI) {
+ hueBar.setLabelFormatter { value: Float ->
+ HueUtils.hueToDegree(value.toInt())
+ }
+ satBar.setLabelFormatter { value: Float ->
+ HueUtils.satToPercent(value.toInt())
+ }
+
+ SliderUtils.setSliderGradient(
+ hueBar,
+ HueUtils.defaultColors(),
+ )
+ SliderUtils.setSliderGradient(
+ satBar,
+ intArrayOf(
+ Color.WHITE,
+ Color.RED,
+ ),
+ )
+
+ hueBar.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ val color = HueUtils.hueSatToRGB(value.toInt(), satBar.value.toInt())
+ colorPickerView.selectByHsvColor(color)
+ lampInterface.onColorChanged(color)
+ }
+ SliderUtils.setSliderGradientNow(
+ satBar,
+ intArrayOf(
+ Color.WHITE,
+ HueUtils.hueToRGB(value.toInt()),
+ ),
+ )
+ }
+ hueBar.addOnSliderTouchListener(
+ OnSliderTouchListener(this) { slider ->
+ hueAPI.changeHueOfGroup(lampInterface.id, slider.value.toInt())
+ },
+ )
+
+ satBar.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ val color = HueUtils.hueSatToRGB(hueBar.value.toInt(), value.toInt())
+ colorPickerView.selectByHsvColor(color)
+ lampInterface.onColorChanged(color)
+ }
+ }
+ satBar.addOnSliderTouchListener(
+ OnSliderTouchListener(this) { slider ->
+ hueAPI.changeSaturationOfGroup(lampInterface.id, slider.value.toInt())
+ },
+ )
+
+ setupColorPicker(hueAPI)
+ }
+
+ private fun setupTemperatureControls(hueAPI: HueAPI) {
+ ctBar.setLabelFormatter { value: Float ->
+ HueUtils.ctToKelvin(value.toInt() + MIN_COLOR_TEMPERATURE)
+ }
+
+ SliderUtils.setSliderGradient(
+ ctBar,
+ intArrayOf(
+ Color.WHITE,
+ "#FF8B16".toColorInt(),
+ ),
+ )
+
+ ctBar.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ lampInterface.onColorChanged(HueUtils.ctToRGB(value.toInt() + MIN_COLOR_TEMPERATURE))
+ }
+ }
+ ctBar.addOnSliderTouchListener(
+ OnSliderTouchListener(this) { slider ->
+ hueAPI.changeColorTemperatureOfGroup(lampInterface.id, slider.value.toInt() + MIN_COLOR_TEMPERATURE)
+ },
+ )
+ }
+
+ companion object {
+ private const val LOADING_DELAY = 200L
+ private const val UPDATE_DELAY = 5000L
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/fragments/HueColorSheet.kt b/app/src/main/java/io/github/domi04151309/home/fragments/HueColorSheet.kt
new file mode 100644
index 0000000..9202dfd
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/fragments/HueColorSheet.kt
@@ -0,0 +1,225 @@
+package io.github.domi04151309.home.fragments
+
+import android.graphics.Color
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import android.widget.Toast
+import androidx.core.graphics.toColorInt
+import com.android.volley.Request
+import com.android.volley.Response
+import com.android.volley.toolbox.JsonObjectRequest
+import com.android.volley.toolbox.Volley
+import com.google.android.material.bottomsheet.BottomSheetDialogFragment
+import com.google.android.material.slider.Slider
+import com.skydoves.colorpickerview.ColorPickerView
+import com.skydoves.colorpickerview.listeners.ColorListener
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.HueUtils
+import io.github.domi04151309.home.helpers.HueUtils.MIN_COLOR_TEMPERATURE
+import io.github.domi04151309.home.helpers.SliderUtils
+import io.github.domi04151309.home.interfaces.HueAdvancedLampInterface
+import org.json.JSONObject
+
+class HueColorSheet(private val lampInterface: HueAdvancedLampInterface) :
+ BottomSheetDialogFragment(),
+ Response.Listener {
+ private lateinit var colorPickerView: ColorPickerView
+ private lateinit var ctText: TextView
+ private lateinit var ctBar: Slider
+ private lateinit var hueSatText: TextView
+ private lateinit var hueBar: Slider
+ private lateinit var satBar: Slider
+ private lateinit var briText: TextView
+ private lateinit var briBar: Slider
+
+ override fun onCreateView(
+ inflater: LayoutInflater,
+ container: ViewGroup?,
+ savedInstanceState: Bundle?,
+ ): View? {
+ val hueAPI = HueAPI(requireContext(), lampInterface.device.id)
+
+ val view = inflater.inflate(R.layout.fragment_hue_bri_color, container, false)
+ colorPickerView = view.findViewById(R.id.colorPickerView)
+ ctText = view.findViewById(R.id.ctTxt)
+ ctBar = view.findViewById(R.id.ctBar)
+ hueSatText = view.findViewById(R.id.hueSatTxt)
+ hueBar = view.findViewById(R.id.hueBar)
+ satBar = view.findViewById(R.id.satBar)
+ briText = view.findViewById(R.id.briTxt)
+ briBar = view.findViewById(R.id.briBar)
+
+ Volley.newRequestQueue(requireContext())
+ .add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ "${lampInterface.addressPrefix}/lights/${lampInterface.id}",
+ null,
+ this,
+ ) { error ->
+ Toast.makeText(
+ requireContext(),
+ Global.volleyError(requireContext(), error),
+ Toast.LENGTH_LONG,
+ ).show()
+ },
+ )
+
+ setupColorControls(hueAPI)
+ setupTemperatureControls(hueAPI)
+ setupBrightnessControls(hueAPI)
+
+ return view
+ }
+
+ override fun onResponse(response: JSONObject) {
+ val availableInputs = arrayOf(colorPickerView, hueBar, satBar, ctBar, briBar)
+ val ctViews = arrayOf(ctText, ctBar)
+ val hueSatViews = arrayOf(colorPickerView, hueSatText, hueBar, satBar)
+ val briViews = arrayOf(briText, briBar)
+ val state = response.getJSONObject("state")
+
+ if (!state.has("ct")) {
+ ctViews.forEach {
+ it.visibility = View.GONE
+ }
+ } else {
+ ctViews.forEach {
+ it.visibility = View.VISIBLE
+ }
+ SliderUtils.setProgress(ctBar, state.getInt("ct") - MIN_COLOR_TEMPERATURE)
+ }
+ if (!state.has("hue") && !state.has("sat")) {
+ hueSatViews.forEach {
+ it.visibility = View.GONE
+ }
+ } else {
+ hueSatViews.forEach {
+ it.visibility = View.VISIBLE
+ }
+ colorPickerView.selectByHsvColor(
+ HueUtils.hueSatToRGB(
+ state.getInt("hue"),
+ state.getInt("sat"),
+ ),
+ )
+ SliderUtils.setProgress(hueBar, state.getInt("hue"))
+ SliderUtils.setProgress(satBar, state.getInt("sat"))
+ }
+ if (!state.has("bri")) {
+ briViews.forEach {
+ it.visibility = View.GONE
+ }
+ } else {
+ briViews.forEach {
+ it.visibility = View.VISIBLE
+ }
+ SliderUtils.setProgress(briBar, state.getInt("bri"))
+ }
+ availableInputs.forEach {
+ it.isEnabled = state.optBoolean("on")
+ }
+ }
+
+ private fun setupColorControls(hueAPI: HueAPI) {
+ hueBar.setLabelFormatter { value: Float ->
+ HueUtils.hueToDegree(value.toInt())
+ }
+ satBar.setLabelFormatter { value: Float ->
+ HueUtils.satToPercent(value.toInt())
+ }
+
+ SliderUtils.setSliderGradient(
+ hueBar,
+ HueUtils.defaultColors(),
+ )
+ SliderUtils.setSliderGradient(
+ satBar,
+ intArrayOf(
+ Color.WHITE,
+ Color.RED,
+ ),
+ )
+
+ hueBar.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ val color = HueUtils.hueSatToRGB(value.toInt(), satBar.value.toInt())
+ hueAPI.changeHue(lampInterface.id, value.toInt())
+ colorPickerView.selectByHsvColor(color)
+ lampInterface.onColorChanged(color)
+ lampInterface.onHueSatChanged(value.toInt(), satBar.value.toInt())
+ }
+ SliderUtils.setSliderGradientNow(
+ satBar,
+ intArrayOf(
+ Color.WHITE,
+ HueUtils.hueToRGB(
+ value.toInt(),
+ ),
+ ),
+ )
+ }
+
+ satBar.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ val color = HueUtils.hueSatToRGB(hueBar.value.toInt(), value.toInt())
+ hueAPI.changeSaturation(lampInterface.id, value.toInt())
+ colorPickerView.selectByHsvColor(color)
+ lampInterface.onColorChanged(color)
+ lampInterface.onHueSatChanged(hueBar.value.toInt(), value.toInt())
+ }
+ }
+
+ colorPickerView.setColorListener(
+ ColorListener { color, fromUser ->
+ if (fromUser) {
+ val hueSat = HueUtils.rgbToHueSat(color)
+ hueAPI.changeHueSat(lampInterface.id, hueSat[0], hueSat[1])
+ hueBar.value = hueSat[0].toFloat()
+ satBar.value = hueSat[1].toFloat()
+ lampInterface.onColorChanged(color)
+ lampInterface.onColorChanged(color)
+ lampInterface.onHueSatChanged(hueSat[0], hueSat[1])
+ }
+ },
+ )
+ }
+
+ private fun setupTemperatureControls(hueAPI: HueAPI) {
+ ctBar.setLabelFormatter { value: Float ->
+ HueUtils.ctToKelvin(value.toInt() + MIN_COLOR_TEMPERATURE)
+ }
+
+ SliderUtils.setSliderGradient(
+ ctBar,
+ intArrayOf(
+ Color.WHITE,
+ "#FF8B16".toColorInt(),
+ ),
+ )
+
+ ctBar.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) {
+ hueAPI.changeColorTemperature(lampInterface.id, value.toInt() + MIN_COLOR_TEMPERATURE)
+ lampInterface.onColorChanged(HueUtils.ctToRGB(value.toInt() + MIN_COLOR_TEMPERATURE))
+ lampInterface.onCtChanged(value.toInt() + MIN_COLOR_TEMPERATURE)
+ }
+ }
+ }
+
+ private fun setupBrightnessControls(hueAPI: HueAPI) {
+ briBar.setLabelFormatter { value: Float ->
+ HueUtils.briToPercent(value.toInt())
+ }
+
+ briBar.addOnChangeListener { _, value, fromUser ->
+ if (fromUser) hueAPI.changeBrightness(lampInterface.id, value.toInt())
+ lampInterface.onBrightnessChanged(value.toInt())
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/fragments/HueLampsFragment.kt b/app/src/main/java/io/github/domi04151309/home/fragments/HueLampsFragment.kt
new file mode 100644
index 0000000..be4b82d
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/fragments/HueLampsFragment.kt
@@ -0,0 +1,171 @@
+package io.github.domi04151309.home.fragments
+
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.CompoundButton
+import android.widget.TextView
+import androidx.core.graphics.toColorInt
+import androidx.fragment.app.Fragment
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.android.volley.RequestQueue
+import com.android.volley.toolbox.Volley
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.adapters.HueLampListAdapter
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.helpers.HueUtils
+import io.github.domi04151309.home.helpers.UpdateHandler
+import io.github.domi04151309.home.interfaces.HueAdvancedLampInterface
+import io.github.domi04151309.home.interfaces.HueRoomInterface
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+import org.json.JSONArray
+import org.json.JSONObject
+
+class HueLampsFragment(private var lampInterface: HueRoomInterface) :
+ Fragment(R.layout.fragment_hue_lamps),
+ RecyclerViewHelperInterface,
+ HueAdvancedLampInterface,
+ HueAPI.RequestCallback,
+ CompoundButton.OnCheckedChangeListener {
+ private lateinit var hueAPI: HueAPI
+ private lateinit var queue: RequestQueue
+ private lateinit var recyclerView: RecyclerView
+ private lateinit var adapter: HueLampListAdapter
+ private val updateHandler: UpdateHandler = UpdateHandler()
+
+ override var id: String = ""
+ override var canReceiveRequest: Boolean = true
+ override lateinit var device: DeviceItem
+ override lateinit var addressPrefix: String
+
+ override fun onCreateView(
+ inflater: LayoutInflater,
+ container: ViewGroup?,
+ savedInstanceState: Bundle?,
+ ): View {
+ hueAPI = HueAPI(requireContext(), lampInterface.device.id)
+ queue = Volley.newRequestQueue(context)
+
+ device = lampInterface.device
+ addressPrefix = lampInterface.addressPrefix
+
+ recyclerView = super.onCreateView(inflater, container, savedInstanceState) as RecyclerView
+
+ adapter = HueLampListAdapter(this, this)
+ recyclerView.layoutManager = LinearLayoutManager(requireContext())
+ recyclerView.adapter = adapter
+
+ return recyclerView
+ }
+
+ override fun onStart() {
+ super.onStart()
+ updateHandler.setUpdateFunction {
+ if (lampInterface.canReceiveRequest && hueAPI.readyForRequest) {
+ hueAPI.loadLightsByIds(lampInterface.lights ?: JSONArray(), this)
+ }
+ }
+ }
+
+ override fun onStop() {
+ super.onStop()
+ updateHandler.stop()
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ id = view.findViewById(R.id.hidden).text.toString()
+ HueColorSheet(this).show(
+ requireActivity().supportFragmentManager,
+ HueColorSheet::class.simpleName,
+ )
+ }
+
+ @Suppress("CognitiveComplexMethod")
+ override fun onLightsLoaded(response: JSONObject?) {
+ if (response != null) {
+ var currentObject: JSONObject
+ var currentState: JSONObject
+ var state: Boolean?
+ val listItems: MutableList = mutableListOf()
+ val colorArray: MutableList = mutableListOf()
+ for (i in response.keys()) {
+ currentObject = response.optJSONObject(i) ?: JSONObject()
+ currentState = currentObject.optJSONObject("state") ?: JSONObject()
+ state = currentState.optBoolean("on")
+ colorArray +=
+ if (currentState.has("hue") && currentState.has("sat")) {
+ HueUtils.hueSatToRGB(
+ currentState.getInt("hue"),
+ currentState.getInt("sat"),
+ )
+ } else if (currentState.has("ct")) {
+ HueUtils.ctToRGB(currentState.getInt("ct"))
+ } else {
+ "#FFFFFF".toColorInt()
+ }
+ listItems +=
+ ListViewItem(
+ title = currentObject.optString("name"),
+ summary =
+ if (currentState.optBoolean("reachable")) {
+ resources.getString(R.string.hue_brightness) +
+ ": " +
+ if (state) {
+ HueUtils.briToPercent(
+ currentState.optInt(
+ "bri",
+ HueUtils.MAX_BRIGHTNESS,
+ ),
+ )
+ } else {
+ "0 %"
+ }
+ } else {
+ resources.getString(R.string.str_unreachable)
+ },
+ hidden = i,
+ state = state,
+ )
+ }
+ adapter.updateData(recyclerView, listItems, colorArray)
+ }
+ }
+
+ override fun onColorChanged(color: Int) {
+ // Do nothing.
+ }
+
+ override fun onBrightnessChanged(brightness: Int) {
+ // Do nothing.
+ }
+
+ override fun onHueSatChanged(
+ hue: Int,
+ sat: Int,
+ ) {
+ // Do nothing.
+ }
+
+ override fun onCtChanged(ct: Int) {
+ // Do nothing.
+ }
+
+ override fun onCheckedChanged(
+ compoundButton: CompoundButton,
+ state: Boolean,
+ ) {
+ if (compoundButton.isPressed) {
+ hueAPI.switchLightById(
+ (compoundButton.parent as ViewGroup).findViewById(R.id.hidden).text.toString(),
+ state,
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/fragments/HueScenesFragment.kt b/app/src/main/java/io/github/domi04151309/home/fragments/HueScenesFragment.kt
new file mode 100644
index 0000000..7ce1d39
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/fragments/HueScenesFragment.kt
@@ -0,0 +1,261 @@
+package io.github.domi04151309.home.fragments
+
+import android.content.Intent
+import android.graphics.Color
+import android.os.Bundle
+import android.util.Log
+import android.view.ContextMenu
+import android.view.LayoutInflater
+import android.view.MenuInflater
+import android.view.MenuItem
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import android.widget.Toast
+import androidx.fragment.app.Fragment
+import androidx.recyclerview.widget.GridLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.android.volley.Request
+import com.android.volley.RequestQueue
+import com.android.volley.Response
+import com.android.volley.toolbox.JsonObjectRequest
+import com.android.volley.toolbox.Volley
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.activities.HueSceneActivity
+import io.github.domi04151309.home.adapters.HueSceneGridAdapter
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.custom.CustomJsonArrayRequest
+import io.github.domi04151309.home.data.SceneGridItem
+import io.github.domi04151309.home.helpers.ColorUtils
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.HueUtils
+import io.github.domi04151309.home.interfaces.HueLampInterface
+import io.github.domi04151309.home.interfaces.RecyclerViewHelperInterface
+import org.json.JSONException
+import org.json.JSONObject
+
+class HueScenesFragment(private var lampInterface: HueLampInterface) :
+ Fragment(R.layout.fragment_hue_scenes),
+ RecyclerViewHelperInterface,
+ Response.Listener {
+ private var scenesRequest: JsonObjectRequest? = null
+ private var selectedScene: CharSequence = ""
+ private var selectedSceneName: CharSequence = ""
+ private lateinit var hueAPI: HueAPI
+ private lateinit var queue: RequestQueue
+ private lateinit var adapter: HueSceneGridAdapter
+
+ override fun onCreateView(
+ inflater: LayoutInflater,
+ container: ViewGroup?,
+ savedInstanceState: Bundle?,
+ ): View {
+ hueAPI = HueAPI(requireContext(), lampInterface.device.id)
+ queue = Volley.newRequestQueue(context)
+
+ val recyclerView = super.onCreateView(inflater, container, savedInstanceState) as RecyclerView
+ adapter = HueSceneGridAdapter(this, this)
+ recyclerView.layoutManager = GridLayoutManager(requireContext(), COLUMNS)
+ recyclerView.adapter = adapter
+
+ scenesRequest =
+ JsonObjectRequest(
+ Request.Method.GET, lampInterface.addressPrefix + SCENES_PATH, null,
+ this,
+ ) { error ->
+ Toast.makeText(
+ requireContext(),
+ Global.volleyError(requireContext(), error),
+ Toast.LENGTH_LONG,
+ ).show()
+ }
+ queue.add(scenesRequest)
+ return recyclerView
+ }
+
+ override fun onResponse(response: JSONObject) {
+ try {
+ val gridItems: ArrayList = ArrayList(response.length())
+ val scenes: List> = getScenes(response)
+ if (scenes.isNotEmpty()) {
+ var completedRequests = 0
+ for (i in scenes.indices) {
+ queue.add(
+ JsonObjectRequest(
+ Request.Method.GET,
+ lampInterface.addressPrefix + SCENES_PATH + scenes[i].first,
+ null,
+ { sceneResponse ->
+ gridItems +=
+ SceneGridItem(
+ name = scenes[i].second,
+ hidden = scenes[i].first,
+ color = getSceneColor(sceneResponse),
+ )
+ completedRequests++
+ if (completedRequests == scenes.size) {
+ val sortedItems =
+ gridItems.sortedWith(compareBy { it.color })
+ .toMutableList()
+ sortedItems +=
+ SceneGridItem(
+ name = resources.getString(R.string.hue_add_scene),
+ hidden = "add",
+ )
+ adapter.updateData(sortedItems)
+ }
+ },
+ { error ->
+ Log.e(Global.LOG_TAG, error.toString())
+ },
+ ),
+ )
+ }
+ } else {
+ adapter.updateData(
+ mutableListOf(
+ SceneGridItem(
+ name = resources.getString(R.string.hue_add_scene),
+ hidden = "add",
+ ),
+ ),
+ )
+ }
+ } catch (e: JSONException) {
+ Log.e(Global.LOG_TAG, e.toString())
+ }
+ }
+
+ private fun getScenes(response: JSONObject): List> {
+ val scenes: ArrayList> =
+ ArrayList(
+ response.length() / SCENE_FRACTION_ESTIMATE,
+ )
+ var currentObject: JSONObject
+ for (i in response.keys()) {
+ currentObject = response.getJSONObject(i)
+ if (currentObject.optString("group") == lampInterface.id) {
+ scenes.add(Pair(i, currentObject.getString("name")))
+ }
+ }
+ return scenes
+ }
+
+ private fun getSceneColor(response: JSONObject): Int {
+ val states = response.getJSONObject("lightstates")
+ val currentSceneValues = ArrayList(states.length())
+ var lampObject: JSONObject
+ for (j in states.keys()) {
+ lampObject = states.getJSONObject(j)
+ if (lampObject.getBoolean("on")) {
+ if (lampObject.has("hue") && lampObject.has("sat")) {
+ currentSceneValues.clear()
+ currentSceneValues.add(
+ HueUtils.hueSatToRGB(
+ lampObject.getInt("hue"),
+ lampObject.getInt("sat"),
+ ),
+ )
+ } else if (lampObject.has("xy")) {
+ val xyArray = lampObject.getJSONArray("xy")
+ currentSceneValues.clear()
+ currentSceneValues.add(
+ ColorUtils.xyToRGB(
+ xyArray.getDouble(0),
+ xyArray.getDouble(1),
+ ),
+ )
+ } else if (lampObject.has("ct")) {
+ currentSceneValues.add(
+ HueUtils.ctToRGB(lampObject.getInt("ct")),
+ )
+ }
+ }
+ }
+ return if (currentSceneValues.isNotEmpty()) {
+ currentSceneValues[0]
+ } else {
+ Color.WHITE
+ }
+ }
+
+ override fun onItemClicked(
+ view: View,
+ position: Int,
+ ) {
+ val hiddenText = view.findViewById(R.id.hidden).text.toString()
+ if (hiddenText == "add") {
+ startActivity(
+ Intent(requireContext(), HueSceneActivity::class.java).putExtra(
+ "deviceId",
+ lampInterface.device.id,
+ ).putExtra("room", lampInterface.id),
+ )
+ } else {
+ hueAPI.activateSceneOfGroup(lampInterface.id, hiddenText)
+ }
+ }
+
+ override fun onCreateContextMenu(
+ menu: ContextMenu,
+ v: View,
+ menuInfo: ContextMenu.ContextMenuInfo?,
+ ) {
+ super.onCreateContextMenu(menu, v, menuInfo)
+ selectedScene = v.findViewById(R.id.hidden).text
+ selectedSceneName = v.findViewById(R.id.title).text
+ if (selectedScene != "add") MenuInflater(requireContext()).inflate(R.menu.activity_hue_lamp_context, menu)
+ }
+
+ override fun onContextItemSelected(item: MenuItem): Boolean =
+ when (item.title) {
+ resources.getString(R.string.str_edit) -> {
+ startActivity(
+ Intent(requireContext(), HueSceneActivity::class.java)
+ .putExtra("deviceId", lampInterface.device.id)
+ .putExtra("room", lampInterface.id)
+ .putExtra("scene", selectedScene),
+ )
+ true
+ }
+ resources.getString(R.string.str_delete) -> {
+ MaterialAlertDialogBuilder(requireContext())
+ .setTitle(R.string.str_delete)
+ .setMessage(R.string.hue_delete_scene)
+ .setPositiveButton(R.string.str_delete) { _, _ ->
+ val deleteSceneRequest =
+ CustomJsonArrayRequest(
+ Request.Method.DELETE,
+ lampInterface.addressPrefix + SCENES_PATH + selectedScene,
+ null,
+ { queue.add(scenesRequest) },
+ { e -> Log.e(Global.LOG_TAG, e.toString()) },
+ )
+ queue.add(deleteSceneRequest)
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ true
+ }
+ else -> {
+ super.onContextItemSelected(item)
+ }
+ }
+
+ override fun onStart() {
+ super.onStart()
+ if (scenesChanged) {
+ scenesChanged = false
+ queue.add(scenesRequest)
+ }
+ }
+
+ companion object {
+ private const val SCENE_FRACTION_ESTIMATE = 4
+ private const val COLUMNS = 3
+ private const val SCENES_PATH = "/scenes/"
+
+ var scenesChanged: Boolean = false
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/ColorUtils.kt b/app/src/main/java/io/github/domi04151309/home/helpers/ColorUtils.kt
new file mode 100644
index 0000000..f0e5949
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/ColorUtils.kt
@@ -0,0 +1,62 @@
+package io.github.domi04151309.home.helpers
+
+import android.graphics.Color
+import kotlin.math.ln
+import kotlin.math.pow
+
+@Suppress("MagicNumber")
+object ColorUtils {
+ private const val MAX: Double = 255.0
+ private const val MIN: Double = 0.0
+
+ fun temperatureToRGB(kelvin: Int): Int {
+ val temp = kelvin / 100.0
+ val red: Double
+ val green: Double
+ val blue: Double
+
+ if (temp <= 66) {
+ red = MAX
+ green = 99.4708025861 * ln(temp) - 161.1195681661
+ blue =
+ if (temp <= 19) {
+ MIN
+ } else {
+ 138.5177312231 * ln(temp - 10) - 305.0447927307
+ }
+ } else {
+ red = 329.698727446 * (temp - 60).pow(-0.1332047592)
+ green = 288.1221695283 * (temp - 60).pow(-0.0755148492)
+ blue = MAX
+ }
+
+ return Color.rgb(clamp(red), clamp(green), clamp(blue))
+ }
+
+ fun xyToRGB(
+ x: Double,
+ y: Double,
+ ): Int {
+ val cieY = 1.0
+ val cieX = cieY * x / y
+ val cieZ = (1 - x - y) * cieY / y
+
+ val r = +3.2404542 * cieX - 1.5371385 * cieY - 0.4985314 * cieZ
+ val g = -0.9692660 * cieX + 1.8760108 * cieY + 0.0415560 * cieZ
+ val b = +0.0556434 * cieX - 0.2040259 * cieY + 1.0572252 * cieZ
+
+ return Color.rgb(formatXyzValue(r), formatXyzValue(g), formatXyzValue(b))
+ }
+
+ private fun formatXyzValue(v: Double): Int =
+ clamp(
+ (if (v <= 0.0031308) 12.92 * v else 1.055 * v.pow(1.0 / 2.4) - 0.055) * MAX,
+ )
+
+ private fun clamp(value: Double): Int =
+ when {
+ value < MIN -> MIN.toInt()
+ value > MAX -> MAX.toInt()
+ else -> value.toInt()
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/DeviceSecrets.kt b/app/src/main/java/io/github/domi04151309/home/helpers/DeviceSecrets.kt
new file mode 100644
index 0000000..841b3b4
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/DeviceSecrets.kt
@@ -0,0 +1,54 @@
+package io.github.domi04151309.home.helpers
+
+import android.content.Context
+import android.content.SharedPreferences
+import androidx.core.content.edit
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+import org.json.JSONObject
+
+class DeviceSecrets(context: Context, private val id: String) {
+ private val masterKeyAlias =
+ MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+
+ private val preferences: SharedPreferences =
+ EncryptedSharedPreferences.create(
+ context,
+ "device_secrets",
+ masterKeyAlias,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
+ )
+
+ private val secrets =
+ JSONObject(
+ preferences.getString(id, DEFAULT_JSON)
+ ?: DEFAULT_JSON,
+ )
+
+ var username: String
+ get() = secrets.optString("username")
+ set(value) {
+ secrets.put("username", value)
+ }
+
+ var password: String
+ get() = secrets.optString("password")
+ set(value) {
+ secrets.put("password", value)
+ }
+
+ fun updateDeviceSecrets() {
+ preferences.edit { putString(id, secrets.toString()) }
+ }
+
+ fun deleteDeviceSecrets() {
+ preferences.edit { remove(id) }
+ }
+
+ companion object {
+ private const val DEFAULT_JSON = """{ "username": "", "password": "" }"""
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/Devices.kt b/app/src/main/java/io/github/domi04151309/home/helpers/Devices.kt
new file mode 100644
index 0000000..f7794f6
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/Devices.kt
@@ -0,0 +1,146 @@
+package io.github.domi04151309.home.helpers
+
+import android.content.Context
+import android.content.SharedPreferences
+import android.util.Log
+import androidx.core.content.edit
+import androidx.preference.PreferenceManager
+import io.github.domi04151309.home.data.DeviceItem
+import org.json.JSONArray
+import org.json.JSONException
+import org.json.JSONObject
+import java.util.Random
+
+@Suppress("TooManyFunctions")
+class Devices(private val context: Context) {
+ private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
+
+ val length: Int get() = deviceOrder.length()
+
+ private val data: JSONObject get() {
+ if (storedData == null) {
+ storedData =
+ try {
+ JSONObject(
+ preferences.getString("devices_json", Global.DEFAULT_JSON)
+ ?: Global.DEFAULT_JSON,
+ )
+ } catch (e: JSONException) {
+ Log.w(Devices::class.simpleName, e)
+ JSONObject(Global.DEFAULT_JSON)
+ }
+ }
+ return storedData!!
+ }
+
+ private val devicesObject: JSONObject get() = data.optJSONObject("devices") ?: JSONObject()
+
+ private val deviceOrder: JSONArray get() {
+ if (!data.has(ORDER)) {
+ data.put(ORDER, devicesObject.names() ?: JSONArray())
+ }
+ return data.getJSONArray(ORDER)
+ }
+
+ private fun generateRandomId(): String {
+ val random = Random()
+ val builder = StringBuilder(ID_LENGTH)
+ for (index in 0 until ID_LENGTH) {
+ builder.append(ALLOWED_CHARACTERS[random.nextInt(ALLOWED_CHARACTERS.length)])
+ }
+ return builder.toString()
+ }
+
+ private fun convertToDeviceItem(id: String): DeviceItem {
+ val json = devicesObject.optJSONObject(id) ?: JSONObject()
+ val device =
+ DeviceItem(
+ id,
+ json.optString("name"),
+ json.optString("mode"),
+ json.optString("icon"),
+ json.optBoolean("hide", false),
+ json.optBoolean("direct_view", false),
+ )
+ device.address = json.optString(ADDRESS)
+ return device
+ }
+
+ fun getDeviceById(id: String): DeviceItem = convertToDeviceItem(id)
+
+ fun getDeviceByIndex(index: Int): DeviceItem = convertToDeviceItem(deviceOrder.getString(index))
+
+ fun idExists(id: String): Boolean = devicesObject.has(id)
+
+ fun addressExists(address: String): Boolean {
+ val formattedAddress = DeviceItem.formatAddress(address)
+ for (i in devicesObject.keys()) {
+ if (devicesObject.getJSONObject(i).optString(ADDRESS) == formattedAddress) {
+ return true
+ }
+ }
+ return false
+ }
+
+ fun generateNewId(): String {
+ var id = generateRandomId()
+ while (devicesObject.has(id)) id = generateRandomId()
+ return id
+ }
+
+ fun addDevice(device: DeviceItem) {
+ if (!idExists(device.id)) deviceOrder.put(device.id)
+ val deviceObject =
+ JSONObject()
+ .put("name", device.name)
+ .put(ADDRESS, device.address)
+ .put("mode", device.mode)
+ .put("icon", device.iconName)
+ .put("hide", device.hide)
+ .put("direct_view", device.directView)
+ devicesObject.put(device.id, deviceObject)
+ saveChanges()
+ }
+
+ fun deleteDevice(id: String) {
+ for (i in 0 until deviceOrder.length()) {
+ if (deviceOrder[i] == id) {
+ deviceOrder.remove(i)
+ break
+ }
+ }
+ devicesObject.remove(id)
+ saveChanges()
+ DeviceSecrets(context, id).deleteDeviceSecrets()
+ }
+
+ fun moveDevice(
+ from: Int,
+ to: Int,
+ ) {
+ val list =
+ MutableList(deviceOrder.length()) {
+ deviceOrder.getString(it)
+ }
+ list.add(to, list.removeAt(from))
+ data.put(ORDER, JSONArray(list))
+ }
+
+ fun saveChanges() {
+ preferences.edit { putString("devices_json", data.toString()) }
+ }
+
+ companion object {
+ const val INTENT_EXTRA_DEVICE: String = "device"
+
+ private const val ALLOWED_CHARACTERS = "0123456789abcdefghijklmnobqrstuvw"
+ private const val ID_LENGTH = 8
+ private const val ORDER = "order"
+ private const val ADDRESS = "address"
+ private var storedData: JSONObject? = null
+
+ fun reloadFromPreferences() {
+ storedData = null
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/Global.kt b/app/src/main/java/io/github/domi04151309/home/helpers/Global.kt
new file mode 100644
index 0000000..3c54b95
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/Global.kt
@@ -0,0 +1,157 @@
+package io.github.domi04151309.home.helpers
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import android.os.Build
+import android.service.controls.DeviceTypes
+import android.util.Log
+import androidx.annotation.RequiresApi
+import androidx.appcompat.app.AppCompatActivity
+import androidx.preference.PreferenceManager
+import com.android.volley.ClientError
+import com.android.volley.NoConnectionError
+import com.android.volley.ParseError
+import com.android.volley.TimeoutError
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.api.EspEasyAPI
+import io.github.domi04151309.home.api.HueAPI
+import io.github.domi04151309.home.api.ShellyAPI
+import io.github.domi04151309.home.api.SimpleHomeAPI
+import io.github.domi04151309.home.api.Tasmota
+import io.github.domi04151309.home.api.UnifiedAPI
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+
+internal object Global {
+ const val LOG_TAG: String = "HomeApp"
+
+ const val DEFAULT_JSON: String = "{\"devices\":{}}"
+ const val ESP_EASY = "ESP Easy"
+ const val HUE_API = "Hue API"
+ const val SHELLY_GEN_1 = "Shelly Gen 1"
+ const val SHELLY_GEN_2 = "Shelly Gen 2"
+ const val SHELLY_GEN_3 = "Shelly Gen 3"
+ const val SIMPLE_HOME_API = "SimpleHome API"
+ const val TASMOTA = "Tasmota"
+ const val NODE_RED = "Node-RED"
+ const val WEBSITE = "Website"
+ const val FRITZ_AUTO_LOGIN = "Fritz! Auto-Login"
+ const val GRAFANA_AUTO_LOGIN = "Grafana Auto-Login"
+ const val PI_HOLE_AUTO_LOGIN = "Pi-hole Auto-Login"
+ val UNIFIED_MODES =
+ arrayOf(
+ ESP_EASY,
+ HUE_API,
+ SHELLY_GEN_1,
+ SHELLY_GEN_2,
+ SHELLY_GEN_3,
+ SIMPLE_HOME_API,
+ TASMOTA,
+ )
+ val POWER_MENU_MODES =
+ arrayOf(
+ ESP_EASY,
+ HUE_API,
+ SHELLY_GEN_1,
+ SHELLY_GEN_2,
+ SHELLY_GEN_3,
+ SIMPLE_HOME_API,
+ TASMOTA,
+ )
+
+ fun getCorrectAPI(
+ context: Context,
+ identifier: String,
+ deviceId: String,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface? = null,
+ tasmotaHelperInterface: HomeRecyclerViewHelperInterface? = null,
+ ): UnifiedAPI =
+ when (identifier) {
+ ESP_EASY -> EspEasyAPI(context, deviceId, recyclerViewInterface)
+ HUE_API -> HueAPI(context, deviceId, recyclerViewInterface)
+ SIMPLE_HOME_API -> SimpleHomeAPI(context, deviceId, recyclerViewInterface)
+ TASMOTA -> Tasmota(context, deviceId, tasmotaHelperInterface ?: recyclerViewInterface)
+ SHELLY_GEN_1 -> ShellyAPI(context, deviceId, recyclerViewInterface, 1)
+ SHELLY_GEN_2 -> ShellyAPI(context, deviceId, recyclerViewInterface, 2)
+ SHELLY_GEN_3 -> ShellyAPI(context, deviceId, recyclerViewInterface, 2)
+ else -> UnifiedAPI(context, deviceId, recyclerViewInterface)
+ }
+
+ @Suppress("CyclomaticComplexMethod")
+ fun getIcon(
+ icon: String,
+ default: Int = R.drawable.ic_warning,
+ ): Int =
+ when (icon.lowercase()) {
+ "christmas tree" -> R.drawable.ic_device_christmas_tree
+ "clock" -> R.drawable.ic_device_clock
+ "display" -> R.drawable.ic_device_display
+ "display alt" -> R.drawable.ic_device_display_alt
+ "docker" -> R.drawable.ic_device_docker
+ "electricity" -> R.drawable.ic_device_electricity
+ "entertainment" -> R.drawable.ic_device_speaker
+ "gauge" -> R.drawable.ic_device_gauge
+ "grafana" -> R.drawable.ic_device_grafana
+ "heating" -> R.drawable.ic_device_thermometer
+ "hygrometer" -> R.drawable.ic_device_hygrometer
+ "lamp" -> R.drawable.ic_device_lamp
+ "lights" -> R.drawable.ic_device_lamp
+ "raspberry pi" -> R.drawable.ic_device_raspberry_pi
+ "raspberry pi alt" -> R.drawable.ic_device_raspberry_pi_alt
+ "router" -> R.drawable.ic_device_router
+ "speaker" -> R.drawable.ic_device_speaker
+ "schwibbogen" -> R.drawable.ic_device_schwibbogen
+ "stack" -> R.drawable.ic_device_stack
+ "socket" -> R.drawable.ic_device_socket
+ "thermometer" -> R.drawable.ic_device_thermometer
+ "webcam" -> R.drawable.ic_device_webcam
+ else -> default
+ }
+
+ @RequiresApi(Build.VERSION_CODES.R)
+ fun getDeviceType(icon: String): Int =
+ when (icon.lowercase()) {
+ "christmas tree", "electricity", "schwibbogen", "socket" -> DeviceTypes.TYPE_OUTLET
+ "display", "display alt" -> DeviceTypes.TYPE_DISPLAY
+ "gauge", "heating", "thermometer" -> DeviceTypes.TYPE_AC_HEATER
+ "hygrometer" -> DeviceTypes.TYPE_HUMIDIFIER
+ "lamp", "lights" -> DeviceTypes.TYPE_LIGHT
+ "webcam" -> DeviceTypes.TYPE_CAMERA
+ else -> DeviceTypes.TYPE_UNKNOWN
+ }
+
+ fun checkNetwork(context: Context): Boolean {
+ if (
+ !PreferenceManager.getDefaultSharedPreferences(context)
+ .getBoolean("safety_checks", true)
+ ) {
+ return true
+ }
+
+ val connectivityManager =
+ context.getSystemService(
+ AppCompatActivity.CONNECTIVITY_SERVICE,
+ ) as ConnectivityManager
+ val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
+ return if (capabilities != null) {
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
+ } else {
+ true
+ }
+ }
+
+ fun volleyError(
+ c: Context,
+ error: java.lang.Exception,
+ ): String {
+ Log.w(LOG_TAG, error)
+ return when (error) {
+ is TimeoutError, is NoConnectionError -> c.resources.getString(R.string.main_device_unavailable)
+ is ParseError -> c.resources.getString(R.string.main_parse_error)
+ is ClientError -> c.resources.getString(R.string.main_client_error)
+ else -> c.resources.getString(R.string.main_device_unavailable)
+ }
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/HueLightListener.kt b/app/src/main/java/io/github/domi04151309/home/helpers/HueLightListener.kt
new file mode 100644
index 0000000..0efcc21
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/HueLightListener.kt
@@ -0,0 +1,20 @@
+package io.github.domi04151309.home.helpers
+
+import io.github.domi04151309.home.data.LightStates
+
+class HueLightListener {
+ private var listeners = mutableListOf<(data: LightStates.Light) -> Unit>()
+ var state: LightStates.Light = LightStates.Light()
+ set(value) {
+ if (value != field) {
+ field = value
+ listeners.forEach {
+ it(value)
+ }
+ }
+ }
+
+ fun addOnDataChangedListener(listener: (data: LightStates.Light) -> Unit) {
+ listeners.add(listener)
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/HueUtils.kt b/app/src/main/java/io/github/domi04151309/home/helpers/HueUtils.kt
new file mode 100644
index 0000000..2e9294a
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/HueUtils.kt
@@ -0,0 +1,66 @@
+package io.github.domi04151309.home.helpers
+
+import android.graphics.Color
+
+@Suppress("MagicNumber")
+object HueUtils {
+ const val MIN_COLOR_TEMPERATURE: Int = 153
+ const val MAX_BRIGHTNESS: Int = 255
+
+ private const val ARGUMENT_OUT_OF_RANGE = "Argument out of range."
+
+ fun defaultColors(): IntArray =
+ IntArray(7) {
+ index ->
+ Color.HSVToColor(floatArrayOf(index * 60f, 1f, 1f))
+ }
+
+ fun ctToRGB(ct: Int): Int {
+ require(!(ct < MIN_COLOR_TEMPERATURE || ct > 500)) { ARGUMENT_OUT_OF_RANGE }
+ return ColorUtils.temperatureToRGB((6500 - 12.968299711 * (ct - MIN_COLOR_TEMPERATURE)).toInt())
+ }
+
+ fun ctToKelvin(ct: Int): String {
+ require(!(ct < MIN_COLOR_TEMPERATURE || ct > 500)) { ARGUMENT_OUT_OF_RANGE }
+ return "${(6500 - 12.968299711 * (ct - MIN_COLOR_TEMPERATURE)).toInt()} K"
+ }
+
+ fun hueSatToRGB(
+ hue: Int,
+ sat: Int,
+ ): Int {
+ require(!(hue > 65_535 || sat > 254)) { ARGUMENT_OUT_OF_RANGE }
+ return Color.HSVToColor(floatArrayOf(hue * 0.005493248F, sat / 254F, 1F))
+ }
+
+ fun hueToRGB(hue: Int): Int {
+ require(hue <= 65_535) { ARGUMENT_OUT_OF_RANGE }
+ return Color.HSVToColor(floatArrayOf(hue * 0.005493248F, 1F, 1F))
+ }
+
+ fun hueToDegree(hue: Int): String {
+ require(hue <= 65_535) { ARGUMENT_OUT_OF_RANGE }
+ return "${(hue * 0.005493248F).toInt()}°"
+ }
+
+ fun satToPercent(sat: Int): String {
+ require(sat <= 254) { ARGUMENT_OUT_OF_RANGE }
+ return "${(sat / 254F * 100).toInt()} %"
+ }
+
+ fun briToPercent(bri: Int): String =
+ when {
+ bri < 1 -> "0 %"
+ bri > 254 -> "100 %"
+ else -> "${(bri / 254F * 100).toInt()} %"
+ }
+
+ fun rgbToHueSat(color: Int): IntArray {
+ val hsv = FloatArray(3)
+ Color.colorToHSV(color, hsv)
+ return intArrayOf(
+ (hsv[0] / 0.0054932478).toInt(),
+ (hsv[1] * 254).toInt(),
+ )
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/P.kt b/app/src/main/java/io/github/domi04151309/home/helpers/P.kt
new file mode 100644
index 0000000..de14199
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/P.kt
@@ -0,0 +1,10 @@
+@file:Suppress("HardCodedStringLiteral")
+
+package io.github.domi04151309.home.helpers
+
+internal object P {
+ const val PREF_COLUMNS = "columns"
+ const val PREF_COLUMNS_DEFAULT = "auto"
+ const val PREF_CONTROLS_AUTH = "controls_auth"
+ const val PREF_CONTROLS_AUTH_DEFAULT = false
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/SliderUtils.kt b/app/src/main/java/io/github/domi04151309/home/helpers/SliderUtils.kt
new file mode 100644
index 0000000..21fd31b
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/SliderUtils.kt
@@ -0,0 +1,68 @@
+package io.github.domi04151309.home.helpers
+
+import android.animation.ObjectAnimator
+import android.content.res.Resources
+import android.graphics.LinearGradient
+import android.graphics.Shader
+import android.graphics.drawable.LayerDrawable
+import android.graphics.drawable.PaintDrawable
+import android.view.View
+import android.view.animation.DecelerateInterpolator
+import com.google.android.material.slider.Slider
+
+object SliderUtils {
+ private const val CORNER_RADIUS = 16
+ private const val MARGIN_VERTICAL = 16
+ private const val MARGIN_HORIZONTAL = 14
+ private const val ANIMATION_DURATION = 300L
+
+ private fun dpToPx(
+ resources: Resources,
+ dp: Int,
+ ): Int = (dp * resources.displayMetrics.density).toInt()
+
+ fun setSliderGradientNow(
+ view: View,
+ colors: IntArray,
+ ) {
+ val gradient = PaintDrawable()
+ gradient.setCornerRadius(dpToPx(view.resources, CORNER_RADIUS).toFloat())
+ gradient.paint.shader =
+ LinearGradient(
+ 0f, 0f,
+ view.width.toFloat(), 0f,
+ colors,
+ null,
+ Shader.TileMode.CLAMP,
+ )
+
+ val layers = LayerDrawable(arrayOf(gradient))
+ layers.setLayerInset(
+ 0,
+ dpToPx(view.resources, MARGIN_HORIZONTAL),
+ dpToPx(view.resources, MARGIN_VERTICAL),
+ dpToPx(view.resources, MARGIN_HORIZONTAL),
+ dpToPx(view.resources, MARGIN_VERTICAL),
+ )
+ view.background = layers
+ }
+
+ fun setSliderGradient(
+ view: View,
+ colors: IntArray,
+ ) {
+ view.post {
+ setSliderGradientNow(view, colors)
+ }
+ }
+
+ fun setProgress(
+ slider: Slider,
+ value: Int,
+ ) {
+ val animation = ObjectAnimator.ofFloat(slider, "value", value.toFloat())
+ animation.duration = ANIMATION_DURATION
+ animation.interpolator = DecelerateInterpolator()
+ animation.start()
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/TasmotaHelper.kt b/app/src/main/java/io/github/domi04151309/home/helpers/TasmotaHelper.kt
new file mode 100644
index 0000000..dd19ead
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/TasmotaHelper.kt
@@ -0,0 +1,149 @@
+package io.github.domi04151309.home.helpers
+
+import android.content.Context
+import android.view.LayoutInflater
+import android.view.ViewGroup
+import android.widget.EditText
+import androidx.core.content.edit
+import androidx.preference.PreferenceManager
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.api.UnifiedAPI
+import org.json.JSONArray
+import org.json.JSONObject
+
+class TasmotaHelper(private val c: Context, private val tasmota: UnifiedAPI) {
+ private val prefs = PreferenceManager.getDefaultSharedPreferences(c)
+ private val nullParent: ViewGroup? = null
+
+ fun updateItem(
+ callback: UnifiedAPI.CallbackInterface,
+ index: Int,
+ ) {
+ val array = JSONArray(prefs.getString(tasmota.deviceId, EMPTY_ARRAY))
+ val arrayItem = array.optJSONObject(index) ?: JSONObject()
+ val view = LayoutInflater.from(c).inflate(R.layout.dialog_tasmota_add, nullParent, false)
+ val titleTxt = view.findViewById(R.id.title)
+ val commandTxt = view.findViewById(R.id.command)
+ titleTxt.setText(arrayItem.optString(TITLE))
+ commandTxt.setText(arrayItem.optString(COMMAND))
+ MaterialAlertDialogBuilder(c)
+ .setTitle(R.string.tasmota_add_command)
+ .setView(view)
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ val newTitle = titleTxt.text.toString()
+ val newCommand = commandTxt.text.toString()
+ array.remove(index)
+ prefs.edit {
+ putString(
+ tasmota.deviceId,
+ array.put(
+ JSONObject()
+ .put(
+ TITLE,
+ if (newTitle == "") {
+ c.resources.getString(R.string.tasmota_add_command_dialog_title_empty)
+ } else {
+ newTitle
+ },
+ )
+ .put(
+ COMMAND,
+ if (newCommand == "") {
+ c.resources.getString(
+ R.string.tasmota_add_command_dialog_command_empty,
+ )
+ } else {
+ newCommand
+ },
+ ),
+ ).toString(),
+ )
+ }
+ tasmota.loadList(callback)
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ }
+
+ fun addToList(
+ callback: UnifiedAPI.CallbackInterface,
+ title: String = "",
+ command: String = "",
+ ) {
+ val view = LayoutInflater.from(c).inflate(R.layout.dialog_tasmota_add, nullParent, false)
+ val titleTxt = view.findViewById(R.id.title)
+ val commandTxt = view.findViewById(R.id.command)
+ titleTxt.setText(title)
+ commandTxt.setText(command)
+ MaterialAlertDialogBuilder(c)
+ .setTitle(R.string.tasmota_add_command)
+ .setView(view)
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ val newTitle = titleTxt.text.toString()
+ val newCommand = commandTxt.text.toString()
+ prefs.edit {
+ putString(
+ tasmota.deviceId,
+ JSONArray(
+ prefs.getString(tasmota.deviceId, EMPTY_ARRAY),
+ ).put(
+ JSONObject()
+ .put(
+ TITLE,
+ if (newTitle == "") {
+ c.resources.getString(
+ R.string.tasmota_add_command_dialog_title_empty,
+ )
+ } else {
+ newTitle
+ },
+ )
+ .put(
+ COMMAND,
+ if (newCommand == "") {
+ c.resources.getString(
+ R.string.tasmota_add_command_dialog_command_empty,
+ )
+ } else {
+ newCommand
+ },
+ ),
+ ).toString(),
+ )
+ }
+ tasmota.loadList(callback)
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ }
+
+ fun removeFromList(
+ callback: UnifiedAPI.CallbackInterface,
+ index: Int,
+ ) {
+ val array = JSONArray(prefs.getString(tasmota.deviceId, EMPTY_ARRAY))
+ array.remove(index)
+ prefs.edit { putString(tasmota.deviceId, array.toString()) }
+ tasmota.loadList(callback)
+ }
+
+ fun executeOnce(callback: UnifiedAPI.CallbackInterface) {
+ val view = LayoutInflater.from(c).inflate(R.layout.dialog_tasmota_execute_once, nullParent, false)
+ val command = view.findViewById(R.id.command)
+ MaterialAlertDialogBuilder(c)
+ .setTitle(R.string.tasmota_execute_once)
+ .setView(view)
+ .setPositiveButton(android.R.string.ok) { _, _ ->
+ tasmota.execute(command.text.toString(), callback)
+ }
+ .setNegativeButton(android.R.string.cancel) { _, _ -> }
+ .show()
+ }
+
+ companion object {
+ const val EMPTY_ARRAY: String = "[]"
+ private const val TITLE = "title"
+ private const val COMMAND = "command"
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/helpers/UpdateHandler.kt b/app/src/main/java/io/github/domi04151309/home/helpers/UpdateHandler.kt
new file mode 100644
index 0000000..0c63aab
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/helpers/UpdateHandler.kt
@@ -0,0 +1,32 @@
+package io.github.domi04151309.home.helpers
+
+import android.os.Handler
+import android.os.Looper
+
+class UpdateHandler : Handler(Looper.getMainLooper()) {
+ var running: Boolean = false
+ private set
+
+ fun setUpdateFunction(function: () -> Unit) {
+ removeCallbacksAndMessages(null)
+ postDelayed(
+ object : Runnable {
+ override fun run() {
+ function()
+ postDelayed(this, UPDATE_DELAY)
+ }
+ },
+ 0,
+ )
+ running = true
+ }
+
+ fun stop() {
+ running = false
+ removeCallbacksAndMessages(null)
+ }
+
+ companion object {
+ private const val UPDATE_DELAY = 1000L
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/interfaces/HomeRecyclerViewHelperInterface.kt b/app/src/main/java/io/github/domi04151309/home/interfaces/HomeRecyclerViewHelperInterface.kt
new file mode 100644
index 0000000..5723dc8
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/interfaces/HomeRecyclerViewHelperInterface.kt
@@ -0,0 +1,17 @@
+package io.github.domi04151309.home.interfaces
+
+import android.view.View
+import io.github.domi04151309.home.data.ListViewItem
+
+interface HomeRecyclerViewHelperInterface {
+ fun onItemClicked(
+ view: View,
+ data: ListViewItem,
+ )
+
+ fun onStateChanged(
+ view: View,
+ data: ListViewItem,
+ state: Boolean,
+ )
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/interfaces/HueAdvancedLampInterface.kt b/app/src/main/java/io/github/domi04151309/home/interfaces/HueAdvancedLampInterface.kt
new file mode 100644
index 0000000..a6a2039
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/interfaces/HueAdvancedLampInterface.kt
@@ -0,0 +1,12 @@
+package io.github.domi04151309.home.interfaces
+
+interface HueAdvancedLampInterface : HueLampInterface {
+ fun onBrightnessChanged(brightness: Int)
+
+ fun onHueSatChanged(
+ hue: Int,
+ sat: Int,
+ )
+
+ fun onCtChanged(ct: Int)
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/interfaces/HueLampInterface.kt b/app/src/main/java/io/github/domi04151309/home/interfaces/HueLampInterface.kt
new file mode 100644
index 0000000..81bf43f
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/interfaces/HueLampInterface.kt
@@ -0,0 +1,12 @@
+package io.github.domi04151309.home.interfaces
+
+import io.github.domi04151309.home.data.DeviceItem
+
+interface HueLampInterface {
+ var id: String
+ var device: DeviceItem
+ var addressPrefix: String
+ var canReceiveRequest: Boolean
+
+ fun onColorChanged(color: Int)
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/interfaces/HueRoomInterface.kt b/app/src/main/java/io/github/domi04151309/home/interfaces/HueRoomInterface.kt
new file mode 100644
index 0000000..ce027ca
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/interfaces/HueRoomInterface.kt
@@ -0,0 +1,9 @@
+package io.github.domi04151309.home.interfaces
+
+import io.github.domi04151309.home.helpers.HueLightListener
+import org.json.JSONArray
+
+interface HueRoomInterface : HueLampInterface {
+ var lights: JSONArray?
+ var lampData: HueLightListener
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/interfaces/RecyclerViewHelperInterface.kt b/app/src/main/java/io/github/domi04151309/home/interfaces/RecyclerViewHelperInterface.kt
new file mode 100644
index 0000000..af08f2c
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/interfaces/RecyclerViewHelperInterface.kt
@@ -0,0 +1,10 @@
+package io.github.domi04151309.home.interfaces
+
+import android.view.View
+
+interface RecyclerViewHelperInterface {
+ fun onItemClicked(
+ view: View,
+ position: Int,
+ )
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/interfaces/RecyclerViewHelperInterfaceAdvanced.kt b/app/src/main/java/io/github/domi04151309/home/interfaces/RecyclerViewHelperInterfaceAdvanced.kt
new file mode 100644
index 0000000..6f86b9b
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/interfaces/RecyclerViewHelperInterfaceAdvanced.kt
@@ -0,0 +1,7 @@
+package io.github.domi04151309.home.interfaces
+
+import androidx.recyclerview.widget.RecyclerView
+
+interface RecyclerViewHelperInterfaceAdvanced : RecyclerViewHelperInterface {
+ fun onItemHandleTouched(viewHolder: RecyclerView.ViewHolder)
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/interfaces/SceneRecyclerViewHelperInterface.kt b/app/src/main/java/io/github/domi04151309/home/interfaces/SceneRecyclerViewHelperInterface.kt
new file mode 100644
index 0000000..a65642e
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/interfaces/SceneRecyclerViewHelperInterface.kt
@@ -0,0 +1,17 @@
+package io.github.domi04151309.home.interfaces
+
+import android.view.View
+import io.github.domi04151309.home.data.SceneListItem
+
+interface SceneRecyclerViewHelperInterface {
+ fun onItemClicked(
+ view: View,
+ data: SceneListItem,
+ )
+
+ fun onStateChanged(
+ view: View,
+ data: SceneListItem,
+ state: Boolean,
+ )
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/services/ControlBuilders.kt b/app/src/main/java/io/github/domi04151309/home/services/ControlBuilders.kt
new file mode 100644
index 0000000..ff49f31
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/services/ControlBuilders.kt
@@ -0,0 +1,163 @@
+package io.github.domi04151309.home.services
+
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.service.controls.Control
+import android.service.controls.templates.ControlButton
+import android.service.controls.templates.RangeTemplate
+import android.service.controls.templates.StatelessTemplate
+import android.service.controls.templates.ToggleRangeTemplate
+import android.service.controls.templates.ToggleTemplate
+import androidx.annotation.RequiresApi
+import androidx.preference.PreferenceManager
+import io.github.domi04151309.home.R
+import io.github.domi04151309.home.activities.ControlInfoActivity
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.ListViewItem
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.helpers.P
+
+@RequiresApi(Build.VERSION_CODES.R)
+object ControlBuilders {
+ private const val RANGE_MIN = 0f
+ private const val RANGE_MAX = 100f
+ private const val RANGE_STEP = 1f
+
+ private var requestCode = 0
+
+ private fun getPendingIntent(
+ context: Context,
+ id: String,
+ title: String,
+ ): PendingIntent =
+ PendingIntent.getActivity(
+ context,
+ requestCode++,
+ Intent(context, ControlInfoActivity::class.java).apply {
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
+ putExtra(ControlInfoActivity.EXTRA_ID, id)
+ putExtra(ControlInfoActivity.EXTRA_TITLE, title)
+ },
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+
+ private fun getControlButton(item: ListViewItem): ControlButton =
+ ControlButton(
+ item.state == true,
+ item.state.toString(),
+ )
+
+ private fun getRangeTemplate(
+ id: String,
+ item: ListViewItem,
+ ): RangeTemplate =
+ RangeTemplate(
+ id,
+ RANGE_MIN,
+ RANGE_MAX,
+ item.percentage?.toFloat() ?: 0f,
+ RANGE_STEP,
+ "%.0f %%",
+ )
+
+ fun buildUnreachableControl(
+ context: Context,
+ id: String,
+ device: DeviceItem,
+ ): Control =
+ Control.StatefulBuilder(id, getPendingIntent(context, id, device.name))
+ .setTitle(device.name)
+ .setZone(device.name)
+ .setStructure(context.resources.getString(R.string.app_name))
+ .setDeviceType(Global.getDeviceType(device.iconName))
+ .setStatus(Control.STATUS_DISABLED)
+ .setStatusText(context.resources.getString(R.string.str_unreachable))
+ .build()
+
+ fun buildGenericControl(
+ context: Context,
+ listItem: ListViewItem,
+ device: DeviceItem,
+ ): Control {
+ val id = device.id + '@' + listItem.hidden
+ return Control.StatelessBuilder(
+ id,
+ getPendingIntent(context, id, listItem.title),
+ )
+ .setTitle(listItem.title)
+ .setSubtitle(device.name)
+ .setZone(device.name)
+ .setStructure(context.resources.getString(R.string.app_name))
+ .setDeviceType(Global.getDeviceType(device.iconName))
+ .build()
+ }
+
+ fun buildStatefulControl(
+ context: Context,
+ id: String,
+ listItem: ListViewItem,
+ device: DeviceItem,
+ ): Control {
+ val controlBuilder =
+ Control.StatefulBuilder(id, getPendingIntent(context, id, listItem.title))
+ .setTitle(listItem.title)
+ .setSubtitle(device.name)
+ .setZone(device.name)
+ .setStructure(context.resources.getString(R.string.app_name))
+ .setDeviceType(Global.getDeviceType(device.iconName))
+ .setStatus(Control.STATUS_OK)
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ controlBuilder.setAuthRequired(
+ PreferenceManager.getDefaultSharedPreferences(context)
+ .getBoolean(
+ P.PREF_CONTROLS_AUTH,
+ P.PREF_CONTROLS_AUTH_DEFAULT,
+ ),
+ )
+ }
+
+ if (listItem.state != null) {
+ controlBuilder.setStatusText(
+ context.resources.getString(
+ if (listItem.state == true) {
+ R.string.str_on
+ } else {
+ R.string.str_off
+ },
+ ),
+ )
+ }
+
+ if (listItem.state != null && listItem.percentage != null) {
+ controlBuilder.setControlTemplate(
+ ToggleRangeTemplate(
+ id,
+ getControlButton(listItem),
+ getRangeTemplate(id, listItem),
+ ),
+ )
+ } else if (listItem.state != null) {
+ controlBuilder.setControlTemplate(
+ ToggleTemplate(
+ id,
+ getControlButton(listItem),
+ ),
+ )
+ } else if (listItem.percentage != null) {
+ controlBuilder.setControlTemplate(
+ getRangeTemplate(id, listItem),
+ )
+ }
+
+ if (device.mode == Global.TASMOTA) {
+ controlBuilder.setControlTemplate(
+ StatelessTemplate(id),
+ )
+ }
+
+ return controlBuilder.build()
+ }
+}
diff --git a/app/src/main/java/io/github/domi04151309/home/services/ControlService.kt b/app/src/main/java/io/github/domi04151309/home/services/ControlService.kt
new file mode 100644
index 0000000..41a2a5b
--- /dev/null
+++ b/app/src/main/java/io/github/domi04151309/home/services/ControlService.kt
@@ -0,0 +1,194 @@
+package io.github.domi04151309.home.services
+
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.service.controls.Control
+import android.service.controls.ControlsProviderService
+import android.service.controls.actions.BooleanAction
+import android.service.controls.actions.CommandAction
+import android.service.controls.actions.ControlAction
+import android.service.controls.actions.FloatAction
+import android.widget.Toast
+import androidx.annotation.RequiresApi
+import io.github.domi04151309.home.api.UnifiedAPI
+import io.github.domi04151309.home.data.DeviceItem
+import io.github.domi04151309.home.data.UnifiedRequestCallback
+import io.github.domi04151309.home.helpers.Devices
+import io.github.domi04151309.home.helpers.Global
+import io.github.domi04151309.home.interfaces.HomeRecyclerViewHelperInterface
+import java.util.concurrent.Flow
+import java.util.function.Consumer
+
+@RequiresApi(Build.VERSION_CODES.R)
+class ControlService : ControlsProviderService() {
+ private var updateSubscriber: Flow.Subscriber? = null
+ private var finishedRequests = 0
+
+ override fun createPublisherForAllAvailable(): Flow.Publisher =
+ Flow.Publisher { subscriber ->
+ updateSubscriber = subscriber
+ if (!Global.checkNetwork(this)) {
+ subscriber.onComplete()
+ @Suppress("LabeledExpression")
+ return@Publisher
+ }
+ val devices = Devices(this)
+ val relevantDevices = mutableListOf()
+ for (i in 0 until devices.length) {
+ val currentDevice = devices.getDeviceByIndex(i)
+ if (
+ !currentDevice.hide &&
+ Global.POWER_MENU_MODES.contains(currentDevice.mode)
+ ) {
+ relevantDevices.add(currentDevice)
+ }
+ }
+ finishedRequests = 0
+ for (index in 0 until relevantDevices.size) {
+ Global.getCorrectAPI(this, relevantDevices[index].mode, relevantDevices[index].id)
+ .loadList(
+ getAllAvailableCallback(
+ subscriber,
+ relevantDevices,
+ index,
+ ),
+ )
+ }
+ }
+
+ private fun getAllAvailableCallback(
+ subscriber: Flow.Subscriber,
+ relevantDevices: MutableList,
+ index: Int,
+ ): UnifiedAPI.CallbackInterface =
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ for (it in holder.response ?: emptyList()) {
+ subscriber.onNext(
+ ControlBuilders.buildGenericControl(this@ControlService, it, relevantDevices[index]),
+ )
+ }
+ finishedRequests++
+ if (finishedRequests == relevantDevices.size) subscriber.onComplete()
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ // Do nothing.
+ }
+ }
+
+ private fun loadStatefulControl(
+ subscriber: Flow.Subscriber?,
+ id: String,
+ ) {
+ val device = Devices(this).getDeviceById(id.substring(0, id.indexOf('@')))
+ if (Global.checkNetwork(this)) {
+ Global
+ .getCorrectAPI(this, device.mode, device.id)
+ .loadList(getStatefulControlsCallback(device, id, subscriber))
+ } else {
+ subscriber?.onNext(ControlBuilders.buildUnreachableControl(this, id, device))
+ }
+ }
+
+ private fun getStatefulControlsCallback(
+ device: DeviceItem,
+ id: String,
+ subscriber: Flow.Subscriber?,
+ ) = object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ if (holder.response == null) {
+ subscriber?.onNext(ControlBuilders.buildUnreachableControl(this@ControlService, id, device))
+ return
+ }
+ for (it in holder.response) {
+ if (device.id + '@' + it.hidden != id) continue
+ subscriber?.onNext(ControlBuilders.buildStatefulControl(this@ControlService, id, it, device))
+ }
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ // Do nothing.
+ }
+ }
+
+ override fun createPublisherFor(controlIds: MutableList): Flow.Publisher =
+ Flow.Publisher { subscriber ->
+ updateSubscriber = subscriber
+ subscriber.onSubscribe(
+ object : Flow.Subscription {
+ override fun request(n: Long) {
+ // Do nothing.
+ }
+
+ override fun cancel() {
+ // Do nothing.
+ }
+ },
+ )
+ for (id in controlIds) {
+ loadStatefulControl(subscriber, id)
+ }
+ }
+
+ override fun performControlAction(
+ controlId: String,
+ action: ControlAction,
+ consumer: Consumer,
+ ) {
+ if (Global.checkNetwork(this)) {
+ val device =
+ Devices(this)
+ .getDeviceById(controlId.substring(0, controlId.indexOf('@')))
+ val api = Global.getCorrectAPI(this, device.mode, device.id)
+ val relevantId = controlId.substring(device.id.length + 1)
+ if (action is BooleanAction) {
+ api.changeSwitchState(relevantId, action.newState)
+ } else if (action is FloatAction) {
+ api.changePercentage(relevantId, action.newValue)
+ } else if (action is CommandAction) {
+ api.execute(
+ relevantId,
+ object : UnifiedAPI.CallbackInterface {
+ override fun onItemsLoaded(
+ holder: UnifiedRequestCallback,
+ recyclerViewInterface: HomeRecyclerViewHelperInterface?,
+ ) {
+ // Do nothing.
+ }
+
+ override fun onExecuted(
+ result: String,
+ shouldRefresh: Boolean,
+ ) {
+ Toast.makeText(this@ControlService, result, Toast.LENGTH_LONG).show()
+ }
+ },
+ )
+ }
+ consumer.accept(ControlAction.RESPONSE_OK)
+ Handler(Looper.getMainLooper()).postDelayed({
+ loadStatefulControl(updateSubscriber, controlId)
+ }, UPDATE_DELAY)
+ } else {
+ consumer.accept(ControlAction.RESPONSE_FAIL)
+ }
+ }
+
+ companion object {
+ private const val UPDATE_DELAY = 100L
+ }
+}
diff --git a/app/src/main/res/drawable-nodpi/header_bg.webp b/app/src/main/res/drawable-nodpi/header_bg.webp
new file mode 100644
index 0000000..85ae53f
Binary files /dev/null and b/app/src/main/res/drawable-nodpi/header_bg.webp differ
diff --git a/app/src/main/res/drawable/ic_about_contributor.xml b/app/src/main/res/drawable/ic_about_contributor.xml
new file mode 100644
index 0000000..40ad8a6
--- /dev/null
+++ b/app/src/main/res/drawable/ic_about_contributor.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_about_github.xml b/app/src/main/res/drawable/ic_about_github.xml
new file mode 100644
index 0000000..7899932
--- /dev/null
+++ b/app/src/main/res/drawable/ic_about_github.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_about_info.xml b/app/src/main/res/drawable/ic_about_info.xml
new file mode 100644
index 0000000..a302ace
--- /dev/null
+++ b/app/src/main/res/drawable/ic_about_info.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_about_library.xml b/app/src/main/res/drawable/ic_about_library.xml
new file mode 100644
index 0000000..52ea4c5
--- /dev/null
+++ b/app/src/main/res/drawable/ic_about_library.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_about_palette.xml b/app/src/main/res/drawable/ic_about_palette.xml
new file mode 100644
index 0000000..87e47fc
--- /dev/null
+++ b/app/src/main/res/drawable/ic_about_palette.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_add.xml b/app/src/main/res/drawable/ic_add.xml
new file mode 100644
index 0000000..ff3a024
--- /dev/null
+++ b/app/src/main/res/drawable/ic_add.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_arrow_back.xml b/app/src/main/res/drawable/ic_arrow_back.xml
new file mode 100644
index 0000000..0266dd9
--- /dev/null
+++ b/app/src/main/res/drawable/ic_arrow_back.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_buttonpress.xml b/app/src/main/res/drawable/ic_buttonpress.xml
new file mode 100644
index 0000000..e242cbe
--- /dev/null
+++ b/app/src/main/res/drawable/ic_buttonpress.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_circle.xml b/app/src/main/res/drawable/ic_circle.xml
new file mode 100644
index 0000000..691ac1f
--- /dev/null
+++ b/app/src/main/res/drawable/ic_circle.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/drawable/ic_color_palette.xml b/app/src/main/res/drawable/ic_color_palette.xml
new file mode 100644
index 0000000..764a8f9
--- /dev/null
+++ b/app/src/main/res/drawable/ic_color_palette.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_delete.xml b/app/src/main/res/drawable/ic_delete.xml
new file mode 100644
index 0000000..29385f6
--- /dev/null
+++ b/app/src/main/res/drawable/ic_delete.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_christmas_tree.webp b/app/src/main/res/drawable/ic_device_christmas_tree.webp
new file mode 100644
index 0000000..4bbec06
Binary files /dev/null and b/app/src/main/res/drawable/ic_device_christmas_tree.webp differ
diff --git a/app/src/main/res/drawable/ic_device_clock.xml b/app/src/main/res/drawable/ic_device_clock.xml
new file mode 100644
index 0000000..65634dc
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_clock.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_display.xml b/app/src/main/res/drawable/ic_device_display.xml
new file mode 100644
index 0000000..6b4f560
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_display.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_display_alt.xml b/app/src/main/res/drawable/ic_device_display_alt.xml
new file mode 100644
index 0000000..d4bae88
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_display_alt.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_docker.xml b/app/src/main/res/drawable/ic_device_docker.xml
new file mode 100644
index 0000000..86c16d4
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_docker.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_electricity.xml b/app/src/main/res/drawable/ic_device_electricity.xml
new file mode 100644
index 0000000..062aee1
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_electricity.xml
@@ -0,0 +1,10 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_gauge.xml b/app/src/main/res/drawable/ic_device_gauge.xml
new file mode 100644
index 0000000..76ef26c
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_gauge.xml
@@ -0,0 +1,20 @@
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_grafana.xml b/app/src/main/res/drawable/ic_device_grafana.xml
new file mode 100644
index 0000000..dd76206
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_grafana.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_hygrometer.xml b/app/src/main/res/drawable/ic_device_hygrometer.xml
new file mode 100644
index 0000000..3c31c5e
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_hygrometer.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_lamp.xml b/app/src/main/res/drawable/ic_device_lamp.xml
new file mode 100644
index 0000000..303140c
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_lamp.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_raspberry_pi.xml b/app/src/main/res/drawable/ic_device_raspberry_pi.xml
new file mode 100644
index 0000000..10b0814
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_raspberry_pi.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_raspberry_pi_alt.xml b/app/src/main/res/drawable/ic_device_raspberry_pi_alt.xml
new file mode 100644
index 0000000..13bc7eb
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_raspberry_pi_alt.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_router.xml b/app/src/main/res/drawable/ic_device_router.xml
new file mode 100644
index 0000000..80e98c0
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_router.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_schwibbogen.xml b/app/src/main/res/drawable/ic_device_schwibbogen.xml
new file mode 100644
index 0000000..8fdeb7a
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_schwibbogen.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_socket.xml b/app/src/main/res/drawable/ic_device_socket.xml
new file mode 100644
index 0000000..e5402e3
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_socket.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_speaker.xml b/app/src/main/res/drawable/ic_device_speaker.xml
new file mode 100644
index 0000000..b4b4201
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_speaker.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_stack.xml b/app/src/main/res/drawable/ic_device_stack.xml
new file mode 100644
index 0000000..16715ff
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_stack.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_thermometer.xml b/app/src/main/res/drawable/ic_device_thermometer.xml
new file mode 100644
index 0000000..83e9877
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_thermometer.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_device_webcam.xml b/app/src/main/res/drawable/ic_device_webcam.xml
new file mode 100644
index 0000000..8955266
--- /dev/null
+++ b/app/src/main/res/drawable/ic_device_webcam.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_do.xml b/app/src/main/res/drawable/ic_do.xml
new file mode 100644
index 0000000..c019127
--- /dev/null
+++ b/app/src/main/res/drawable/ic_do.xml
@@ -0,0 +1,15 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_done.xml b/app/src/main/res/drawable/ic_done.xml
new file mode 100644
index 0000000..72519e6
--- /dev/null
+++ b/app/src/main/res/drawable/ic_done.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_drag_handle.xml b/app/src/main/res/drawable/ic_drag_handle.xml
new file mode 100644
index 0000000..ca8eedd
--- /dev/null
+++ b/app/src/main/res/drawable/ic_drag_handle.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_edit.xml b/app/src/main/res/drawable/ic_edit.xml
new file mode 100644
index 0000000..0418e54
--- /dev/null
+++ b/app/src/main/res/drawable/ic_edit.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_home_accent.xml b/app/src/main/res/drawable/ic_home_accent.xml
new file mode 100644
index 0000000..4ad0a81
--- /dev/null
+++ b/app/src/main/res/drawable/ic_home_accent.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_home_white.xml b/app/src/main/res/drawable/ic_home_white.xml
new file mode 100644
index 0000000..a77cac8
--- /dev/null
+++ b/app/src/main/res/drawable/ic_home_white.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_hue_lamp_base.xml b/app/src/main/res/drawable/ic_hue_lamp_base.xml
new file mode 100644
index 0000000..2c7ace1
--- /dev/null
+++ b/app/src/main/res/drawable/ic_hue_lamp_base.xml
@@ -0,0 +1,5 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_hue_lamp_color.xml b/app/src/main/res/drawable/ic_hue_lamp_color.xml
new file mode 100644
index 0000000..d342a69
--- /dev/null
+++ b/app/src/main/res/drawable/ic_hue_lamp_color.xml
@@ -0,0 +1,4 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_hue_scene_add.xml b/app/src/main/res/drawable/ic_hue_scene_add.xml
new file mode 100644
index 0000000..1fdc8cd
--- /dev/null
+++ b/app/src/main/res/drawable/ic_hue_scene_add.xml
@@ -0,0 +1,51 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_hue_scene_base.xml b/app/src/main/res/drawable/ic_hue_scene_base.xml
new file mode 100644
index 0000000..d3e04ff
--- /dev/null
+++ b/app/src/main/res/drawable/ic_hue_scene_base.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_hue_scene_color.xml b/app/src/main/res/drawable/ic_hue_scene_color.xml
new file mode 100644
index 0000000..e32641e
--- /dev/null
+++ b/app/src/main/res/drawable/ic_hue_scene_color.xml
@@ -0,0 +1,5 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_info.xml b/app/src/main/res/drawable/ic_info.xml
new file mode 100644
index 0000000..a302ace
--- /dev/null
+++ b/app/src/main/res/drawable/ic_info.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..4aa8af3
--- /dev/null
+++ b/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 0000000..0e95347
--- /dev/null
+++ b/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_nav_open_in_new.xml b/app/src/main/res/drawable/ic_nav_open_in_new.xml
new file mode 100644
index 0000000..c4471ad
--- /dev/null
+++ b/app/src/main/res/drawable/ic_nav_open_in_new.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_room.xml b/app/src/main/res/drawable/ic_room.xml
new file mode 100644
index 0000000..d8b5276
--- /dev/null
+++ b/app/src/main/res/drawable/ic_room.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_scene.xml b/app/src/main/res/drawable/ic_scene.xml
new file mode 100644
index 0000000..71b7807
--- /dev/null
+++ b/app/src/main/res/drawable/ic_scene.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_scene_white.xml b/app/src/main/res/drawable/ic_scene_white.xml
new file mode 100644
index 0000000..64ba025
--- /dev/null
+++ b/app/src/main/res/drawable/ic_scene_white.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_search.xml b/app/src/main/res/drawable/ic_search.xml
new file mode 100644
index 0000000..1eacb08
--- /dev/null
+++ b/app/src/main/res/drawable/ic_search.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_settings.xml b/app/src/main/res/drawable/ic_settings.xml
new file mode 100644
index 0000000..3c11c0c
--- /dev/null
+++ b/app/src/main/res/drawable/ic_settings.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/app/src/main/res/drawable/ic_warning.xml b/app/src/main/res/drawable/ic_warning.xml
new file mode 100644
index 0000000..144e8ba
--- /dev/null
+++ b/app/src/main/res/drawable/ic_warning.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/app/src/main/res/drawable/ic_zone.xml b/app/src/main/res/drawable/ic_zone.xml
new file mode 100644
index 0000000..7aa85ad
--- /dev/null
+++ b/app/src/main/res/drawable/ic_zone.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout-land/activity_hue_lamp.xml b/app/src/main/res/layout-land/activity_hue_lamp.xml
new file mode 100644
index 0000000..50923e8
--- /dev/null
+++ b/app/src/main/res/layout-land/activity_hue_lamp.xml
@@ -0,0 +1,68 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_devices.xml b/app/src/main/res/layout/activity_devices.xml
new file mode 100644
index 0000000..678b206
--- /dev/null
+++ b/app/src/main/res/layout/activity_devices.xml
@@ -0,0 +1,5 @@
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_edit_device.xml b/app/src/main/res/layout/activity_edit_device.xml
new file mode 100644
index 0000000..fedb122
--- /dev/null
+++ b/app/src/main/res/layout/activity_edit_device.xml
@@ -0,0 +1,285 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_hue_connect.xml b/app/src/main/res/layout/activity_hue_connect.xml
new file mode 100644
index 0000000..4e57326
--- /dev/null
+++ b/app/src/main/res/layout/activity_hue_connect.xml
@@ -0,0 +1,41 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_hue_lamp.xml b/app/src/main/res/layout/activity_hue_lamp.xml
new file mode 100644
index 0000000..ad2c710
--- /dev/null
+++ b/app/src/main/res/layout/activity_hue_lamp.xml
@@ -0,0 +1,61 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_hue_scene.xml b/app/src/main/res/layout/activity_hue_scene.xml
new file mode 100644
index 0000000..c416ec2
--- /dev/null
+++ b/app/src/main/res/layout/activity_hue_scene.xml
@@ -0,0 +1,110 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..363e279
--- /dev/null
+++ b/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,86 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
new file mode 100644
index 0000000..13326d5
--- /dev/null
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -0,0 +1,6 @@
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_web.xml b/app/src/main/res/layout/activity_web.xml
new file mode 100644
index 0000000..7df4a1f
--- /dev/null
+++ b/app/src/main/res/layout/activity_web.xml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/dialog_input.xml b/app/src/main/res/layout/dialog_input.xml
new file mode 100644
index 0000000..2999608
--- /dev/null
+++ b/app/src/main/res/layout/dialog_input.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/dialog_tasmota_add.xml b/app/src/main/res/layout/dialog_tasmota_add.xml
new file mode 100644
index 0000000..1d04864
--- /dev/null
+++ b/app/src/main/res/layout/dialog_tasmota_add.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/dialog_tasmota_execute_once.xml b/app/src/main/res/layout/dialog_tasmota_execute_once.xml
new file mode 100644
index 0000000..2f4bfa4
--- /dev/null
+++ b/app/src/main/res/layout/dialog_tasmota_execute_once.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/dialog_web_authentication.xml b/app/src/main/res/layout/dialog_web_authentication.xml
new file mode 100644
index 0000000..19c8488
--- /dev/null
+++ b/app/src/main/res/layout/dialog_web_authentication.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/dropdown_item.xml b/app/src/main/res/layout/dropdown_item.xml
new file mode 100644
index 0000000..324a1d0
--- /dev/null
+++ b/app/src/main/res/layout/dropdown_item.xml
@@ -0,0 +1,9 @@
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_control_info.xml b/app/src/main/res/layout/fragment_control_info.xml
new file mode 100644
index 0000000..dc42733
--- /dev/null
+++ b/app/src/main/res/layout/fragment_control_info.xml
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_hue_bri_color.xml b/app/src/main/res/layout/fragment_hue_bri_color.xml
new file mode 100644
index 0000000..ae4a503
--- /dev/null
+++ b/app/src/main/res/layout/fragment_hue_bri_color.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_hue_color.xml b/app/src/main/res/layout/fragment_hue_color.xml
new file mode 100644
index 0000000..97bee4f
--- /dev/null
+++ b/app/src/main/res/layout/fragment_hue_color.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_hue_lamps.xml b/app/src/main/res/layout/fragment_hue_lamps.xml
new file mode 100644
index 0000000..42abb8a
--- /dev/null
+++ b/app/src/main/res/layout/fragment_hue_lamps.xml
@@ -0,0 +1,8 @@
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/fragment_hue_scenes.xml b/app/src/main/res/layout/fragment_hue_scenes.xml
new file mode 100644
index 0000000..1b78125
--- /dev/null
+++ b/app/src/main/res/layout/fragment_hue_scenes.xml
@@ -0,0 +1,7 @@
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/grid_item.xml b/app/src/main/res/layout/grid_item.xml
new file mode 100644
index 0000000..8e28d2a
--- /dev/null
+++ b/app/src/main/res/layout/grid_item.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/hue_color_controls.xml b/app/src/main/res/layout/hue_color_controls.xml
new file mode 100644
index 0000000..f5e6e10
--- /dev/null
+++ b/app/src/main/res/layout/hue_color_controls.xml
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/hue_controls.xml b/app/src/main/res/layout/hue_controls.xml
new file mode 100644
index 0000000..760e781
--- /dev/null
+++ b/app/src/main/res/layout/hue_controls.xml
@@ -0,0 +1,84 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/icon_dropdown_item.xml b/app/src/main/res/layout/icon_dropdown_item.xml
new file mode 100644
index 0000000..b3f2518
--- /dev/null
+++ b/app/src/main/res/layout/icon_dropdown_item.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/list_item.xml b/app/src/main/res/layout/list_item.xml
new file mode 100644
index 0000000..412be5a
--- /dev/null
+++ b/app/src/main/res/layout/list_item.xml
@@ -0,0 +1,60 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/list_item_device_discovery.xml b/app/src/main/res/layout/list_item_device_discovery.xml
new file mode 100644
index 0000000..7daee83
--- /dev/null
+++ b/app/src/main/res/layout/list_item_device_discovery.xml
@@ -0,0 +1,60 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/list_item_devices.xml b/app/src/main/res/layout/list_item_devices.xml
new file mode 100644
index 0000000..020b094
--- /dev/null
+++ b/app/src/main/res/layout/list_item_devices.xml
@@ -0,0 +1,59 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/list_item_simple.xml b/app/src/main/res/layout/list_item_simple.xml
new file mode 100644
index 0000000..d57a1ba
--- /dev/null
+++ b/app/src/main/res/layout/list_item_simple.xml
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/menu/activity_hue_lamp_actions.xml b/app/src/main/res/menu/activity_hue_lamp_actions.xml
new file mode 100644
index 0000000..cc2c872
--- /dev/null
+++ b/app/src/main/res/menu/activity_hue_lamp_actions.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/menu/activity_hue_lamp_context.xml b/app/src/main/res/menu/activity_hue_lamp_context.xml
new file mode 100644
index 0000000..fce7d12
--- /dev/null
+++ b/app/src/main/res/menu/activity_hue_lamp_context.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/menu/activity_main_tasmota_context.xml b/app/src/main/res/menu/activity_main_tasmota_context.xml
new file mode 100644
index 0000000..fce7d12
--- /dev/null
+++ b/app/src/main/res/menu/activity_main_tasmota_context.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/menu/activity_web_actions.xml b/app/src/main/res/menu/activity_web_actions.xml
new file mode 100644
index 0000000..97c6618
--- /dev/null
+++ b/app/src/main/res/menu/activity_web_actions.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/menu/top_app_bar.xml b/app/src/main/res/menu/top_app_bar.xml
new file mode 100644
index 0000000..aba7ad6
--- /dev/null
+++ b/app/src/main/res/menu/top_app_bar.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..50ec886
--- /dev/null
+++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp
new file mode 100644
index 0000000..55f7323
Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp
new file mode 100644
index 0000000..f7577f5
Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
new file mode 100644
index 0000000..e02184b
Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
new file mode 100644
index 0000000..78eb489
Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
new file mode 100644
index 0000000..c4c36c5
Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
new file mode 100644
index 0000000..aabc5ba
--- /dev/null
+++ b/app/src/main/res/values-de/strings.xml
@@ -0,0 +1,182 @@
+
+ Home
+ Eine kleine Smart-Home-App für Philips Hue, Arduino und andere Geräte
+
+ Keine Geräte gefunden
+ Füge ein Gerät in den Einstellungen hinzu
+ Diese Gerät existiert nicht
+ Tippe zum Verbinden
+ Verbinde
+ Unsichere Verbindung
+ Das Gerät benutzt einen unbekannten Modus
+ Das Gerät ist momentan nicht verfügbar
+ Die Antwort erfüllt nicht die Voraussetzungen
+ Das Gerät hat nicht geantwortet
+ Erfolgreich ausgeführt
+
+ Gerätesymbol
+ Deine Geräte
+
+ Etwas ist schiefgegangen
+ Falsches Format
+ Geben Sie bitte einen Namen ein
+ Ein Name ist wichtig, damit sie Den Eintrag später wiedererkennen können
+ Geben Sie bitte eine Adresse ein
+ Eine Adresse ist wichtig, damit die App das Gerät erreichen kann
+
+ Verbinde dich mit deiner Bridge
+ Bitte drücke den Knopf auf deiner Bridge um fortzufahren.
+ Tippe um Auszuwählen
+ Helligkeit
+ Farbtemperatur
+ Farbton und Sättigung
+ Szene
+ Szene hinzufügen
+ Neue Szene
+ Sind Sie sich sicher, dass Sie diese Szene löschen möchten?
+ Brücke
+ Brückenname
+ Brückenmodell
+ Brücken-ID
+ Softwareversion
+ Zigbee-Kanal
+ Zeitzone
+ Steuerungen
+ Lampen
+ Hue Raum
+ Hue Szene
+
+ Noch keine Befehle hinzugefügt
+ Fügen Sie Befehle unten hinzu
+ Befehl hinzufügen
+ Fügt einen neuen Befehl zur Liste hinzu
+ Titel
+ Befehl
+ Sind Sie sich sicher, dass Sie diesen Eintrag löschen möchten?
+ Befehl ausführen
+ Führt einen Befehl ein Mal aus ohne ihn der Liste hinzuzufügen
+
+ Aktuelle Luftfeuchtigkeit
+ Aktueller Stromverbrauch
+ Stromstärke
+ Spannung
+ Energie
+ Zurückgeführte Energie
+ Schalter %1$d
+ Aktuelle Temperatur
+ W-Lan
+ MQTT
+ Cloud
+ Betriebszeit
+ Verwendeter Speicher
+ Verwendeter RAM
+ Updates verfügbar
+
+ Geben Sie etwas ein
+ Eingabe
+ Der Schalter ist an
+ Der Schalter ist aus
+
+ Internetansicht
+ Im Browser öffnen
+ Laden der Webseite fehlgeschlagen
+ Bitte überprüfen Sie Ihre Verbindung oder versuchen Sie es später erneut
+ Authentifizierung
+ Kein vertrauenswürdiges Zertifikat
+
+ Einstellungen
+ Generelle Einstellungen
+ Spaltenanzahl
+ Ändert die Anzahl der Spalten der Hauptliste
+ Geräte
+ Geräteliste bearbeiten
+ Bearbeiten Sie Ihre Geräteliste
+ Sind Sie sich sicher, dass Sie dieses Gerät löschen möchten?
+ Gerätekonfiguration
+ Zum Startbildschirm hinzufügen
+ Shortcuts werden von Ihrem System nicht unterstützt
+ Ein neues Gerät hinzufügen
+ Ein neues Gerät mit seiner Adresse hinzufügen
+ Methode auswählen
+ Neues Gerät
+ Interne ID: %1$s
+ Name
+ z.B. Gerät
+ Gerät
+ Adresse
+ z.B. http://127.0.0.1/
+ Symbol
+ Modus
+ Suche nach kompatiblen Geräten
+ Dies kann einige Sekunden dauern
+ Gerär hinzufügen
+ Wollen Sie “%1$s” zu Ihren Geräten hinzufügen?
+ Erweitertes Bearbeiten
+ Bearbeiten Sie die JSON-Zeichenfolge selbst
+ Entsperren des Geräts für Steuerelemente erfordern
+ Erfordern, dass das Gerät für die Steuerung über das Power-Menü entsperrt wird
+ Erweiterte Einstellungen
+ Alle Geräte löschen
+ Löscht alle Geräte
+ Sind Sie sich sicher, dass Sie alle Geräte löschen möchten? Dies kann nicht rückgängig gemacht werden!
+ Alle Geräte gelöscht
+ Potenziell unsichere Anfragen blockieren
+ Sicherheitsüberprüfungen durchführen\nWarnung: Bei Deaktivierung können Angreifer Verbindungsdaten abgreifen!
+ Informationen
+ Wiki
+ Dokumentation und Hilfe
+ Hintergrund des Kopfbereiches
+ Hintergrund des Kopfbereiches von Alberto Castillo Q. auf Unsplash
+ Router
+ Lädt
+
+ Benutzername
+ Passwort
+
+ Gerät mit Hauptliste laden
+ Gerät aus Hauptliste ausblenden
+ ausgeblendet
+ Geräteinfo
+ Status
+
+ Abbrechen
+ Bearbeiten
+ Löschen
+ Anzeigen
+ Fertig
+ Hinzufügen
+ Senden
+ An
+ Aus
+ Ja
+ Nein
+ Nicht erreichbar
+
+ Über
+ Über die App
+ App-Version
+ Externe Inhalte
+ Externe Inhalte werden von GitHub geladen. Lesen Sie deren Datenschutzrichtlinie für weitere Informationen.
+ Datenschutz-Bestimmungen
+ Mitwirkende
+ Eine Liste der Mitwirkenden
+ Allgemein
+ GitHub-Repository
+ Lizenz
+ Icons
+ Icons von Icons8 und Google
+ Bibliotheken
+ Eine Liste aller verwendeten Bibliotheken
+
+
+ - Auto
+ - Eins
+ - Zwei
+ - Drei
+ - Vier
+
+
+ - Gerät mit Adresse hinzufügen
+ - Nach kompatiblen Geräten suchen (experimentell)
+
+
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
new file mode 100644
index 0000000..205423c
--- /dev/null
+++ b/app/src/main/res/values-es/strings.xml
@@ -0,0 +1,80 @@
+
+ Home
+
+ Sin dispositivos encontrados
+ Añade un nuevo dispositivo en los ajustes
+ El dispositivo no existe en su lista
+ Toque para conectar
+ Conectando
+ El dispositivo utiliza un modo desconocido
+ El dispositivo no está disponible actualmente
+ La respuesta no cumple los requisitos
+ El dispositivo no respondió
+ Ejecución completada con éxito
+
+ Icono del dispositivos
+ Tus dispositivos
+
+ Algo salió mal
+ Formato incorrecto
+ Por favor, introduzca un nombre
+ Un nombre es importante para reconocer la entrada más tarde
+ Por favor, introduzca una dirección
+ Una dirección es importante para que la aplicación llegue al dispositivo
+
+ Conecta tu puente
+ Por favor, pulse el botón de su puente para continuar.
+ Toque para seleccionar
+ Brillo
+ Temperatura de color
+ Tono y saturación
+ Añadir escenario
+ Nuevo escenario
+ ¿Estás seguro de que quieres borrar esta escena?
+
+ Web View
+ La carga de la página web falló
+ Por favor, compruebe su conexión a la red o inténtelo de nuevo más tarde
+
+ Ajustes
+ Ajustes generales
+ Dispositivos
+ Editar lista de dispositivos
+ Editar la lista de dispositivos
+ ¿Estás seguro de que quieres borrar este dispositivo?
+ Añadir a la pantalla de inicio
+ Los atajos no están soportados por el sistema
+ Añadir nuevo dispositivo
+ Añade un nuevo dispositivo con su dirección
+ Seleccionar método
+ Nuevo dispositivo
+ Identificación interna: %1$s
+ Nombre
+ Dispositivo
+ Dispositivo
+ Dirección
+ http://127.0.0.1/
+ Icono
+ Modo
+ Edición avanzada
+ Edita la cadena JSON por tu cuenta
+ Información
+ Wiki
+ Fondo de cabecera
+ Fondo de cabecera por Alberto Castillo Q. en Unsplash
+ Router
+ Cargando
+
+ Cancelar
+ Borrar
+ Encendido
+ Apagado
+
+ Acerca de
+ Sobre la aplicación
+
+
+ - Añadir dispositivo por dirección
+ - Búsqueda de dispositivos compatibles (experimental)
+
+
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
new file mode 100644
index 0000000..eb7702f
--- /dev/null
+++ b/app/src/main/res/values-nl/strings.xml
@@ -0,0 +1,80 @@
+
+ Huis
+
+ Geen apparaten aangetroffen
+ Ga naar de instellingen en voeg een apparaat toe
+ Dit apparaat staat niet op je lijst
+ Druk hier om te verbinden
+ Bezig met verbinden…
+ Het apparaat maakt gebruik van een onbekende modus
+ Het apparaat is momenteel niet beschikbaar
+ De terugkoppeling voldoet niet aan de vereisten
+ Het apparaat stuurde geen terugkoppeling
+ Uitvoeren voltooid
+
+ Apparaatpictogram
+ Mijn apparaten
+
+ Er is iets misgegaan
+ Onbekend formaat
+ Voer een naam in
+ Voer een naam in om het apparaat makkelijk te herkennen
+ Voer een adres in
+ Voer een adres in zodat de app verbinding kan maken met het apparaat
+
+ Koppel je Bridge
+ Druk op de knop op je bridge om door te gaan.
+ Druk hier om te kiezen
+ Helderheid
+ Kleurtemperatuur
+ Tint and verzadiging
+ Scène toevoegen
+ Nieuwe scène
+ Weet je zeker dat je deze scène wilt verwijderen?
+
+ Webweergave
+ De website kan niet worden geladen
+ Controleer je internetverbinding of probeer het later opnieuw
+
+ Instellingen
+ Algemeen
+ Apparaten
+ Apparaatlijst bewerken
+ Bewerk de lijst met apparaten
+ Weet je zeker dat je dit apparaat wilt verwijderen?
+ Toevoegen aan startscherm
+ Je systeem heeft geen ondersteuning voor snelkoppelingen
+ Apparaat toevoegen
+ Voeg een apparaat (met bijbehorend adres) toe
+ Methode kiezen
+ Nieuw apparaat
+ Interne id: %1$s
+ Naam
+ Apparaat
+ Apparaat
+ Adres
+ http://127.0.0.1/
+ Pictogram
+ Modus
+ Expertmodus
+ Pas de json-tekenreeks handmatig aan
+ Informatie
+ Wiki
+ Kopachtergrond
+ De kopachtergrond is gemaakt door Alberto Castillo Q. van Unsplash
+ Router
+ Bezig met laden
+
+ Annuleren
+ Verwijderen
+ Aan
+ Uit
+
+ Over
+ Over de app
+
+
+ - Apparaat toevoegen middels adres
+ - Zoeken naar compatibele apparaten (experimenteel)
+
+
diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml
new file mode 100644
index 0000000..cf27f01
--- /dev/null
+++ b/app/src/main/res/values/dimens.xml
@@ -0,0 +1,12 @@
+
+ 16dp
+ 16dp
+ 32dp
+ 8dp
+
+ 48dp
+
+ 96dp
+
+ 8dp
+
\ No newline at end of file
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..cd95656
--- /dev/null
+++ b/app/src/main/res/values/strings.xml
@@ -0,0 +1,251 @@
+
+ Home
+ A little smart home app for Philips Hue, Arduino and other devices
+
+ No devices found
+ Add a new device in the settings
+ The device does not exist in your list
+ Tap to connect
+ Connecting
+ Connection not secure
+ The device uses an unknown mode
+ The device is currently unavailable
+ The response does not meet the requirements
+ The device did not answer
+ Execution completed successfully
+
+ Device Icon
+ Your Devices
+
+ Something went wrong
+ Wrong format
+ Please enter a name
+ A name is important so that you can recognize the entry later
+ Please enter an address
+ An address is important because it allows the app to reach the device
+
+ Connect to your Bridge
+ Please press the button on your bridge to continue.
+ Tap to select
+ Brightness
+ Color temperature
+ Hue and saturation
+ Scene
+ Add Scene
+ New Scene
+ Are you sure you want to delete this scene?
+ Bridge
+ Bridge Name
+ Bridge Model
+ Bridge ID
+ Software Version
+ Zigbee Channel
+ Time Zone
+ Controls
+ Lights
+ Hue Room
+ Hue Scene
+
+ Tasmota
+ No commands added yet
+ Add commands below
+ Add command to list
+ Add a new command to your list
+ Title
+ cm\?cmnd=Power%20On
+ Command
+ cm\?
+ Are you sure you want to delete this entry?
+ Execute command
+ Execute command once without adding it to the list
+
+ Current humidity
+ Current power consumption
+ Current
+ Voltage
+ Energy
+ Returned energy
+ Switch %1$d
+ Current temperature
+ WiFi
+ MQTT
+ Cloud
+ Uptime
+ Storage Used
+ RAM Used
+ Updates Available
+
+ Please enter something
+ Input
+ The switch is on
+ The switch is off
+
+ Web View
+ Open in browser
+ Loading the website failed
+ Please check your network connection or try again later
+ Authentication
+ Untrusted certificate
+
+ Settings
+ General Settings
+ Column count
+ Changes the number of columns of the main list
+ Devices
+ Edit device list
+ Edit the list of devices
+ Are you sure you want to delete this device?
+ Device Configuration
+ Add to Home screen
+ Shortcuts are not supported by your system
+ Add a new device
+ Add a new device with its address
+ Select Method
+ New Device
+ Internal ID: %1$s
+ Name
+ e.g., Device
+ Device
+ Address
+ e.g., http://127.0.0.1/
+ Icon
+ Mode
+ Searching for compatible devices
+ This might take a couple of seconds
+ Add Device
+ Do you want to add “%1$s” to your devices?
+ Advanced editing
+ Edit the JSON string by yourself
+ Require device unlock for controls
+ Require the device to be unlocked for power menu controls
+ Advanced Settings
+ Delete all devices
+ This deletes all your devices
+ Are you sure you want to delete all of your devices? This cannot be undone!
+ Deleted all devices
+ Block potentially unsafe requests
+ Perform basic security checks\nWarning: Turning this off can leak connection data to attackers!
+ Information
+ Wiki
+ Documentation and help
+ Header background
+ Header background by Alberto Castillo Q. on Unsplash
+ Router
+ Loading
+
+ Username
+ Password
+
+ Load device with main list
+ Hide device from main list
+ hidden
+ Device Info
+ Status
+
+ Cancel
+ Edit
+ Delete
+ Show
+ Done
+ Add
+ Send
+ On
+ Off
+ Yes
+ No
+ Unreachable
+
+ About
+ About the app
+ App version
+ %1$s (%2$d)
+ External Content
+ External content will be loaded from GitHub. Read their privacy policy for further information.
+ Privacy Policy
+ Contributors
+ A list of the contributors
+ General
+ GitHub repository
+ License
+ GPL-3.0
+ Icons
+ Icons by Icons8 and Google
+ Libraries
+ A list of all used libraries
+
+
+ - Auto
+ - One
+ - Two
+ - Three
+ - Four
+
+
+ - auto
+ - 1
+ - 2
+ - 3
+ - 4
+
+
+ - Add device by address
+ - Search for compatible devices (experimental)
+
+
+ - Clock
+ - Display
+ - Display Alt
+ - Docker
+ - Electricity
+ - Gauge
+ - Grafana
+ - Hygrometer
+ - Lamp
+ - Raspberry Pi
+ - Raspberry Pi Alt
+ - Router
+ - Socket
+ - Speaker
+ - Stack
+ - Thermometer
+ - Webcam
+
+
+ - SimpleHome API
+ - ESP Easy
+ - Fritz! Auto-Login
+ - Grafana Auto-Login
+ - Hue API
+ - Node-RED
+ - Pi-hole Auto-Login
+ - Shelly Gen 1
+ - Shelly Gen 2
+ - Shelly Gen 3
+ - Tasmota
+ - Website
+
+
+ - Icons8
+ - Google
+
+
+ - Android Preferences KTX
+ - AndroidX Security Kotlin Extensions
+ - Annotation
+ - AppCompat
+ - ColorPickerView
+ - Material Components For Android
+ - UPnPDiscovery
+ - Volley
+
+
+ - Apache 2.0
+ - Apache 2.0
+ - Apache 2.0
+ - Apache 2.0
+ - Apache 2.0
+ - Apache 2.0
+ - Apache 2.0
+ - Apache 2.0
+
+
diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..306bcca
--- /dev/null
+++ b/app/src/main/res/values/styles.xml
@@ -0,0 +1,7 @@
+
+
+
+
diff --git a/app/src/main/res/xml/backup_descriptor.xml b/app/src/main/res/xml/backup_descriptor.xml
new file mode 100644
index 0000000..294ae2c
--- /dev/null
+++ b/app/src/main/res/xml/backup_descriptor.xml
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 0000000..68c5432
--- /dev/null
+++ b/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/xml/pref_about.xml b/app/src/main/res/xml/pref_about.xml
new file mode 100644
index 0000000..83267d6
--- /dev/null
+++ b/app/src/main/res/xml/pref_about.xml
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/xml/pref_about_list.xml b/app/src/main/res/xml/pref_about_list.xml
new file mode 100644
index 0000000..d94dfad
--- /dev/null
+++ b/app/src/main/res/xml/pref_about_list.xml
@@ -0,0 +1,5 @@
+
+
+
diff --git a/app/src/main/res/xml/pref_general.xml b/app/src/main/res/xml/pref_general.xml
new file mode 100644
index 0000000..aba4c1f
--- /dev/null
+++ b/app/src/main/res/xml/pref_general.xml
@@ -0,0 +1,76 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/test/java/io/github/domi04151309/home/EspEasyAPIParserTest.kt b/app/src/test/java/io/github/domi04151309/home/EspEasyAPIParserTest.kt
new file mode 100644
index 0000000..6b3fe3a
--- /dev/null
+++ b/app/src/test/java/io/github/domi04151309/home/EspEasyAPIParserTest.kt
@@ -0,0 +1,111 @@
+package io.github.domi04151309.home
+
+import android.content.res.Resources
+import io.github.domi04151309.home.api.EspEasyAPIParser
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.json.JSONObject
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+class EspEasyAPIParserTest {
+ private val resources: Resources = RuntimeEnvironment.getApplication().applicationContext.resources
+ private val parser = EspEasyAPIParser(resources, null)
+
+ @Test
+ fun parseInfo1() {
+ val infoJson = JSONObject(Helpers.getFileContents("/espeasy/espeasy-1.json"))
+
+ val listItems = parser.parseResponse(infoJson)
+ assertThat(listItems.size, `is`(4))
+
+ // sensor 1: Temperature + Humidity
+ var num = 0
+ assertThat(listItems[num].title, `is`("24.7 °C"))
+ assertThat(listItems[num].summary, `is`("DHT: Temperatur"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_thermometer))
+
+ num++
+ assertThat(listItems[num].title, `is`("39.5 %"))
+ assertThat(listItems[num].summary, `is`("DHT: Feuchte"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_hygrometer))
+
+ // sensor 2: Temperature only
+ num++
+ assertThat(listItems[num].title, `is`("0 °C"))
+ assertThat(listItems[num].summary, `is`("DS: Temperatur"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_thermometer))
+
+ // sensor 3: Switch in off mode
+ num++
+ assertThat(listItems[num].title, `is`("Relais"))
+ assertThat(listItems[num].summary, `is`(resources.getString(R.string.switch_summary_off)))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("12"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+ }
+
+ @Test
+ fun parseInfoDisabledTasks() {
+ val infoJson = JSONObject(Helpers.getFileContents("/espeasy/espeasy-disabledtasks.json"))
+
+ val listItems = parser.parseResponse(infoJson)
+ assertThat(listItems.size, `is`(0))
+ }
+
+ @Test
+ fun parseInfoHideNanSensorValues() {
+ val infoJson = JSONObject(Helpers.getFileContents("/espeasy/espeasy-nan.json"))
+
+ val listItems = parser.parseResponse(infoJson)
+
+ assertThat(listItems.size, `is`(1))
+
+ // first sensor value is humidity since temperature returns a "NaN" that we hidd
+ val num = 0
+ assertThat(listItems[num].title, `is`("39.5 %"))
+ assertThat(listItems[num].summary, `is`("DHT: Feuchte"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_hygrometer))
+ }
+
+ @Test
+ fun parseInfoPressure() {
+ val infoJson = JSONObject(Helpers.getFileContents("/espeasy/espeasy-pressure.json"))
+
+ val listItems = parser.parseResponse(infoJson)
+
+ assertThat(listItems.size, `is`(3))
+ // sensor 1: Temperature + Humidity + Pressure
+ var num = 0
+ assertThat(listItems[num].title, `is`("30 °C"))
+ assertThat(listItems[num].summary, `is`("BMP_HWR: Temp_BMP"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_thermometer))
+
+ num++
+ assertThat(listItems[num].title, `is`("0 %"))
+ assertThat(listItems[num].summary, `is`("BMP_HWR: Feuchte_BMP"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_hygrometer))
+
+ num++
+ assertThat(listItems[num].title, `is`("1004 hPa"))
+ assertThat(listItems[num].summary, `is`("BMP_HWR: Druck_BMP"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_gauge))
+ }
+}
diff --git a/app/src/test/java/io/github/domi04151309/home/Helpers.kt b/app/src/test/java/io/github/domi04151309/home/Helpers.kt
new file mode 100644
index 0000000..4b049a9
--- /dev/null
+++ b/app/src/test/java/io/github/domi04151309/home/Helpers.kt
@@ -0,0 +1,8 @@
+package io.github.domi04151309.home
+
+object Helpers {
+ fun getFileContents(path: String): String =
+ javaClass.getResource(path)
+ ?.readText()
+ ?: error("Cannot get file contents.")
+}
diff --git a/app/src/test/java/io/github/domi04151309/home/HueAPIParserTest.kt b/app/src/test/java/io/github/domi04151309/home/HueAPIParserTest.kt
new file mode 100644
index 0000000..6503477
--- /dev/null
+++ b/app/src/test/java/io/github/domi04151309/home/HueAPIParserTest.kt
@@ -0,0 +1,96 @@
+package io.github.domi04151309.home
+
+import android.content.res.Resources
+import io.github.domi04151309.home.api.HueAPIParser
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.json.JSONObject
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+class HueAPIParserTest {
+ private val resources: Resources = RuntimeEnvironment.getApplication().applicationContext.resources
+ private val parser = HueAPIParser(resources)
+
+ @Test
+ fun parseListItems_docs() {
+ val groupsJson = JSONObject(Helpers.getFileContents("/hue/docs-groups.json"))
+
+ val listItems = parser.parseResponse(groupsJson)
+ assertThat(listItems.size, `is`(0))
+ }
+
+ @Test
+ fun parseListItems_home() {
+ val groupsJson = JSONObject(Helpers.getFileContents("/hue/home-groups.json"))
+
+ val listItems = parser.parseResponse(groupsJson)
+ assertThat(listItems.size, `is`(9))
+
+ var num = 0
+ assertThat(listItems[num].title, `is`("Bedroom"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("1"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_room))
+
+ num = 1
+ assertThat(listItems[num].title, `is`("Hallway"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("5"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_room))
+
+ num = 2
+ assertThat(listItems[num].title, `is`("Kitchen"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("7"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_room))
+
+ num = 3
+ assertThat(listItems[num].title, `is`("Living Room"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("2"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_room))
+
+ num = 4
+ assertThat(listItems[num].title, `is`("Office"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("6"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_room))
+
+ num = 5
+ assertThat(listItems[num].title, `is`("Unused"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("8"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_room))
+
+ num = 6
+ assertThat(listItems[num].title, `is`("Kitchen Cabinets"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("9"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_zone))
+
+ num = 7
+ assertThat(listItems[num].title, `is`("Kitchen Ceiling"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("3"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_zone))
+
+ num = 8
+ assertThat(listItems[num].title, `is`("Living Room Ambient"))
+ assertThat(listItems[num].summary, `is`("Brightness: 0 %"))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("4"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_zone))
+ }
+}
diff --git a/app/src/test/java/io/github/domi04151309/home/ShellyAPIParserTest.kt b/app/src/test/java/io/github/domi04151309/home/ShellyAPIParserTest.kt
new file mode 100644
index 0000000..990791d
--- /dev/null
+++ b/app/src/test/java/io/github/domi04151309/home/ShellyAPIParserTest.kt
@@ -0,0 +1,189 @@
+package io.github.domi04151309.home
+
+import android.content.res.Resources
+import io.github.domi04151309.home.api.ShellyAPIParser
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.json.JSONObject
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+@Suppress("FunctionMaxLength")
+class ShellyAPIParserTest {
+ private val resources: Resources = RuntimeEnvironment.getApplication().applicationContext.resources
+ private val parserV1 = ShellyAPIParser(resources, 1)
+ private val parserV2 = ShellyAPIParser(resources, 2)
+
+ @Test
+ fun parseListItemsJsonV1_shellyPlug1WithPowerMeter() {
+ val settingsJson = JSONObject(Helpers.getFileContents("/shelly/shellyplug1-settings.json"))
+ val statusJson = JSONObject(Helpers.getFileContents("/shelly/shellyplug1-status.json"))
+
+ val listItems = parserV1.parseResponse(settingsJson, statusJson)
+ assertThat(listItems.size, `is`(2))
+
+ var num = 0
+ assertThat(listItems[num].title, `is`("Wohnzimmer Gartenfenster"))
+ assertThat(listItems[num].summary, `is`(resources.getString(R.string.switch_summary_on)))
+ assertThat(listItems[num].state, `is`(true))
+ assertThat(listItems[num].hidden, `is`("0"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+
+ num = 1
+ assertThat(listItems[num].title, `is`("27.95 W"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_powermeter_summary)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_electricity))
+ }
+
+ @Test
+ fun parseListItemsJsonV1_shellyPlug1ApplianceTypesForIcons() {
+ val settingsJson = JSONObject(Helpers.getFileContents("/shelly/shellyplug1-icons-settings.json"))
+ val statusJson = JSONObject(Helpers.getFileContents("/shelly/shellyplug1-icons-status.json"))
+
+ val listItems = parserV1.parseResponse(settingsJson, statusJson)
+ assertThat(listItems.size, `is`(6))
+
+ var num = 0
+ assertThat(listItems[num].title, `is`("Deckenlampe"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_lamp))
+
+ num = 1
+ assertThat(listItems[num].title, `is`("Steckdose"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_socket))
+
+ num = 2
+ assertThat(listItems[num].title, `is`("Radiator"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_thermometer))
+
+ num = 3
+ assertThat(listItems[num].title, `is`("Stereoanlage"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_speaker))
+
+ num = 4
+ assertThat(listItems[num].title, `is`("Tannenbaum (en)"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_christmas_tree))
+
+ num = 5
+ assertThat(listItems[num].title, `is`("Schwibbogen"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_schwibbogen))
+ }
+
+ @Test
+ fun parseListItemsJsonV1_shelly1WithTemperatureNoRelayName() {
+ val settingsJson = JSONObject(Helpers.getFileContents("/shelly/shelly1-settings.json"))
+ val statusJson = JSONObject(Helpers.getFileContents("/shelly/shelly1-status.json"))
+
+ val listItems = parserV1.parseResponse(settingsJson, statusJson)
+ assertThat(listItems.size, `is`(3))
+
+ var num = 0
+ assertThat(listItems[num].title, `is`(resources.getString(R.string.shelly_switch_title, 1)))
+ assertThat(listItems[num].summary, `is`(resources.getString(R.string.switch_summary_off)))
+ assertThat(listItems[num].state, `is`(false))
+ assertThat(listItems[num].hidden, `is`("0"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+
+ num++
+ assertThat(listItems[num].title, `is`("23.0 °C"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_temperature_sensor_summary)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_thermometer))
+
+ num++
+ assertThat(listItems[num].title, `is`("52.3%"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_humidity_sensor_summary)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`(""))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_hygrometer))
+ }
+
+ @Test
+ fun parseListItemsJsonV2_shellyPlus1() {
+ val configJson = JSONObject(Helpers.getFileContents("/shelly/shelly-plus-1-Shelly.GetConfig.json"))
+ val statusJson = JSONObject(Helpers.getFileContents("/shelly/shelly-plus-1-Shelly.GetStatus.json"))
+
+ val listItems = parserV2.parseResponse(configJson, statusJson)
+ assertThat(listItems.size, `is`(1))
+
+ val num = 0
+ assertThat(listItems[num].title, `is`("Kamin"))
+ assertThat(listItems[num].summary, `is`(resources.getString(R.string.switch_summary_on)))
+ assertThat(listItems[num].state, `is`(true))
+ assertThat(listItems[num].hidden, `is`("0"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_lamp))
+ }
+
+ @Test
+ fun parseListItemsJsonV2_shellyMiniPMG3() {
+ val configJson = JSONObject(Helpers.getFileContents("/shelly/shelly-MiniPMG3-Shelly.GetConfig.json"))
+ val statusJson = JSONObject(Helpers.getFileContents("/shelly/shelly-MiniPMG3-Shelly.GetStatus.json"))
+
+ val listItems = parserV2.parseResponse(configJson, statusJson)
+ assertThat(listItems.size, `is`(5))
+
+ var num = 0
+ assertThat(listItems[num].title, `is`("4 W"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_powermeter_summary)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("0"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_electricity))
+
+ num = 1
+ assertThat(listItems[num].title, `is`("0.033 A"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_powermeter_current)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("0c"))
+ assertThat(listItems[num].icon, `is`(0))
+
+ num = 2
+ assertThat(listItems[num].title, `is`("231.5 V"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_powermeter_voltage)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("0v"))
+ assertThat(listItems[num].icon, `is`(0))
+
+ num = 3
+ assertThat(listItems[num].title, `is`("0.002 kWh"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_powermeter_energy)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("0e"))
+ assertThat(listItems[num].icon, `is`(0))
+
+ num = 4
+ assertThat(listItems[num].title, `is`("0 kWh"))
+ assertThat(
+ listItems[num].summary,
+ `is`(resources.getString(R.string.shelly_powermeter_return_energy)),
+ )
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("0rete"))
+ assertThat(listItems[num].icon, `is`(0))
+ }
+}
diff --git a/app/src/test/java/io/github/domi04151309/home/SimpleHomeAPIParserTest.kt b/app/src/test/java/io/github/domi04151309/home/SimpleHomeAPIParserTest.kt
new file mode 100644
index 0000000..0425105
--- /dev/null
+++ b/app/src/test/java/io/github/domi04151309/home/SimpleHomeAPIParserTest.kt
@@ -0,0 +1,83 @@
+package io.github.domi04151309.home
+
+import android.content.res.Resources
+import io.github.domi04151309.home.api.SimpleHomeAPIParser
+import org.hamcrest.CoreMatchers.`is`
+import org.hamcrest.MatcherAssert.assertThat
+import org.json.JSONObject
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+@Suppress("FunctionMaxLength")
+class SimpleHomeAPIParserTest {
+ private val resources: Resources = RuntimeEnvironment.getApplication().applicationContext.resources
+ private val parser = SimpleHomeAPIParser(resources, null)
+
+ @Test
+ fun parseListItems_TemperatureSensor() {
+ val commandsJson = JSONObject(Helpers.getFileContents("/simplehome/temperature-sensor-commands.json"))
+
+ val listItems = parser.parseResponse(commandsJson)
+ assertThat(listItems.size, `is`(2))
+
+ var num = 0
+ assertThat(listItems[num].title, `is`("Temperature"))
+ assertThat(listItems[num].summary, `is`("It is currently 18.00°C in your room"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("none@temperature"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_thermometer))
+
+ num = 1
+ assertThat(listItems[num].title, `is`("Humidity"))
+ assertThat(listItems[num].summary, `is`("The humidity is 86.30 %"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("none@humidity"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_device_hygrometer))
+ }
+
+ @Test
+ fun parseListItems_TestServer() {
+ val commandsJson = JSONObject(Helpers.getFileContents("/simplehome/test-server-commands.json"))
+
+ val listItems = parser.parseResponse(commandsJson)
+ assertThat(listItems.size, `is`(5))
+
+ var num = 0
+ assertThat(listItems[num].title, `is`("Title of the command"))
+ assertThat(listItems[num].summary, `is`("Summary of the command"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("action@example"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+
+ num = 1
+ assertThat(listItems[num].title, `is`("Title of the command"))
+ assertThat(listItems[num].summary, `is`("Mode: none"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("none@example2"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+
+ num = 2
+ assertThat(listItems[num].title, `is`("Title of the command"))
+ assertThat(listItems[num].summary, `is`("Mode: input"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("input@example3"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+
+ num = 3
+ assertThat(listItems[num].title, `is`("Title of the command"))
+ assertThat(listItems[num].summary, `is`("Mode: switch"))
+ assertThat(listItems[num].state, `is`(true))
+ assertThat(listItems[num].hidden, `is`("switch@example4"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+
+ num = 4
+ assertThat(listItems[num].title, `is`("1944518792"))
+ assertThat(listItems[num].summary, `is`("523219119"))
+ assertThat(listItems[num].state, `is`(null as Boolean?))
+ assertThat(listItems[num].hidden, `is`("action@rand"))
+ assertThat(listItems[num].icon, `is`(R.drawable.ic_do))
+ }
+}
diff --git a/app/src/test/resources/espeasy/espeasy-1.json b/app/src/test/resources/espeasy/espeasy-1.json
new file mode 100644
index 0000000..a7bf315
--- /dev/null
+++ b/app/src/test/resources/espeasy/espeasy-1.json
@@ -0,0 +1,196 @@
+{
+ "System": {
+ "Load": 100,
+ "Load LC": 3,
+ "Build": 20116,
+ "Git Build": "mega-20211105_c79d675",
+ "System Libraries": "ESP82xx Core 2843a5ac, NONOS SDK 2.2.2-dev(38a443e), LWIP: 2.1.2 PUYA support",
+ "Plugin Count": 47,
+ "Plugin Description": "[Normal]",
+ "Local Time": "2021-12-10 20:10:10",
+ "Time Source": "NTP",
+ "Time Wander": 0,
+ "Use NTP": "true",
+ "Unit Number": 0,
+ "Unit Name": "ESP_Easy",
+ "Uptime": 3,
+ "Uptime (ms)": 157461,
+ "Last Boot Cause": "Cold Boot",
+ "Reset Reason": "External System",
+ "CPU Eco Mode": "false",
+ "Heap Max Free Block": 9928,
+ "Heap Fragmentation": 14,
+ "Free RAM": 11600,
+ "Free Stack": 3488,
+ "Sunrise": "5:50",
+ "Sunset": "17:57",
+ "Timezone Offset": 1,
+ "Latitude": 0,
+ "Longitude": 0
+ },
+ "WiFi": {
+ "Hostname": "ESP-Easy",
+ "IP Config": "DHCP",
+ "IP Address": "192.168.3.119",
+ "IP Subnet": "255.255.255.0",
+ "Gateway": "192.168.3.91",
+ "STA MAC": "60:01:94:01:6E:75",
+ "DNS 1": "192.168.3.3",
+ "DNS 2": "(IP unset)",
+ "SSID": "home.cweiske.de",
+ "BSSID": "5C:49:79:3B:B1:E0",
+ "Channel": 1,
+ "Encryption Type": "WPA2/PSK",
+ "Connected msec": 153000,
+ "Last Disconnect Reason": 1,
+ "Last Disconnect Reason str": "(1) Unspecified",
+ "Number Reconnects": 0,
+ "Configured SSID1": "home.cweiske.de",
+ "Configured SSID2": "Neo809B",
+ "Force WiFi B/G": "false",
+ "Restart WiFi Lost Conn": "false",
+ "Force WiFi No Sleep": "false",
+ "Periodical send Gratuitous ARP": "true",
+ "Connection Failure Threshold": 0,
+ "Max WiFi TX Power": 17.5,
+ "Current WiFi TX Power": 14,
+ "WiFi Sensitivity Margin": 3,
+ "Send With Max TX Power": "false",
+ "Extra WiFi scan loops": 0,
+ "Use Last Connected AP from RTC": "false",
+ "RSSI": -79
+ },
+ "Sensors": [
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "Temperatur",
+ "NrDecimals": 1,
+ "Value": 24.7
+ },
+ {
+ "ValueNumber": 2,
+ "Name": "Feuchte",
+ "NrDecimals": 1,
+ "Value": 39.5
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 5,
+ "Type": "Environment - DHT11/12/22 SONOFF2301/7021",
+ "TaskName": "DHT",
+ "TaskDeviceNumber": 5,
+ "TaskEnabled": "true",
+ "TaskNumber": 1
+ },
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "Temperatur",
+ "NrDecimals": 1,
+ "Value": 0
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 60,
+ "Type": "Environment - DS18b20",
+ "TaskName": "DS",
+ "TaskDeviceNumber": 4,
+ "TaskEnabled": "true",
+ "TaskNumber": 2
+ },
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "State",
+ "NrDecimals": 0,
+ "Value": 0
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 0,
+ "Type": "Switch input - Switch",
+ "TaskName": "Relais~GPIO~12",
+ "TaskDeviceNumber": 1,
+ "TaskEnabled": "true",
+ "TaskNumber": 3
+ },
+ {
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 1,
+ "Type": "Display - OLED SSD1306",
+ "TaskName": "OLED",
+ "TaskDeviceNumber": 23,
+ "TaskEnabled": "true",
+ "TaskNumber": 4
+ }
+ ],
+ "TTL": 5000
+}
diff --git a/app/src/test/resources/espeasy/espeasy-disabledtasks.json b/app/src/test/resources/espeasy/espeasy-disabledtasks.json
new file mode 100644
index 0000000..4ba2461
--- /dev/null
+++ b/app/src/test/resources/espeasy/espeasy-disabledtasks.json
@@ -0,0 +1,161 @@
+{
+ "System": {
+ "Build": 20111,
+ "Git Build": "",
+ "System Libraries": "ESP82xx Core 2843a5ac, NONOS SDK 2.2.2-dev(38a443e), LWIP: 2.1.2 PUYA support",
+ "Plugin Count": 46,
+ "Plugin Description": "[Normal]",
+ "Local Time": "2021-12-10 22:54:36",
+ "Unit Number": 242,
+ "Unit Name": "TH2",
+ "Uptime": 62,
+ "Last Boot Cause": "Manual reboot",
+ "Reset Reason": "Software/System restart",
+ "Load": 5.24,
+ "Load LC": 3473,
+ "CPU Eco Mode": "false",
+ "Heap Max Free Block": 20512,
+ "Heap Fragmentation": 10,
+ "Free RAM": 22760
+ },
+ "WiFi": {
+ "Hostname": "TH2-242",
+ "IP Config": "DHCP",
+ "IP Address": "192.168.3.113",
+ "IP Subnet": "255.255.255.0",
+ "Gateway": "192.168.3.91",
+ "STA MAC": "CC:50:E3:4F:FD:A2",
+ "DNS 1": "192.168.3.3",
+ "DNS 2": "(IP unset)",
+ "SSID": "home.cweiske.de",
+ "BSSID": "5C:49:79:3B:B1:E0",
+ "Channel": 1,
+ "Connected msec": 3713000,
+ "Last Disconnect Reason": 1,
+ "Last Disconnect Reason str": "(1) Unspecified",
+ "Number Reconnects": 0,
+ "Force WiFi B/G": "false",
+ "Restart WiFi Lost Conn": "false",
+ "Force WiFi No Sleep": "false",
+ "Connection Failure Threshold": 0,
+ "RSSI": -72
+ },
+ "nodes": [
+ {
+ "nr": 242,
+ "name": "TH2",
+ "build": 20111,
+ "platform": "ESP Easy Mega",
+ "ip": "192.168.3.113",
+ "age": 1
+ }
+ ],
+ "Sensors": [
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "Ausgang",
+ "NrDecimals": 0,
+ "Value": 0
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 0,
+ "Type": "Switch input - Switch",
+ "TaskName": "Relais",
+ "TaskDeviceNumber": 1,
+ "TaskEnabled": "false",
+ "TaskNumber": 1
+ },
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "Eingang",
+ "NrDecimals": 0,
+ "Value": 0
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 0,
+ "Type": "Switch input - Switch",
+ "TaskName": "Schalter",
+ "TaskDeviceNumber": 1,
+ "TaskEnabled": "false",
+ "TaskNumber": 2
+ },
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "Temperatur",
+ "NrDecimals": 2,
+ "Value": "nan"
+ },
+ {
+ "ValueNumber": 2,
+ "Name": "Feuchte",
+ "NrDecimals": 2,
+ "Value": "nan"
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 300,
+ "Type": "Environment - DHT11/12/22 SONOFF2301/7021",
+ "TaskName": "DHT_TH2",
+ "TaskDeviceNumber": 5,
+ "TaskEnabled": "false",
+ "TaskNumber": 3
+ }
+ ],
+ "TTL": 60000
+}
diff --git a/app/src/test/resources/espeasy/espeasy-nan.json b/app/src/test/resources/espeasy/espeasy-nan.json
new file mode 100644
index 0000000..bc836ec
--- /dev/null
+++ b/app/src/test/resources/espeasy/espeasy-nan.json
@@ -0,0 +1,105 @@
+{
+ "System": {
+ "Load": 100,
+ "Load LC": 3,
+ "Build": 20116,
+ "Git Build": "mega-20211105_c79d675",
+ "System Libraries": "ESP82xx Core 2843a5ac, NONOS SDK 2.2.2-dev(38a443e), LWIP: 2.1.2 PUYA support",
+ "Plugin Count": 47,
+ "Plugin Description": "[Normal]",
+ "Local Time": "2021-12-10 20:10:10",
+ "Time Source": "NTP",
+ "Time Wander": 0,
+ "Use NTP": "true",
+ "Unit Number": 0,
+ "Unit Name": "ESP_Easy",
+ "Uptime": 3,
+ "Uptime (ms)": 157461,
+ "Last Boot Cause": "Cold Boot",
+ "Reset Reason": "External System",
+ "CPU Eco Mode": "false",
+ "Heap Max Free Block": 9928,
+ "Heap Fragmentation": 14,
+ "Free RAM": 11600,
+ "Free Stack": 3488,
+ "Sunrise": "5:50",
+ "Sunset": "17:57",
+ "Timezone Offset": 1,
+ "Latitude": 0,
+ "Longitude": 0
+ },
+ "WiFi": {
+ "Hostname": "ESP-Easy",
+ "IP Config": "DHCP",
+ "IP Address": "192.168.3.119",
+ "IP Subnet": "255.255.255.0",
+ "Gateway": "192.168.3.91",
+ "STA MAC": "60:01:94:01:6E:75",
+ "DNS 1": "192.168.3.3",
+ "DNS 2": "(IP unset)",
+ "SSID": "home.cweiske.de",
+ "BSSID": "5C:49:79:3B:B1:E0",
+ "Channel": 1,
+ "Encryption Type": "WPA2/PSK",
+ "Connected msec": 153000,
+ "Last Disconnect Reason": 1,
+ "Last Disconnect Reason str": "(1) Unspecified",
+ "Number Reconnects": 0,
+ "Configured SSID1": "home.cweiske.de",
+ "Configured SSID2": "Neo809B",
+ "Force WiFi B/G": "false",
+ "Restart WiFi Lost Conn": "false",
+ "Force WiFi No Sleep": "false",
+ "Periodical send Gratuitous ARP": "true",
+ "Connection Failure Threshold": 0,
+ "Max WiFi TX Power": 17.5,
+ "Current WiFi TX Power": 14,
+ "WiFi Sensitivity Margin": 3,
+ "Send With Max TX Power": "false",
+ "Extra WiFi scan loops": 0,
+ "Use Last Connected AP from RTC": "false",
+ "RSSI": -79
+ },
+ "Sensors": [
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "Temperatur",
+ "NrDecimals": 1,
+ "Value": "nan"
+ },
+ {
+ "ValueNumber": 2,
+ "Name": "Feuchte",
+ "NrDecimals": 1,
+ "Value": 39.5
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 5,
+ "Type": "Environment - DHT11/12/22 SONOFF2301/7021",
+ "TaskName": "DHT",
+ "TaskDeviceNumber": 5,
+ "TaskEnabled": "true",
+ "TaskNumber": 1
+ }
+ ],
+ "TTL": 5000
+}
diff --git a/app/src/test/resources/espeasy/espeasy-pressure.json b/app/src/test/resources/espeasy/espeasy-pressure.json
new file mode 100644
index 0000000..46a61e1
--- /dev/null
+++ b/app/src/test/resources/espeasy/espeasy-pressure.json
@@ -0,0 +1,110 @@
+{
+ "System": {
+ "Build": 20111,
+ "Git Build": "",
+ "System Libraries": "ESP82xx Core 2843a5ac, NONOS SDK 2.2.2-dev(38a443e), LWIP: 2.1.2 PUYA support",
+ "Plugin Count": 46,
+ "Plugin Description": "[Normal]",
+ "Local Time": "2021-12-10 22:54:32",
+ "Unit Number": 244,
+ "Unit Name": "HWR",
+ "Uptime": 121667,
+ "Last Boot Cause": "Manual reboot",
+ "Reset Reason": "Exception",
+ "Load": 14.59,
+ "Load LC": 2255,
+ "CPU Eco Mode": "false",
+ "Heap Max Free Block": 14560,
+ "Heap Fragmentation": 8,
+ "Free RAM": 15696
+ },
+ "WiFi": {
+ "Hostname": "HWR",
+ "IP Config": "DHCP",
+ "IP Address": "172.22.1.244",
+ "IP Subnet": "255.255.255.0",
+ "Gateway": "172.22.1.1",
+ "STA MAC": "5C:CF:7F:2A:1C:D6",
+ "DNS 1": "172.22.1.20",
+ "DNS 2": "(IP unset)",
+ "SSID": "EndeDerVernunft",
+ "BSSID": "E8:DF:70:E4:A7:9C",
+ "Channel": 11,
+ "Connected msec": 1779758000,
+ "Last Disconnect Reason": 8,
+ "Last Disconnect Reason str": "(8) Assoc leave",
+ "Number Reconnects": 2,
+ "Force WiFi B/G": "false",
+ "Restart WiFi Lost Conn": "false",
+ "Force WiFi No Sleep": "false",
+ "Periodical send Gratuitous ARP": "true",
+ "Connection Failure Threshold": 0,
+ "RSSI": -80
+ },
+ "nodes": [
+ {
+ "nr": 244,
+ "name": "HWR",
+ "build": 20111,
+ "platform": "ESP Easy Mega",
+ "ip": "172.22.1.244",
+ "age": 1
+ },
+ {
+ "nr": 245,
+ "name": "Saunahuette",
+ "build": 20116,
+ "platform": "ESP Easy Mega",
+ "ip": "172.22.1.245",
+ "age": 1
+ }
+ ],
+ "Sensors": [
+ {
+ "TaskValues": [
+ {
+ "ValueNumber": 1,
+ "Name": "Temp_BMP",
+ "NrDecimals": 0,
+ "Value": 30
+ },
+ {
+ "ValueNumber": 2,
+ "Name": "Feuchte_BMP",
+ "NrDecimals": 1,
+ "Value": 0
+ },
+ {
+ "ValueNumber": 3,
+ "Name": "Druck_BMP",
+ "NrDecimals": 0,
+ "Value": 1004
+ }
+ ],
+ "DataAcquisition": [
+ {
+ "Controller": 1,
+ "IDX": 0,
+ "Enabled": "true"
+ },
+ {
+ "Controller": 2,
+ "IDX": 0,
+ "Enabled": "false"
+ },
+ {
+ "Controller": 3,
+ "IDX": 0,
+ "Enabled": "false"
+ }
+ ],
+ "TaskInterval": 60,
+ "Type": "Environment - BMx280",
+ "TaskName": "BMP_HWR",
+ "TaskDeviceNumber": 28,
+ "TaskEnabled": "true",
+ "TaskNumber": 1
+ }
+ ],
+ "TTL": 50000
+}
diff --git a/app/src/test/resources/hue/docs-groups.json b/app/src/test/resources/hue/docs-groups.json
new file mode 100644
index 0000000..1885cd1
--- /dev/null
+++ b/app/src/test/resources/hue/docs-groups.json
@@ -0,0 +1,47 @@
+{
+ "1": {
+ "name": "Group 1",
+ "lights": [
+ "1",
+ "2"
+ ],
+ "type": "LightGroup",
+ "action": {
+ "on": true,
+ "bri": 254,
+ "hue": 10000,
+ "sat": 254,
+ "effect": "none",
+ "xy": [
+ 0.5,
+ 0.5
+ ],
+ "ct": 250,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "2": {
+ "name": "Group 2",
+ "lights": [
+ "3",
+ "4",
+ "5"
+ ],
+ "type": "LightGroup",
+ "action": {
+ "on": true,
+ "bri": 153,
+ "hue": 4345,
+ "sat": 254,
+ "effect": "none",
+ "xy": [
+ 0.5,
+ 0.5
+ ],
+ "ct": 250,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/test/resources/hue/home-groups.json b/app/src/test/resources/hue/home-groups.json
new file mode 100644
index 0000000..e4aa27d
--- /dev/null
+++ b/app/src/test/resources/hue/home-groups.json
@@ -0,0 +1,272 @@
+{
+ "1": {
+ "name": "Bedroom",
+ "lights": [
+ "11"
+ ],
+ "sensors": [],
+ "type": "Room",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Bedroom",
+ "action": {
+ "on": false,
+ "bri": 254,
+ "ct": 366,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "2": {
+ "name": "Living Room",
+ "lights": [
+ "1",
+ "7",
+ "2",
+ "10"
+ ],
+ "sensors": [],
+ "type": "Room",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Living room",
+ "action": {
+ "on": false,
+ "bri": 254,
+ "hue": 556,
+ "sat": 254,
+ "effect": "none",
+ "xy": [
+ 0.5267,
+ 0.4133
+ ],
+ "ct": 366,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "3": {
+ "name": "Kitchen Ceiling",
+ "lights": [
+ "13",
+ "14",
+ "15"
+ ],
+ "sensors": [],
+ "type": "Zone",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Kitchen",
+ "action": {
+ "on": false,
+ "bri": 254,
+ "ct": 369,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "4": {
+ "name": "Living Room Ambient",
+ "lights": [
+ "7",
+ "2",
+ "1"
+ ],
+ "sensors": [],
+ "type": "Zone",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Living room",
+ "action": {
+ "on": false,
+ "bri": 76,
+ "hue": 556,
+ "sat": 254,
+ "effect": "none",
+ "xy": [
+ 0.5267,
+ 0.4133
+ ],
+ "ct": 454,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "5": {
+ "name": "Hallway",
+ "lights": [
+ "9",
+ "12"
+ ],
+ "sensors": [],
+ "type": "Room",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Hallway",
+ "action": {
+ "on": false,
+ "bri": 143,
+ "ct": 443,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "6": {
+ "name": "Office",
+ "lights": [
+ "8"
+ ],
+ "sensors": [],
+ "type": "Room",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Computer",
+ "action": {
+ "on": false,
+ "bri": 254,
+ "alert": "select"
+ }
+ },
+ "7": {
+ "name": "Kitchen",
+ "lights": [
+ "13",
+ "14",
+ "15",
+ "6",
+ "5"
+ ],
+ "sensors": [],
+ "type": "Room",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Kitchen",
+ "action": {
+ "on": false,
+ "bri": 254,
+ "ct": 369,
+ "alert": "select",
+ "colormode": "hs"
+ }
+ },
+ "8": {
+ "name": "Unused",
+ "lights": [
+ "4",
+ "3"
+ ],
+ "sensors": [],
+ "type": "Room",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Home",
+ "action": {
+ "on": false,
+ "bri": 119,
+ "ct": 439,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "9": {
+ "name": "Kitchen Cabinets",
+ "lights": [
+ "6",
+ "5"
+ ],
+ "sensors": [],
+ "type": "Zone",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": false,
+ "class": "Kitchen",
+ "action": {
+ "on": false,
+ "alert": "select"
+ }
+ },
+ "10": {
+ "name": "Custom group for $leftGroup",
+ "lights": [
+ "10"
+ ],
+ "sensors": [],
+ "type": "LightGroup",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": true,
+ "action": {
+ "on": false,
+ "bri": 254,
+ "ct": 366,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ },
+ "11": {
+ "name": "Custom group for $leftGroup",
+ "lights": [
+ "8"
+ ],
+ "sensors": [],
+ "type": "LightGroup",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": true,
+ "action": {
+ "on": false,
+ "bri": 254,
+ "alert": "select"
+ }
+ },
+ "12": {
+ "name": "Custom group for $leftGroup",
+ "lights": [
+ "11"
+ ],
+ "sensors": [],
+ "type": "LightGroup",
+ "state": {
+ "all_on": false,
+ "any_on": false
+ },
+ "recycle": true,
+ "action": {
+ "on": false,
+ "bri": 254,
+ "ct": 366,
+ "alert": "select",
+ "colormode": "ct"
+ }
+ }
+}
diff --git a/app/src/test/resources/shelly/shelly-MiniPMG3-Shelly.GetConfig.json b/app/src/test/resources/shelly/shelly-MiniPMG3-Shelly.GetConfig.json
new file mode 100644
index 0000000..5380c8c
--- /dev/null
+++ b/app/src/test/resources/shelly/shelly-MiniPMG3-Shelly.GetConfig.json
@@ -0,0 +1,109 @@
+{
+ "ble": {
+ "enable": false,
+ "rpc": {
+ "enable": false
+ },
+ "observer": {
+ "enable": false
+ }
+ },
+ "bthome": {},
+ "cloud": {
+ "enable": false,
+ "server": "iot.shelly.cloud:6012/jrpc"
+ },
+ "mqtt": {
+ "enable": false,
+ "server": null,
+ "client_id": "shellypmminig3-ecda3bc7176c",
+ "user": null,
+ "ssl_ca": null,
+ "topic_prefix": "shellypmminig3-ecda3bc7176c",
+ "rpc_ntf": true,
+ "status_ntf": false,
+ "use_client_cert": false,
+ "enable_rpc": true,
+ "enable_control": true
+ },
+ "pm1:0": {
+ "id": 0,
+ "name": "Kühlschrank",
+ "reverse": false
+ },
+ "sys": {
+ "device": {
+ "name": "shellypm4",
+ "mac": "ECDA3BC7176C",
+ "fw_id": "20241011-114503/1.4.4-g6d2a586",
+ "discoverable": true,
+ "eco_mode": false
+ },
+ "location": {
+ "tz": "Europe/Berlin",
+ "lat": 51.1591,
+ "lon": 12.2847
+ },
+ "debug": {
+ "level": 2,
+ "file_level": null,
+ "mqtt": {
+ "enable": false
+ },
+ "websocket": {
+ "enable": false
+ },
+ "udp": {
+ "addr": null
+ }
+ },
+ "ui_data": {},
+ "rpc_udp": {
+ "dst_addr": null,
+ "listen_port": null
+ },
+ "sntp": {
+ "server": "time.google.com"
+ },
+ "cfg_rev": 9
+ },
+ "wifi": {
+ "ap": {
+ "ssid": "ShellyPMMiniG3-ECDA3BC7176C",
+ "is_open": true,
+ "enable": false,
+ "range_extender": {
+ "enable": false
+ }
+ },
+ "sta": {
+ "ssid": "home.cweiske.de",
+ "is_open": false,
+ "enable": true,
+ "ipv4mode": "static",
+ "ip": "192.168.3.63",
+ "netmask": "255.255.255.0",
+ "gw": "192.168.3.3",
+ "nameserver": "192.168.3.3"
+ },
+ "sta1": {
+ "ssid": null,
+ "is_open": true,
+ "enable": false,
+ "ipv4mode": "dhcp",
+ "ip": null,
+ "netmask": null,
+ "gw": null,
+ "nameserver": null
+ },
+ "roam": {
+ "rssi_thr": -80,
+ "interval": 60
+ }
+ },
+ "ws": {
+ "enable": false,
+ "server": null,
+ "ssl_ca": "ca.pem"
+ }
+}
\ No newline at end of file
diff --git a/app/src/test/resources/shelly/shelly-MiniPMG3-Shelly.GetStatus.json b/app/src/test/resources/shelly/shelly-MiniPMG3-Shelly.GetStatus.json
new file mode 100644
index 0000000..096df6c
--- /dev/null
+++ b/app/src/test/resources/shelly/shelly-MiniPMG3-Shelly.GetStatus.json
@@ -0,0 +1,69 @@
+{
+ "ble": {},
+ "bthome": {
+ "errors": [
+ "bluetooth_disabled"
+ ]
+ },
+ "cloud": {
+ "connected": false
+ },
+ "mqtt": {
+ "connected": false
+ },
+ "pm1:0": {
+ "id": 0,
+ "voltage": 231.5,
+ "current": 0.033,
+ "apower": 4,
+ "freq": 50.1,
+ "aenergy": {
+ "total": 1.695,
+ "by_minute": [
+ 0,
+ 0,
+ 211.882
+ ],
+ "minute_ts": 1738782780
+ },
+ "ret_aenergy": {
+ "total": 0,
+ "by_minute": [
+ 0,
+ 0,
+ 0
+ ],
+ "minute_ts": 1738782780
+ }
+ },
+ "sys": {
+ "mac": "ECDA3BC7176C",
+ "restart_required": false,
+ "time": "20:13",
+ "unixtime": 1738782813,
+ "uptime": 1546,
+ "ram_size": 260924,
+ "ram_free": 143424,
+ "fs_size": 1048576,
+ "fs_free": 618496,
+ "cfg_rev": 9,
+ "kvs_rev": 5,
+ "schedule_rev": 0,
+ "webhook_rev": 0,
+ "available_updates": {
+ "beta": {
+ "version": "1.5.0-beta2"
+ }
+ },
+ "reset_reason": 3
+ },
+ "wifi": {
+ "sta_ip": "192.168.3.63",
+ "status": "got ip",
+ "ssid": "home.cweiske.de",
+ "rssi": -64
+ },
+ "ws": {
+ "connected": false
+ }
+}
\ No newline at end of file
diff --git a/app/src/test/resources/shelly/shelly-plus-1-Shelly.GetConfig.json b/app/src/test/resources/shelly/shelly-plus-1-Shelly.GetConfig.json
new file mode 100644
index 0000000..f9e1973
--- /dev/null
+++ b/app/src/test/resources/shelly/shelly-plus-1-Shelly.GetConfig.json
@@ -0,0 +1,108 @@
+{
+ "ble": {
+ "enable": false
+ },
+ "cloud": {
+ "enable": false,
+ "server": "iot.shelly.cloud:6012/jrpc"
+ },
+ "input:0": {
+ "id": 0,
+ "name": null,
+ "type": "switch",
+ "invert": false,
+ "factory_reset": true
+ },
+ "mqtt": {
+ "enable": false,
+ "server": null,
+ "user": null,
+ "pass": null,
+ "topic_prefix": null,
+ "rpc_ntf": true,
+ "status_ntf": false
+ },
+ "switch:0": {
+ "id": 0,
+ "name": "Kamin",
+ "in_mode": "follow",
+ "initial_state": "restore_last",
+ "auto_on": false,
+ "auto_on_delay": 60,
+ "auto_off": false,
+ "auto_off_delay": 60
+ },
+ "sys": {
+ "device": {
+ "name": "Shelly Kamin",
+ "mac": "A8032ABD2342",
+ "fw_id": "20211203-130101/0.9.1-ga939435"
+ },
+ "location": {
+ "tz": "Europe/Berlin",
+ "lat": 49.86571,
+ "lon": 8.62604
+ },
+ "debug": {
+ "mqtt": {
+ "enable": false
+ },
+ "websocket": {
+ "enable": false
+ },
+ "udp": {
+ "addr": null
+ }
+ },
+ "ui_data": {
+ "pin_locks": [
+ {
+ "value": "",
+ "enable": false
+ }
+ ],
+ "consumption_types": [
+ "lights"
+ ]
+ },
+ "rpc_udp": {
+ "dst_addr": null,
+ "listen_port": null
+ },
+ "sntp": {
+ "server": "time.google.com"
+ },
+ "cfg_rev": 1
+ },
+ "wifi": {
+ "ap": {
+ "ssid": "ShellyPlus1-A8032ABD2342",
+ "is_open": true,
+ "enable": false
+ },
+ "sta": {
+ "ssid": "home.cweiske.de",
+ "is_open": false,
+ "enable": true,
+ "ipv4mode": "static",
+ "ip": "192.168.3.72",
+ "netmask": "255.255.255.0",
+ "gw": "192.168.3.3",
+ "nameserver": "192.168.3.3"
+ },
+ "sta1": {
+ "ssid": null,
+ "is_open": true,
+ "enable": false,
+ "ipv4mode": "dhcp",
+ "ip": null,
+ "netmask": null,
+ "gw": null,
+ "nameserver": null
+ },
+ "roam": {
+ "rssi_thr": -80,
+ "interval": 60
+ }
+ }
+}
diff --git a/app/src/test/resources/shelly/shelly-plus-1-Shelly.GetStatus.json b/app/src/test/resources/shelly/shelly-plus-1-Shelly.GetStatus.json
new file mode 100644
index 0000000..b98b7e8
--- /dev/null
+++ b/app/src/test/resources/shelly/shelly-plus-1-Shelly.GetStatus.json
@@ -0,0 +1,41 @@
+{
+ "ble": {},
+ "cloud": {
+ "connected": false
+ },
+ "input:0": {
+ "id": 0,
+ "state": false
+ },
+ "mqtt": {
+ "connected": false
+ },
+ "switch:0": {
+ "id": 0,
+ "source": "HTTP",
+ "output": true,
+ "temperature": {
+ "tC": 58.6,
+ "tF": 137.6
+ }
+ },
+ "sys": {
+ "mac": "A8032ABD2342",
+ "restart_required": true,
+ "time": "21:21",
+ "unixtime": 1638822089,
+ "uptime": 179113,
+ "ram_size": 249408,
+ "ram_free": 176100,
+ "fs_size": 458752,
+ "fs_free": 241664,
+ "cfg_rev": 1,
+ "available_updates": {}
+ },
+ "wifi": {
+ "sta_ip": "192.168.3.72",
+ "status": "got ip",
+ "ssid": "home.cweiske.de",
+ "rssi": -64
+ }
+}
diff --git a/app/src/test/resources/shelly/shelly1-settings.json b/app/src/test/resources/shelly/shelly1-settings.json
new file mode 100644
index 0000000..c702661
--- /dev/null
+++ b/app/src/test/resources/shelly/shelly1-settings.json
@@ -0,0 +1,164 @@
+{
+ "device": {
+ "type": "SHSW-1",
+ "mac": "40F520052342",
+ "hostname": "shelly1-40F520052342",
+ "num_outputs": 1
+ },
+ "wifi_ap": {
+ "enabled": false,
+ "ssid": "shelly1-40F520052342",
+ "key": ""
+ },
+ "wifi_sta": {
+ "enabled": true,
+ "ssid": "IoT",
+ "ipv4_method": "static",
+ "ip": "172.22.2.19",
+ "gw": "172.22.2.1",
+ "mask": "255.255.255.0",
+ "dns": "8.8.8.8"
+ },
+ "wifi_sta1": {
+ "enabled": false,
+ "ssid": null,
+ "ipv4_method": "dhcp",
+ "ip": null,
+ "gw": null,
+ "mask": null,
+ "dns": null
+ },
+ "ap_roaming": {
+ "enabled": false,
+ "threshold": -70
+ },
+ "mqtt": {
+ "enable": false,
+ "server": "192.168.33.3:1883",
+ "user": "",
+ "id": "shelly1-40F520052342",
+ "reconnect_timeout_max": 60,
+ "reconnect_timeout_min": 2,
+ "clean_session": true,
+ "keep_alive": 60,
+ "max_qos": 0,
+ "retain": false,
+ "update_period": 30
+ },
+ "coiot": {
+ "enabled": true,
+ "update_period": 15,
+ "peer": ""
+ },
+ "sntp": {
+ "server": "time.google.com",
+ "enabled": true
+ },
+ "login": {
+ "enabled": false,
+ "unprotected": false,
+ "username": "admin"
+ },
+ "pin_code": "",
+ "name": null,
+ "fw": "20211109-124958/v1.11.7-g682a0db",
+ "factory_reset_from_switch": true,
+ "discoverable": true,
+ "build_info": {
+ "build_id": "20211109-124958/v1.11.7-g682a0db",
+ "build_timestamp": "2021-11-09T12:49:58Z",
+ "build_version": "1.0"
+ },
+ "cloud": {
+ "enabled": false,
+ "connected": false
+ },
+ "timezone": "Europe/Berlin",
+ "lat": 51.231339,
+ "lng": 12.71792,
+ "tzautodetect": true,
+ "tz_utc_offset": 3600,
+ "tz_dst": false,
+ "tz_dst_auto": true,
+ "time": "21:16",
+ "unixtime": 1638994593,
+ "debug_enable": false,
+ "allow_cross_origin": false,
+ "ext_switch_enable": false,
+ "ext_switch_reverse": false,
+ "ext_switch": {
+ "0": {
+ "relay_num": -1
+ }
+ },
+ "actions": {
+ "active": false,
+ "names": [
+ "btn_on_url",
+ "btn_off_url",
+ "longpush_url",
+ "shortpush_url",
+ "out_on_url",
+ "out_off_url",
+ "lp_on_url",
+ "lp_off_url",
+ "ext_temp_over_url",
+ "ext_temp_under_url",
+ "ext_temp_over_url",
+ "ext_temp_under_url",
+ "ext_temp_over_url",
+ "ext_temp_under_url",
+ "ext_hum_over_url",
+ "ext_hum_under_url"
+ ]
+ },
+ "hwinfo": {
+ "hw_revision": "prod-191217",
+ "batch_id": 1
+ },
+ "mode": "relay",
+ "longpush_time": 800,
+ "relays": [
+ {
+ "name": null,
+ "appliance_type": "General",
+ "ison": false,
+ "has_timer": false,
+ "default_state": "switch",
+ "btn_type": "toggle",
+ "btn_reverse": 0,
+ "auto_on": 0,
+ "auto_off": 0,
+ "power": 0,
+ "schedule": true,
+ "schedule_rules": [
+ "0300-01234-on",
+ "1000-01234-off"
+ ]
+ }
+ ],
+ "ext_sensors": {
+ "temperature_unit": "C"
+ },
+ "ext_temperature": {
+ "0": {
+ "overtemp_threshold_tC": 23,
+ "overtemp_threshold_tF": 73.4,
+ "undertemp_threshold_tC": 20,
+ "undertemp_threshold_tF": 68,
+ "overtemp_act": "relay_off",
+ "undertemp_act": "relay_on",
+ "offset_tC": 0,
+ "offset_tF": 0
+ }
+ },
+ "ext_humidity": {
+ "0": {
+ "overhum_threshold": 0,
+ "underhum_threshold": 0,
+ "overhum_act": "disabled",
+ "underhum_act": "disabled",
+ "offset": 0
+ }
+ }
+}
diff --git a/app/src/test/resources/shelly/shelly1-shelly.json b/app/src/test/resources/shelly/shelly1-shelly.json
new file mode 100644
index 0000000..1a29a3f
--- /dev/null
+++ b/app/src/test/resources/shelly/shelly1-shelly.json
@@ -0,0 +1,8 @@
+{
+ "type": "SHSW-1",
+ "mac": "483FDA822342",
+ "auth": false,
+ "fw": "20211109-124958/v1.11.7-g682a0db",
+ "longid": 1,
+ "num_outputs": 1
+}
\ No newline at end of file
diff --git a/app/src/test/resources/shelly/shelly1-status.json b/app/src/test/resources/shelly/shelly1-status.json
new file mode 100644
index 0000000..c1edf19
--- /dev/null
+++ b/app/src/test/resources/shelly/shelly1-status.json
@@ -0,0 +1,74 @@
+{
+ "wifi_sta": {
+ "connected": true,
+ "ssid": "IoT",
+ "ip": "172.22.2.19",
+ "rssi": -70
+ },
+ "cloud": {
+ "enabled": false,
+ "connected": false
+ },
+ "mqtt": {
+ "connected": false
+ },
+ "time": "13:22",
+ "unixtime": 1638361363,
+ "serial": 1,
+ "has_update": false,
+ "mac": "483FDA822342",
+ "cfg_changed_cnt": 0,
+ "actions_stats": {
+ "skipped": 0
+ },
+ "relays": [
+ {
+ "ison": false,
+ "has_timer": false,
+ "timer_started": 0,
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "source": "input"
+ }
+ ],
+ "meters": [
+ {
+ "power": 0,
+ "is_valid": true
+ }
+ ],
+ "inputs": [
+ {
+ "input": 0,
+ "event": "",
+ "event_cnt": 0
+ }
+ ],
+ "ext_sensors": {
+ "temperature_unit": "C"
+ },
+ "ext_temperature": {
+ "0": {
+ "hwID": "0300",
+ "tC": 23,
+ "tF": 73.4
+ }
+ },
+ "ext_humidity": {
+ "0": {
+ "hwID": "0300",
+ "hum": 52.3
+ }
+ },
+ "update": {
+ "status": "idle",
+ "has_update": false,
+ "new_version": "20211109-124958/v1.11.7-g682a0db",
+ "old_version": "20211109-124958/v1.11.7-g682a0db"
+ },
+ "ram_total": 50880,
+ "ram_free": 39512,
+ "fs_size": 233681,
+ "fs_free": 151102,
+ "uptime": 51
+}
\ No newline at end of file
diff --git a/app/src/test/resources/shelly/shellyplug1-icons-settings.json b/app/src/test/resources/shelly/shellyplug1-icons-settings.json
new file mode 100644
index 0000000..21230f9
--- /dev/null
+++ b/app/src/test/resources/shelly/shellyplug1-icons-settings.json
@@ -0,0 +1,176 @@
+{
+ "device": {
+ "type": "SHPLG-S",
+ "mac": "E09806972342",
+ "hostname": "shellyplug-s-972342",
+ "num_outputs": 1,
+ "num_meters": 1
+ },
+ "wifi_ap": {
+ "enabled": false,
+ "ssid": "shellyplug-s-972342",
+ "key": ""
+ },
+ "wifi_sta": {
+ "enabled": true,
+ "ssid": "home.cweiske.de",
+ "ipv4_method": "static",
+ "ip": "192.168.3.77",
+ "gw": "192.168.3.3",
+ "mask": "255.255.255.0",
+ "dns": "192.168.3.3"
+ },
+ "wifi_sta1": {
+ "enabled": false,
+ "ssid": null,
+ "ipv4_method": "dhcp",
+ "ip": null,
+ "gw": null,
+ "mask": null,
+ "dns": null
+ },
+ "ap_roaming": {
+ "enabled": false,
+ "threshold": -70
+ },
+ "mqtt": {
+ "enable": false,
+ "server": "192.168.33.3:1883",
+ "user": "",
+ "id": "shellyplug-s-972342",
+ "reconnect_timeout_max": 60,
+ "reconnect_timeout_min": 2,
+ "clean_session": true,
+ "keep_alive": 60,
+ "max_qos": 0,
+ "retain": false,
+ "update_period": 30
+ },
+ "coiot": {
+ "enabled": true,
+ "update_period": 15,
+ "peer": ""
+ },
+ "sntp": {
+ "server": "time.google.com",
+ "enabled": true
+ },
+ "login": {
+ "enabled": false,
+ "unprotected": false,
+ "username": "myuser"
+ },
+ "pin_code": "",
+ "name": "Shellyplug1",
+ "fw": "20211109-130223/v1.11.7-g682a0db",
+ "discoverable": true,
+ "build_info": {
+ "build_id": "20211109-130223/v1.11.7-g682a0db",
+ "build_timestamp": "2021-11-09T13:02:23Z",
+ "build_version": "1.0"
+ },
+ "cloud": {
+ "enabled": false,
+ "connected": false
+ },
+ "timezone": "Europe/Berlin",
+ "lat": 49.865711,
+ "lng": 8.62604,
+ "tzautodetect": true,
+ "tz_utc_offset": 3600,
+ "tz_dst": false,
+ "tz_dst_auto": true,
+ "time": "20:46",
+ "unixtime": 1638733563,
+ "led_status_disable": true,
+ "debug_enable": false,
+ "allow_cross_origin": false,
+ "actions": {
+ "active": false,
+ "names": [
+ "btn_on_url",
+ "out_on_url",
+ "out_off_url"
+ ]
+ },
+ "hwinfo": {
+ "hw_revision": "prod-190516",
+ "batch_id": 1
+ },
+ "max_power": 2500,
+ "led_power_disable": true,
+ "relays": [
+ {
+ "name": "Deckenlampe",
+ "appliance_type": "lights",
+ "ison": true,
+ "has_timer": false,
+ "default_state": "last",
+ "auto_on": 0,
+ "auto_off": 0,
+ "schedule": false,
+ "schedule_rules": [],
+ "max_power": 2500
+ },
+ {
+ "name": "Steckdose",
+ "appliance_type": "socket",
+ "ison": true,
+ "has_timer": false,
+ "default_state": "last",
+ "auto_on": 0,
+ "auto_off": 0,
+ "schedule": false,
+ "schedule_rules": [],
+ "max_power": 2500
+ },
+ {
+ "name": "Radiator",
+ "appliance_type": "heating",
+ "ison": true,
+ "has_timer": false,
+ "default_state": "last",
+ "auto_on": 0,
+ "auto_off": 0,
+ "schedule": false,
+ "schedule_rules": [],
+ "max_power": 2500
+ },
+ {
+ "name": "Stereoanlage",
+ "appliance_type": "entertainment",
+ "ison": true,
+ "has_timer": false,
+ "default_state": "last",
+ "auto_on": 0,
+ "auto_off": 0,
+ "schedule": false,
+ "schedule_rules": [],
+ "max_power": 2500
+ },
+ {
+ "name": "Tannenbaum (en)",
+ "appliance_type": "christmas tree",
+ "ison": true,
+ "has_timer": false,
+ "default_state": "last",
+ "auto_on": 0,
+ "auto_off": 0,
+ "schedule": false,
+ "schedule_rules": [],
+ "max_power": 2500
+ },
+ {
+ "name": "Schwibbogen",
+ "appliance_type": "schwibbogen",
+ "ison": true,
+ "has_timer": false,
+ "default_state": "last",
+ "auto_on": 0,
+ "auto_off": 0,
+ "schedule": false,
+ "schedule_rules": [],
+ "max_power": 2500
+ }
+ ]
+}
diff --git a/app/src/test/resources/shelly/shellyplug1-icons-status.json b/app/src/test/resources/shelly/shellyplug1-icons-status.json
new file mode 100644
index 0000000..05795cd
--- /dev/null
+++ b/app/src/test/resources/shelly/shellyplug1-icons-status.json
@@ -0,0 +1,100 @@
+{
+ "actions_stats": {
+ "skipped": 0
+ },
+ "cfg_changed_cnt": 2,
+ "cloud": {
+ "connected": false,
+ "enabled": false
+ },
+ "fs_free": 164656,
+ "fs_size": 233681,
+ "has_update": false,
+ "mac": "E09806972342",
+ "meters": [
+ ],
+ "mqtt": {
+ "connected": false
+ },
+ "overtemperature": false,
+ "ram_free": 40024,
+ "ram_total": 51272,
+ "relays": [
+ {
+ "has_timer": false,
+ "ison": true,
+ "overpower": false,
+ "source": "http",
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "timer_started": 0
+ },
+ {
+ "has_timer": false,
+ "ison": true,
+ "overpower": false,
+ "source": "http",
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "timer_started": 0
+ },
+ {
+ "has_timer": false,
+ "ison": true,
+ "overpower": false,
+ "source": "http",
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "timer_started": 0
+ },
+ {
+ "has_timer": false,
+ "ison": true,
+ "overpower": false,
+ "source": "http",
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "timer_started": 0
+ },
+ {
+ "has_timer": false,
+ "ison": true,
+ "overpower": false,
+ "source": "http",
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "timer_started": 0
+ },
+ {
+ "has_timer": false,
+ "ison": true,
+ "overpower": false,
+ "source": "http",
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "timer_started": 0
+ }
+ ],
+ "serial": 117,
+ "temperature": 31.49,
+ "time": "20:39",
+ "tmp": {
+ "is_valid": true,
+ "tC": 31.49,
+ "tF": 88.68
+ },
+ "unixtime": 1638905945,
+ "update": {
+ "has_update": false,
+ "new_version": "20211109-130223/v1.11.7-g682a0db",
+ "old_version": "20211109-130223/v1.11.7-g682a0db",
+ "status": "idle"
+ },
+ "uptime": 454998,
+ "wifi_sta": {
+ "connected": true,
+ "ip": "192.168.3.77",
+ "rssi": -68,
+ "ssid": "home.cweiske.de"
+ }
+}
diff --git a/app/src/test/resources/shelly/shellyplug1-settings.json b/app/src/test/resources/shelly/shellyplug1-settings.json
new file mode 100644
index 0000000..41b62e2
--- /dev/null
+++ b/app/src/test/resources/shelly/shellyplug1-settings.json
@@ -0,0 +1,116 @@
+{
+ "device": {
+ "type": "SHPLG-S",
+ "mac": "E09806972342",
+ "hostname": "shellyplug-s-972342",
+ "num_outputs": 1,
+ "num_meters": 1
+ },
+ "wifi_ap": {
+ "enabled": false,
+ "ssid": "shellyplug-s-972342",
+ "key": ""
+ },
+ "wifi_sta": {
+ "enabled": true,
+ "ssid": "home.cweiske.de",
+ "ipv4_method": "static",
+ "ip": "192.168.3.77",
+ "gw": "192.168.3.3",
+ "mask": "255.255.255.0",
+ "dns": "192.168.3.3"
+ },
+ "wifi_sta1": {
+ "enabled": false,
+ "ssid": null,
+ "ipv4_method": "dhcp",
+ "ip": null,
+ "gw": null,
+ "mask": null,
+ "dns": null
+ },
+ "ap_roaming": {
+ "enabled": false,
+ "threshold": -70
+ },
+ "mqtt": {
+ "enable": false,
+ "server": "192.168.33.3:1883",
+ "user": "",
+ "id": "shellyplug-s-972342",
+ "reconnect_timeout_max": 60,
+ "reconnect_timeout_min": 2,
+ "clean_session": true,
+ "keep_alive": 60,
+ "max_qos": 0,
+ "retain": false,
+ "update_period": 30
+ },
+ "coiot": {
+ "enabled": true,
+ "update_period": 15,
+ "peer": ""
+ },
+ "sntp": {
+ "server": "time.google.com",
+ "enabled": true
+ },
+ "login": {
+ "enabled": false,
+ "unprotected": false,
+ "username": "myuser"
+ },
+ "pin_code": "",
+ "name": "Shellyplug1",
+ "fw": "20211109-130223/v1.11.7-g682a0db",
+ "discoverable": true,
+ "build_info": {
+ "build_id": "20211109-130223/v1.11.7-g682a0db",
+ "build_timestamp": "2021-11-09T13:02:23Z",
+ "build_version": "1.0"
+ },
+ "cloud": {
+ "enabled": false,
+ "connected": false
+ },
+ "timezone": "Europe/Berlin",
+ "lat": 49.865711,
+ "lng": 8.62604,
+ "tzautodetect": true,
+ "tz_utc_offset": 3600,
+ "tz_dst": false,
+ "tz_dst_auto": true,
+ "time": "20:46",
+ "unixtime": 1638733563,
+ "led_status_disable": true,
+ "debug_enable": false,
+ "allow_cross_origin": false,
+ "actions": {
+ "active": false,
+ "names": [
+ "btn_on_url",
+ "out_on_url",
+ "out_off_url"
+ ]
+ },
+ "hwinfo": {
+ "hw_revision": "prod-190516",
+ "batch_id": 1
+ },
+ "max_power": 2500,
+ "led_power_disable": true,
+ "relays": [
+ {
+ "name": "Wohnzimmer Gartenfenster",
+ "appliance_type": "General",
+ "ison": true,
+ "has_timer": false,
+ "default_state": "last",
+ "auto_on": 0,
+ "auto_off": 0,
+ "schedule": false,
+ "schedule_rules": [],
+ "max_power": 2500
+ }
+ ]
+}
diff --git a/app/src/test/resources/shelly/shellyplug1-status.json b/app/src/test/resources/shelly/shellyplug1-status.json
new file mode 100644
index 0000000..618b164
--- /dev/null
+++ b/app/src/test/resources/shelly/shellyplug1-status.json
@@ -0,0 +1,67 @@
+{
+ "actions_stats": {
+ "skipped": 0
+ },
+ "cfg_changed_cnt": 2,
+ "cloud": {
+ "connected": false,
+ "enabled": false
+ },
+ "fs_free": 164656,
+ "fs_size": 233681,
+ "has_update": false,
+ "mac": "E09806972342",
+ "meters": [
+ {
+ "counters": [
+ 27.889,
+ 27.884,
+ 27.887
+ ],
+ "is_valid": true,
+ "overpower": 0.0,
+ "power": 27.95,
+ "timestamp": 1638909545,
+ "total": 79532
+ }
+ ],
+ "mqtt": {
+ "connected": false
+ },
+ "overtemperature": false,
+ "ram_free": 40024,
+ "ram_total": 51272,
+ "relays": [
+ {
+ "has_timer": false,
+ "ison": true,
+ "overpower": false,
+ "source": "http",
+ "timer_duration": 0,
+ "timer_remaining": 0,
+ "timer_started": 0
+ }
+ ],
+ "serial": 117,
+ "temperature": 31.49,
+ "time": "20:39",
+ "tmp": {
+ "is_valid": true,
+ "tC": 31.49,
+ "tF": 88.68
+ },
+ "unixtime": 1638905945,
+ "update": {
+ "has_update": false,
+ "new_version": "20211109-130223/v1.11.7-g682a0db",
+ "old_version": "20211109-130223/v1.11.7-g682a0db",
+ "status": "idle"
+ },
+ "uptime": 454998,
+ "wifi_sta": {
+ "connected": true,
+ "ip": "192.168.3.77",
+ "rssi": -68,
+ "ssid": "home.cweiske.de"
+ }
+}
diff --git a/app/src/test/resources/simplehome/temperature-sensor-commands.json b/app/src/test/resources/simplehome/temperature-sensor-commands.json
new file mode 100644
index 0000000..3615b74
--- /dev/null
+++ b/app/src/test/resources/simplehome/temperature-sensor-commands.json
@@ -0,0 +1,16 @@
+{
+ "commands": {
+ "temperature": {
+ "title": "Temperature",
+ "summary": "It is currently 18.00°C in your room",
+ "icon": "thermometer",
+ "mode": "none"
+ },
+ "humidity": {
+ "title": "Humidity",
+ "summary": "The humidity is 86.30 %",
+ "icon": "hygrometer",
+ "mode": "none"
+ }
+ }
+}
diff --git a/app/src/test/resources/simplehome/test-server-commands.json b/app/src/test/resources/simplehome/test-server-commands.json
new file mode 100644
index 0000000..8693390
--- /dev/null
+++ b/app/src/test/resources/simplehome/test-server-commands.json
@@ -0,0 +1,29 @@
+{
+ "commands": {
+ "example": {
+ "title": "Title of the command",
+ "summary": "Summary of the command"
+ },
+ "example2": {
+ "title": "Title of the command",
+ "summary": "Mode: none",
+ "mode": "none"
+ },
+ "example3": {
+ "title": "Title of the command",
+ "summary": "Mode: input",
+ "mode": "input",
+ "data": "Default"
+ },
+ "example4": {
+ "title": "Title of the command",
+ "summary": "Mode: switch",
+ "mode": "switch",
+ "data": true
+ },
+ "rand": {
+ "title": "1944518792",
+ "summary": "523219119"
+ }
+ }
+}
diff --git a/build.gradle.kts b/build.gradle.kts
new file mode 100644
index 0000000..3e9598f
--- /dev/null
+++ b/build.gradle.kts
@@ -0,0 +1,6 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+plugins {
+ id("com.android.application") version "8.10.1" apply false
+ id("org.jetbrains.kotlin.android") version "2.1.21" apply false
+ id("io.gitlab.arturbosch.detekt") version "1.23.8" apply false
+}
diff --git a/fastlane/metadata/android/en-US/changelogs/1100.txt b/fastlane/metadata/android/en-US/changelogs/1100.txt
new file mode 100644
index 0000000..1705d10
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/1100.txt
@@ -0,0 +1 @@
+This version includes a new editor for Hue scenes and supports tinted app icons on the new Android version. There are also some new shortcuts (widgets) for devices and Hue controls that help you find what you are looking for faster. Furthermore, there is now a new device info page for Shelly Gen 2 devices, and an issue with Shelly Gen 1 devices has been fixed thanks to @Gared.
diff --git a/fastlane/metadata/android/en-US/changelogs/1110.txt b/fastlane/metadata/android/en-US/changelogs/1110.txt
new file mode 100644
index 0000000..5347cb8
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/1110.txt
@@ -0,0 +1 @@
+This version includes improved Shelly Gen 3 support, thanks to cweiske. Furthermore, there were some behind-the-scenes changes to improve code quality.
diff --git a/fastlane/metadata/android/en-US/changelogs/1120.txt b/fastlane/metadata/android/en-US/changelogs/1120.txt
new file mode 100644
index 0000000..75fd567
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/1120.txt
@@ -0,0 +1,3 @@
+This update introduces support for displaying energy counter values for Shelly devices. Hue device integration has been improved with the addition of brightness control and color adjustment directly from system home controls. A new basic control information activity has been implemented, and internal support for sliders has been prepared. The logic for live summary updates has been revised for improved responsiveness. Layout adjustments have been made, including padding enhancements and updates to the edit device screen. Dependency updates have been applied throughout.
+
+Additionally, a simple Grafana integration now features auto-login and a new icon, with the client extracted from the web activity for better modularity. Pi-hole has also received auto-login functionality along with updated Docker and Raspberry Pi icons. Script evaluation has been adjusted, and certificate handling in the web view has been relaxed to allow self-signed certificates.
diff --git a/fastlane/metadata/android/en-US/changelogs/161.txt b/fastlane/metadata/android/en-US/changelogs/161.txt
new file mode 100644
index 0000000..a7922ab
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/161.txt
@@ -0,0 +1,3 @@
+- Add German translation
+- Add Dutch translation
+- Improve about screen
diff --git a/fastlane/metadata/android/en-US/changelogs/170.txt b/fastlane/metadata/android/en-US/changelogs/170.txt
new file mode 100644
index 0000000..cc59130
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/170.txt
@@ -0,0 +1,4 @@
+- Add Spanish translation
+- Add Tasmota support
+- Add support for web authentication
+- Update Hue data in real-time
diff --git a/fastlane/metadata/android/en-US/changelogs/171.txt b/fastlane/metadata/android/en-US/changelogs/171.txt
new file mode 100644
index 0000000..791311c
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/171.txt
@@ -0,0 +1,5 @@
+- Fixed bug related to the device list
+- Improved performance
+- Websites won't reload on orientation change
+- More detailed Tasmota response
+- Switched to Material Components
diff --git a/fastlane/metadata/android/en-US/changelogs/172.txt b/fastlane/metadata/android/en-US/changelogs/172.txt
new file mode 100644
index 0000000..0dc81a8
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/172.txt
@@ -0,0 +1 @@
+This update includes bug fixes and performance improvements.
diff --git a/fastlane/metadata/android/en-US/changelogs/173.txt b/fastlane/metadata/android/en-US/changelogs/173.txt
new file mode 100644
index 0000000..f1a1c69
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/173.txt
@@ -0,0 +1 @@
+This update includes new layouts for Hue rooms and lamps. Furthermore, you can now see your scene and lamp colors and if your hue lamps are reachable. Try changing the color of your Hue lamps with the new visual color picker. In addition to that, the experimental device discovery has been made more robust and the Node-RED dashboard can now be viewed in the app. A button for opening websites in your browser has been added as well and reordering your devices is more intuitive with this update. In case you are using Fritz! products, you can try the new Auto-Login mode to save some time. Your passwords are stored encrypted. And finally, lots of invisible performance improvements have been made.
diff --git a/fastlane/metadata/android/en-US/changelogs/180.txt b/fastlane/metadata/android/en-US/changelogs/180.txt
new file mode 100644
index 0000000..fd8e695
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/180.txt
@@ -0,0 +1,2 @@
+This update adds support for Shelly and Esp Easy devices. Furthermore, the device discovery process has been improved once again, and new device icons have been added. A big new feature is "Direct View" which makes it possible to load devices directly when you start the app.
+Make sure to check out the release notes of previous versions as well!
\ No newline at end of file
diff --git a/fastlane/metadata/android/en-US/changelogs/190.txt b/fastlane/metadata/android/en-US/changelogs/190.txt
new file mode 100644
index 0000000..cc17bdc
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/190.txt
@@ -0,0 +1 @@
+This release lets you control your devices from your Android (> 11) power menu and improves the implementation of the SimpleHome API. Furthermore, support for Philips Hue has been improved and the number of columns in the main activity has been made adjustable. Of course, there were some under the hood improvements as well. Make sure to check out the release notes of previous versions as well!
\ No newline at end of file
diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt
new file mode 100644
index 0000000..aed63ee
--- /dev/null
+++ b/fastlane/metadata/android/en-US/full_description.txt
@@ -0,0 +1,27 @@
+HomeApp is a small and easy to use smart home app with a simple framework. The goal of this application is to make remote execution of predefined features as easy and user-friendly as possible to help you get started with smart home technology.
+
+Supported devices
+- Philips Hue Bridge
+- Shelly Gen 1 devices
+- Shelly Gen 2 devices
+- Devices using ESP Easy
+- Devices using Tasmota
+- Devices using the Node-RED dashboard
+- Devices using the SimpleHome API
+- Devices with a web interface
+
+Features
+- Control your Philips Hue lights
+- Live preview of the current light color
+- Create, rename and delete scenes
+- Add devices to your home screen
+- Add devices with a web interface (e.g. Router)
+
+How it works
+Communication between the devices uses HTTP requests and JSON strings. After the commanding device has send a HTTP request to the smart home device, the smart home device sends back a JSON string containing the information the app needs.
+This app is especially useful if you are using microcontrollers or other small devices such as the Raspberry Pi for smart home automation.
+
+Related Links
+Source code: https://github.com/Domi04151309/HomeApp
+Documentation: https://github.com/Domi04151309/HomeApp/wiki
+Icons8: https://icons8.com/
diff --git a/fastlane/metadata/android/en-US/images/featureGraphic.jpg b/fastlane/metadata/android/en-US/images/featureGraphic.jpg
new file mode 100644
index 0000000..dd0003c
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/featureGraphic.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/icon.png b/fastlane/metadata/android/en-US/images/icon.png
new file mode 100644
index 0000000..4c948ce
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/icon.png differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg
new file mode 100644
index 0000000..192fe3f
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/1.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg
new file mode 100644
index 0000000..5b6ac77
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/2.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg
new file mode 100644
index 0000000..398e3e0
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/3.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg
new file mode 100644
index 0000000..32fce3c
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/4.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg
new file mode 100644
index 0000000..601bac4
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/5.jpg differ
diff --git a/fastlane/metadata/android/en-US/images/phoneScreenshots/6.jpg b/fastlane/metadata/android/en-US/images/phoneScreenshots/6.jpg
new file mode 100644
index 0000000..323eeb8
Binary files /dev/null and b/fastlane/metadata/android/en-US/images/phoneScreenshots/6.jpg differ
diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt
new file mode 100644
index 0000000..f9b5d56
--- /dev/null
+++ b/fastlane/metadata/android/en-US/short_description.txt
@@ -0,0 +1 @@
+A little smart home app for Philips Hue, Arduino and other devices
diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt
new file mode 100644
index 0000000..e38a9b8
--- /dev/null
+++ b/fastlane/metadata/android/en-US/title.txt
@@ -0,0 +1 @@
+Home App | For Philips Hue, Arduino & more
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..e328724
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,23 @@
+# Enables namespacing of each library's R class so that its R class includes only the
+# resources declared in the library itself and none from the library's dependencies,
+# thereby reducing the size of the R class for that library
+android.nonTransitiveRClass=true
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+# AndroidX package structure to make it clearer which packages are bundled with the
+# Android operating system, and which are packaged with your app's APK
+# https://developer.android.com/topic/libraries/support-library/androidx-rn
+android.useAndroidX=true
+# Kotlin code style for this project: "official" or "obsolete":
+kotlin.code.style=official
+# Project-wide Gradle settings.
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..13372ae
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..1acfdab
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Thu Nov 05 18:03:47 CET 2020
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-all.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..9d82f78
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..8a0b282
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle.kts b/settings.gradle.kts
new file mode 100644
index 0000000..2ca0459
--- /dev/null
+++ b/settings.gradle.kts
@@ -0,0 +1,18 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+@Suppress("UnstableApiUsage")
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+include(":app")