Android app for the VW e-up! media unit API
Kotlin port of upXlink and MIBBridge: Bluetooth tunnel, registration with PIN and certificate check, TLS-PSK session, REST reads and writes, WebSocket events, demo car, English and German UI, CI with signed release builds on tags. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A.hearthforge-ci.toml
@@ -0,0 +1,85 @@
# Steps run in file order, in one container, sharing /ci/build.
image = "docker.io/library/debian:trixie"
work_dir = "/ci/build"
clone_project_to = "/ci/build/project"
shell_setup = """
set -euo pipefail
export ANDROID_HOME=/ci/cache/android-sdk
"""
timeout = 3600
memory_limit = "6g"
cache = [
{ path = "/ci/cache/android-sdk", max_size = "3g" },
{ path = "/root/.gradle", max_size = "4g" },
]
[on]
push = ["master"]
tag = true
[[steps]]
name = "setup"
timeout = 900
run_sh = """
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
openjdk-21-jdk-headless curl unzip ca-certificates > /dev/null
# Only for the license files. Gradle installs the platform and build-tools
# that the app needs on its own.
if [ ! -x "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" ]; then
curl -fsSL -o /tmp/clt.zip \
"https://dl.google.com/android/repository/commandlinetools-linux-15859902_latest.zip"
echo "040d3996a65543d22ec4bf73e4c37aa37a8d4af4 /tmp/clt.zip" | sha1sum -c -
unzip -q /tmp/clt.zip -d /tmp/clt
mkdir -p "$ANDROID_HOME/cmdline-tools"
mv /tmp/clt/cmdline-tools "$ANDROID_HOME/cmdline-tools/latest"
rm -r /tmp/clt /tmp/clt.zip
fi
(yes || true) | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null
java -version
"""
[[steps]]
name = "test"
timeout = 1800
run_sh = "cd project && ./gradlew --no-daemon testDebugUnitTest"
[[steps]]
name = "build"
timeout = 1800
run_sh = """
cd project
./gradlew --no-daemon assembleDebug
cp app/build/outputs/apk/debug/app-debug.apk /ci/build/upapp-debug.apk
"""
publish_file = ["/ci/build/upapp-debug.apk"]
# Needs the CI secrets ANDROID_KEYSTORE_BASE64 (base64 of a PKCS12 keystore)
# and ANDROID_KEYSTORE_PASSWORD. Releases must keep the same key: Android
# refuses an update signed with another key.
[[steps]]
name = "release"
run_if = 'test -n "${CI_COMMIT_TAG}"'
warn_on_fail = true
timeout = 1800
run_sh = """
if [ -z "${ANDROID_KEYSTORE_BASE64:-}" ] || [ -z "${ANDROID_KEYSTORE_PASSWORD:-}" ]; then
echo "WARNING: CI secrets ANDROID_KEYSTORE_BASE64 or ANDROID_KEYSTORE_PASSWORD missing. No signed release APK."
exit 1
fi
export ANDROID_KEYSTORE=/tmp/release.p12 ANDROID_KEY_ALIAS=upapp
printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 -d > "$ANDROID_KEYSTORE"
cd project
./gradlew --no-daemon assembleRelease
cp app/build/outputs/apk/release/app-release.apk /ci/build/upapp-release.apk
"""
publish_file = ["/ci/build/upapp-release.apk"]
[[steps]]
name = "lint"
warn_on_fail = true
run_sh = "cd project && ./gradlew --no-daemon lintDebug"
ALICENSE
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
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 AGPL, see <http://www.gnu.org/licenses/>.
APLAN.md
@@ -0,0 +1,77 @@
# upApp: upXlink as an Android app
Kotlin Android app that talks to the media unit of a VW e-up! (and Citigo e iV / Mii electric).
It reimplements two Python projects:
- MIBBridge: tunnel protocol over Bluetooth RFCOMM channel 5.
- upXlink: registration, TLS-PSK session, REST (VIWI) access, entity parsing.
## How the original works
1. Phone opens RFCOMM channel 5 to the car.
2. MIBBridge protocol multiplexes virtual TCP connections over that socket.
Segment header: `port u16le | type u8 | ...`. Types: TRANSMIT 0 (`len u16le` + data), OPEN 1 (`dst u16le`), CLOSE 2, HEARTBEAT 3 (echo it).
3. `GET http://car:80/car/info/vin` (plain HTTP) returns the VIN.
4. No stored credentials for that VIN: `POST http://car:80/auth/registration` returns 303 with `content-location`.
`GET https://car:443<location>` with TLS 1.2, `ECDHE-RSA-AES128-GCM-SHA256`, no cert check, legacy renegotiation allowed.
The user confirms a PIN on the car display. The body is `username,password`.
5. All further requests use TLS 1.2 with `PSK-AES128-CBC-SHA256` (identity = username, key = password).
6. REST endpoints: `/car/batteries`, `/car/info`, `/car/ranges`, `/chargingmanager/{providers,profiles,timers}`.
The first profile is the default profile. Departure times are UTC.
## Key technical decisions
- **TLS: BouncyCastle low-level API (`bctls`).** Android's Conscrypt (BoringSSL) has no `TLS_PSK_WITH_AES_128_CBC_SHA256`.
BC's `PSKTlsClient` supports it. BC also lets us skip cert checks and allow legacy renegotiation for registration.
- **No localhost TCP bridge.** MIBBridge listens on local ports so that `requests` can connect.
On Android we run TLS directly on the in-process tunnel streams. This removes ports, threads and the proxy layer.
- **Minimal HTTP/1.1 client** over the TLS stream (request line, headers, Content-Length or chunked body).
OkHttp cannot use a BC TLS-PSK stream.
- **JSON: `org.json`** (part of Android). No serialization library.
- **Credentials:** app-private SharedPreferences keyed by VIN. `allowBackup=false`.
- **Bluetooth:** pick from bonded devices, no scanning. Permission `BLUETOOTH_CONNECT` (API 31+).
Connect by the SDP service UUID from maps+more. See docs/maps-and-more.md.
- **UI:** Jetpack Compose, Material 3, single activity, coroutines on `Dispatchers.IO`.
- **License:** AGPL-3.0-or-later (EUPL-compatible). Attribution to upXlink and MIBBridge in the README.
## Files (target)
```
app/src/main/java/.../
Tunnel.kt MIBBridge segment codec, reader loop, heartbeat, virtual connection streams
Tls.kt BC TLS clients: registration (ECDHE-RSA) and session (PSK)
Http.kt minimal HTTP/1.1 request/response
Car.kt connect flow: VIN, credentials, registration, get/post
Model.kt Battery, Info, Range, ChargingManager parsing
MainActivity.kt Compose UI: device picker, dashboard, charging manager, raw GET/POST console
app/src/test/... codec test, parser tests (ported from upXlink fixtures)
```
## Phases
1. **Setup.** Android SDK, Gradle project, JDK 21.
2. **Transport.** Tunnel, TLS, HTTP, registration, raw GET/POST console. First car session: register and read `/`.
3. **Read parity.** Battery, range, info, charging manager. Unit tests with the upXlink fixtures.
4. **Roadmap items** (see below). Each needs car sessions.
5. **Docs.** README with protocol notes and the endpoint list we discover.
## Roadmap items from upXlink
| Item | Status | Needs |
|---|---|---|
| Charging manager write | Done | Tested in the car: timer edits, off-peak days, location create and delete. Location and options edits untested. |
| WebSocket events | Done | Tested in the car. |
| Cert check at registration | Done | Tested in the car. |
| PIN calculation | Done | Tested in the car. |
| Documentation | Done | README and docs/maps-and-more.md. |
| MediaControl | Open | Explore `/` and `/media/*` on the car. Scope depends on what the car exposes. |
| Infotainment keys | Open | Events arrive and are logged. Map keys to screens, like maps+more. |
| Missing location fields | Open | Temperature, min. level, more operations in the location editor. |
| Car clock sync | Open | maps+more sets the car date and time from the phone. |
| Release build | Open | R8, signing, Play listing. Debug logging of raw responses still on. |
## Debugging in the car
- Laptop to phone over USB or wireless adb: install, `logcat`, run the raw console.
- API exploration needs no new code: run upXlink on the laptop over the laptop's own Bluetooth.
- Optional: Bluetooth HCI snoop log of maps+more. Payloads are TLS encrypted, so value is limited.
AREADME.md
@@ -0,0 +1,45 @@
# upApp
Android app for the VW e-up! and its siblings (Škoda Citigo e iV, SEAT Mii electric).
It reads battery, range, car info and the charging manager over Bluetooth, like the discontinued maps+more app.
This is a Kotlin port of [upXlink](https://github.com/hahnworks/upXlink) and [MIBBridge](https://github.com/hahnworks/MIBBridge) by Alexander Hahn.
Those projects are licensed under EUPL-1.2. This port was created in October 2026 and is licensed under AGPL-3.0-or-later, an EUPL-compatible licence.
It is not associated with VWAG or its sub-brands.

## Status
- Tested in a 2020 e-up! with a Pixel 8a: registration, reads, live events, timer edits, off-peak days, adding and deleting locations.
- Edits of location fields and of the options are implemented but not yet tested in a car.
- `WRITES_ENABLED` in `MainActivity.kt` turns all writes off.
## How it talks to the car
1. Bluetooth RFCOMM to the car service `3728ED40-E416-11E4-80A0-0002A5D5C51B`. The MIBBridge protocol multiplexes virtual TCP connections over it.
2. `GET /car/info/vin` on port 80 without TLS.
3. First connection only: `POST /auth/registration` on port 80, then a TLS GET on port 443. The app checks the car certificate against the VW ViWi root CA. Phone and car show the same PIN. The user confirms it on the car. The car returns `user,password`.
4. All other requests: TLS 1.2 with `TLS_PSK_WITH_AES_128_CBC_SHA256` on port 443. Android's own TLS lacks this cipher, so the app uses BouncyCastle.
The car stores timer and off-peak times in UTC. The app shows them in local time.
Details from the maps+more app: [docs/maps-and-more.md](docs/maps-and-more.md).
## Demo mode
Pick "Demo car" in the device list. The app then talks to a simulated car inside the app (`Demo.kt`).
The demo car charges slowly and sends live events. Writes are enabled in demo mode.
The unit tests use the same simulated car.
## Build
```
./gradlew testDebugUnitTest assembleDebug
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
Requires Android 12 (API 31) or newer.
A signed release needs `ANDROID_KEYSTORE` (PKCS12 file), `ANDROID_KEYSTORE_PASSWORD` and `ANDROID_KEY_ALIAS` in the environment.
Without them, `assembleRelease` builds an unsigned APK. The CI builds the signed release on tags (`.hearthforge-ci.toml`).
Aapp/build.gradle.kts
@@ -0,0 +1,58 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.plugin.compose")
}
android {
namespace = "de.upapp"
compileSdk = 37
defaultConfig {
applicationId = "de.upapp"
minSdk = 31
targetSdk = 37
versionCode = 1
versionName = "0.1.0"
}
// Without ANDROID_KEYSTORE, assembleRelease builds an unsigned APK.
val keystore = providers.environmentVariable("ANDROID_KEYSTORE").orNull
val releaseSigning = keystore?.let {
signingConfigs.create("release") {
storeFile = file(it)
storePassword = providers.environmentVariable("ANDROID_KEYSTORE_PASSWORD").get()
keyAlias = providers.environmentVariable("ANDROID_KEY_ALIAS").get()
// PKCS12 has one password for the store and the key.
keyPassword = storePassword
}
}
buildTypes {
release { signingConfig = releaseSigning }
}
buildFeatures {
compose = true
buildConfig = true
}
testOptions { unitTests.isReturnDefaultValues = true }
packaging {
resources.excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
resources.pickFirsts += "META-INF/LICENSE.md"
}
}
dependencies {
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.material:material-icons-core:1.7.8")
implementation("androidx.activity:activity-compose:1.13.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
// Conscrypt has no TLS_PSK_WITH_AES_128_CBC_SHA256, the car's only session cipher.
implementation("org.bouncycastle:bctls-jdk18on:1.86.2")
testImplementation("junit:junit:4.13.2")
// android.jar only has org.json stubs.
testImplementation("org.json:json:20260814")
// Creates the test certificates for the registration handshake.
testImplementation("org.bouncycastle:bcpkix-jdk18on:1.86")
}
Aapp/src/main/AndroidManifest.xml
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:name="android.hardware.bluetooth" android:required="true" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<application
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Material.NoActionBar">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Aapp/src/main/java/de/upapp/Car.kt
@@ -0,0 +1,110 @@
package de.upapp
import android.content.SharedPreferences
import android.util.Log
import androidx.core.content.edit
import org.bouncycastle.tls.AlertDescription
import org.bouncycastle.tls.TlsClientProtocol
import org.bouncycastle.tls.TlsFatalAlertReceived
import org.json.JSONObject
import java.io.IOException
// Host headers as maps+more sends them through its local port mapping.
private const val HTTP_HOST = "127.0.0.1:4080"
internal const val HTTPS_HOST = "127.0.0.1:4443"
// The car answers only after the user confirms the PIN on its display.
private const val REGISTRATION_TIMEOUT_MS = 120_000L
/** REST access to the car. [credentials] stores one `user,password` pair per VIN. */
class Car(internal val tunnel: Tunnel, private val credentials: SharedPreferences) {
lateinit var vin: String
private set
internal lateinit var psk: Pair<String, String>
private set
/** Reads the VIN, registers if needed and opens a session. [onPin] gets the PIN that the car display shows. */
fun connect(onPin: (String) -> Unit) {
val r = plain("GET", "/car/info/vin")
if (r.status != 200) throw IOException("Reading the VIN failed: HTTP ${r.status}")
vin = r.text.trim()
val stored = credentials.getString(vin, null)
psk = parseCredentials(stored ?: register(onPin))
if (stored == null) credentials.edit { putString(vin, "${psk.first},${psk.second}") }
try {
get("/")
} catch (e: TlsFatalAlertReceived) {
credentials.edit { remove(vin) }
throw IOException("The car rejected the stored key (${AlertDescription.getText(e.alertDescription)}). Connect again to register.", e)
}
}
fun get(path: String): String = send("GET", path).ok().text
fun post(path: String, json: JSONObject): String = send("POST", path, json.toString().encodeToByteArray()).ok().text
/** Raw request over the authenticated session. Does not check the status. */
@Synchronized
fun send(method: String, path: String, body: ByteArray? = null): Response {
val reused = session != null
val s = session ?: Session(tunnel.open(443))
session = null
val r = try {
exchange(s.tls.inputStream, s.tls.outputStream, method, HTTPS_HOST, "/" + path.trimStart('/'), body, keepAlive = true)
} catch (e: IOException) {
s.close()
// The car may have closed the idle connection. The retry opens a fresh one.
if (reused) return send(method, path, body)
throw e
}
if (r.reusable) session = s else s.close()
if (BuildConfig.DEBUG) Log.d("Http", "$method $path -> ${r.status} ${r.text.take(3000)}")
return r
}
private var session: Session? = null
private inner class Session(val channel: Tunnel.Channel) {
val tls = try {
sessionTls(channel.input, channel.output, psk.first, psk.second)
} catch (e: IOException) {
channel.close()
throw e
}
fun close() {
runCatching { tls.close() }
channel.close()
}
}
private fun register(onPin: (String) -> Unit): String {
val r = plain("POST", "/auth/registration", ByteArray(0))
if (r.status != 303) throw IOException("Registration failed: expected HTTP 303, got ${r.status}")
val location = r.headers["content-location"] ?: throw IOException("Registration failed: no content-location header")
return tunnel.open(443, REGISTRATION_TIMEOUT_MS).use { ch ->
val (tls, pin) = registrationTls(ch.input, ch.output)
onPin(pin)
tls.exchangeAndClose("GET", location, null)
}.ok().text
}
private fun plain(method: String, path: String, body: ByteArray? = null) =
tunnel.open(80).use { exchange(it.input, it.output, method, HTTP_HOST, path, body) }
private fun TlsClientProtocol.exchangeAndClose(method: String, path: String, body: ByteArray?) =
try {
exchange(inputStream, outputStream, method, HTTPS_HOST, path, body)
} finally {
runCatching { close() }
}
internal fun Response.ok() = apply {
if (status !in 200..299) throw IOException("HTTP $status: ${text.take(200)}")
}
}
internal fun parseCredentials(s: String): Pair<String, String> {
val parts = s.trim().split(',')
if (parts.size != 2) throw IOException("Invalid credentials from the car")
return parts[0] to parts[1]
}
Aapp/src/main/java/de/upapp/Demo.kt
@@ -0,0 +1,249 @@
package de.upapp
import org.bouncycastle.tls.CipherSuite
import org.bouncycastle.tls.PSKTlsServer
import org.bouncycastle.tls.ProtocolVersion
import org.bouncycastle.tls.TlsPSKIdentityManager
import org.bouncycastle.tls.TlsServerProtocol
import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto
import org.json.JSONArray
import org.json.JSONObject
import java.io.DataInputStream
import java.io.EOFException
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.security.SecureRandom
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.concurrent.thread
const val DEMO_VIN = "WVWZZZAAZLD000042"
const val DEMO_CREDENTIALS = "demo,demo"
/** Car end of a tunnel, for the demo and tests. [serve] handles each connection that the phone opens. */
class CarSide(serve: (port: Int, InputStream, OutputStream) -> Unit) {
private val toPhone = Pipe()
private val toCar = Pipe()
val tunnel = Tunnel(toPhone.input, toCar.output)
init {
thread(isDaemon = true, name = "car") {
val pipes = ConcurrentHashMap<Int, Pipe>()
val chunk = ByteArray(4096)
var buf = ByteArray(0)
while (true) {
val n = toCar.input.read(chunk)
if (n < 0) break
buf += chunk.copyOf(n)
while (true) {
val (s, size) = decode(buf) ?: break
buf = buf.copyOfRange(size, buf.size)
when (s.type) {
HEARTBEAT -> toPhone.put(frame(0, HEARTBEAT))
OPEN -> {
val pipe = Pipe().also { pipes[s.port] = it }
val remote = (s.data[0].toInt() and 0xFF) or ((s.data[1].toInt() and 0xFF) shl 8)
val out = object : OutputStream() {
override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
override fun write(b: ByteArray, off: Int, len: Int) =
toPhone.put(frame(s.port, TRANSMIT, u16(len) + b.copyOfRange(off, off + len)))
}
thread(isDaemon = true) {
try {
serve(remote, pipe.input, out)
} catch (_: Exception) {
}
if (pipes.remove(s.port) != null) toPhone.put(frame(s.port, CLOSE))
}
}
TRANSMIT -> pipes[s.port]?.put(s.data)
CLOSE -> pipes.remove(s.port)?.end() ?: Unit
}
}
}
pipes.values.forEach { it.end() }
}
}
}
private class Request(val method: String, val path: String, val headers: Map<String, String>, val body: String)
private fun readRequest(input: InputStream): Request? {
val first = try {
input.line()
} catch (_: EOFException) {
return null
}
val (method, path) = first.split(' ')
val headers = generateSequence { input.line().ifEmpty { null } }
.associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() }
val body = ByteArray(headers["content-length"]?.toInt() ?: 0).also { DataInputStream(input).readFully(it) }
return Request(method, path, headers, body.decodeToString())
}
private fun respond(out: OutputStream, status: Int, body: Any? = null, headers: List<String> = emptyList()) {
val text = body?.toString().orEmpty().toByteArray()
val head = (listOf("HTTP/1.1 $status X", "Content-Length: ${text.size}") + headers).joinToString("\r\n") + "\r\n\r\n"
out.write(head.toByteArray() + text)
out.flush()
}
/** A simulated e-up! that serves the REST API and events in memory. */
class DemoCar {
private val docs = LinkedHashMap<String, JSONObject>()
private val listeners = CopyOnWriteArrayList<OutputStream>()
val tunnel = CarSide(::serve).tunnel
init {
val now = LocalDateTime.now()
add("/car/info/", "info", "vehicleIdenticationNumber" to DEMO_VIN, "vehicleType" to "VW120", "language" to "de",
"vehicleDate" to now.format(DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH)),
"vehicleTime" to now.format(DateTimeFormatter.ofPattern("HH:mm:ss")))
add("/car/batteries/", "BEV battery", "soc" to 64.0, "socUnit" to "percent")
add("/car/ranges/", "BEV range", "value" to 151.0, "valueUnit" to "km")
add("/car/environments/", "environment", "outsideTemperature" to 12.5, "outsideTemperatureUnit" to "celsius", "lightIntensity" to 40)
add("/chargingmanager/batteryCharges/", "batteryCharge", "state" to "running")
add("/chargingmanager/batteryPlugs/", "batteryPlug", "plug" to "plugged")
add("/chargingmanager/batteryClimates/", "batteryClimate", "state" to "idle")
add("/chargingmanager/profiles/", "Optionen", "operations" to JSONArray(listOf("climateExtSupply", "climate")),
"maxCurrent" to 16, "minLevel" to 30, "targetLevel" to 0, "temperature" to 21.5)
val home = createProfile("Zuhause", 80, 16, listOf("charge", "climate"))
val work = createProfile("Arbeit", 100, 10, listOf("charge"))
add("/chargingmanager/timers/", "Timer1", "state" to TIMER_ON, "departureTime" to "05:30:00", "cyclic" to true,
"weekdays" to JSONArray(listOf("monday", "tuesday", "wednesday", "thursday", "friday")), "profile" to link(home))
add("/chargingmanager/timers/", "Timer2", "state" to TIMER_OFF, "departureTime" to "08:00:00", "cyclic" to true,
"weekdays" to JSONArray(listOf("saturday")), "profile" to link(work))
add("/chargingmanager/timers/", "Timer3", "state" to TIMER_OFF, "departureTime" to "16:45:00", "cyclic" to false,
"departureDate" to now.plusDays(3).format(DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH)),
"weekdays" to JSONArray(), "profile" to link(home))
thread(isDaemon = true, name = "demo charging") { simulateCharging() }
}
private fun add(collection: String, name: String, vararg fields: Pair<String, Any>): JSONObject {
val id = UUID.randomUUID().toString()
val doc = JSONObject().put("id", id).put("name", name).put("uri", collection + id)
fields.forEach { (k, v) -> doc.put(k, v) }
docs[doc.getString("uri")] = doc
return doc
}
private fun createProfile(name: String, target: Int, current: Int, operations: List<String>): JSONObject {
val provider = add("/chargingmanager/providers/", "", "cyclic" to true, "preferredTimeStart" to "21:00:00",
"preferredTimeEnd" to "05:00:00", "weekdays" to JSONArray(listOf("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday")))
return add("/chargingmanager/profiles/", name, "operations" to JSONArray(operations), "maxCurrent" to current,
"minLevel" to 0, "targetLevel" to target, "temperature" to 21.0, "powerProvider" to link(provider))
}
private fun link(doc: JSONObject) = JSONObject().put("id", doc["id"]).put("name", doc["name"]).put("uri", doc["uri"])
private fun collection(path: String) = JSONArray(docs.filterKeys { it.startsWith(path) && it != path }.values)
private fun first(collection: String) = docs.entries.first { it.key.startsWith(collection) }.value
private fun simulateCharging() {
while (true) {
Thread.sleep(3_000)
synchronized(this) {
val charge = first("/chargingmanager/batteryCharges/")
if (charge["state"] != "running") return@synchronized
val battery = first("/car/batteries/")
val soc = battery.getDouble("soc") + 1
battery.put("soc", soc)
first("/car/ranges/").put("value", (soc * 2.4).toInt().toDouble())
if (soc >= 80) charge.put("state", "completed")
listOf("/car/batteries/", "/car/ranges/", "/chargingmanager/batteryCharges/").forEach(::notify)
}
}
}
private fun notify(collection: String) {
val message = JSONObject().put("type", "data").put("event", "$collection#42").put("data", collection(collection))
listeners.forEach { out ->
runCatching { writeFrame(out, WS_TEXT, message.toString().toByteArray(), mask = false) }.onFailure { listeners.remove(out) }
}
}
private fun serve(port: Int, input: InputStream, output: OutputStream) {
if (port == 80) {
val r = readRequest(input) ?: return
if (r.path == "/car/info/vin") respond(output, 200, DEMO_VIN) else respond(output, 404)
return
}
val tls = TlsServerProtocol(input, output)
tls.accept(object : PSKTlsServer(BcTlsCrypto(SecureRandom()), object : TlsPSKIdentityManager {
override fun getHint(): ByteArray = DEMO_VIN.toByteArray()
override fun getPSK(identity: ByteArray) = DEMO_CREDENTIALS.substringAfter(',').toByteArray()
}) {
override fun getSupportedVersions(): Array<ProtocolVersion> = ProtocolVersion.TLSv12.only()
override fun getSupportedCipherSuites() = intArrayOf(CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256)
})
val inp = tls.inputStream
val out = tls.outputStream
while (true) {
val r = readRequest(inp) ?: break
if (r.headers["upgrade"].equals("websocket", ignoreCase = true)) {
respond(out, 101, null, listOf("Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: ${wsAccept(r.headers.getValue("sec-websocket-key"))}"))
events(inp, out)
break
}
synchronized(this) { handle(r, out) }
}
tls.close()
}
private fun events(input: InputStream, output: OutputStream) {
listeners.add(output)
try {
while (true) {
val (_, data) = readMessage(input, output, mask = false)
val m = JSONObject(data.decodeToString())
val reply = JSONObject().put("type", m.getString("type")).put("event", m.getString("event")).put("status", "ok")
writeFrame(output, WS_TEXT, reply.toString().toByteArray(), mask = false)
}
} finally {
listeners.remove(output)
}
}
private fun handle(r: Request, out: OutputStream) {
val path = r.path
val doc = docs[path]
when {
r.method == "GET" && path == "/" -> respond(out, 200, JSONObject())
r.method == "GET" && doc != null -> respond(out, 200, JSONObject().put("status", "ok").put("data", doc))
r.method == "GET" && path.endsWith("/") && docs.keys.any { it.startsWith(path) } -> respond(out, 200, JSONObject().put("data", collection(path)))
r.method == "POST" && path == "/chargingmanager/profiles/" -> {
val b = JSONObject(r.body)
val created = createProfile(b.getString("name"), b.getInt("targetLevel"), b.getInt("maxCurrent"),
b.getJSONArray("operations").let { a -> List(a.length()) { a.getString(it) } })
respond(out, 201, created)
notify("/chargingmanager/profiles/")
notify("/chargingmanager/providers/")
}
r.method == "POST" && doc != null -> {
val b = JSONObject(r.body)
b.keys().forEach { k ->
val v = b.get(k)
val target = (v as? String)?.let { id -> docs.values.firstOrNull { it.optString("id") == id } }
doc.put(k, if (k in setOf("profile", "powerProvider") && target != null) link(target) else v)
}
respond(out, 200, JSONObject().put("status", "ok"))
notify(path.substringBeforeLast('/') + "/")
}
r.method == "DELETE" && doc != null -> {
docs.remove(path)
doc.optJSONObject("powerProvider")?.let { docs.remove(it.getString("uri")) }
respond(out, 200)
notify("/chargingmanager/profiles/")
notify("/chargingmanager/providers/")
}
else -> respond(out, 404)
}
}
}
Aapp/src/main/java/de/upapp/Http.kt
@@ -0,0 +1,88 @@
package de.upapp
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.EOFException
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
/** [reusable] is true if the connection can carry the next request. */
class Response(val status: Int, val headers: Map<String, String>, val body: ByteArray, val reusable: Boolean = false) {
val text get() = body.decodeToString()
}
/** Sends one HTTP/1.1 request and reads the response. Header names are lower case. */
fun exchange(
input: InputStream, output: OutputStream, method: String, host: String, path: String, body: ByteArray? = null,
keepAlive: Boolean = false, extraHeaders: List<String> = emptyList(),
): Response {
val head = buildString {
append("$method $path HTTP/1.1\r\nHost: $host\r\n")
if (!keepAlive) append("Connection: close\r\n")
extraHeaders.forEach { append("$it\r\n") }
if (body != null) {
// Same type as maps+more. Other types are untested on the car.
if (body.isNotEmpty()) append("Content-Type: text/plain; charset=UTF-8\r\n")
append("Content-Length: ${body.size}\r\n")
}
append("\r\n")
}
output.write(head.encodeToByteArray() + (body ?: ByteArray(0)))
output.flush()
// No buffering. Read-ahead would swallow the start of the next response on a reused connection.
val inp = DataInputStream(input)
val statusLine = inp.line()
val status = statusLine.split(' ').getOrNull(1)?.toIntOrNull() ?: throw IOException("Bad status line: $statusLine")
val headers = generateSequence { inp.line().ifEmpty { null } }
.associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() }
val length = headers["content-length"]?.toInt()
var framed = true
val bytes = when {
headers["transfer-encoding"]?.contains("chunked", ignoreCase = true) == true -> inp.chunked()
length != null -> ByteArray(length).also { inp.readFully(it) }
status in 100..199 || status == 204 || status == 304 -> ByteArray(0)
else -> inp.untilEof().also { framed = false }
}
val reusable = keepAlive && framed && !headers["connection"].equals("close", ignoreCase = true)
return Response(status, headers, bytes, reusable)
}
internal fun InputStream.line(): String {
val out = ByteArrayOutputStream()
while (true) {
val c = read()
if (c < 0) throw EOFException("Connection closed in HTTP header")
if (c == '\n'.code) break
out.write(c)
}
return out.toString(Charsets.ISO_8859_1.name()).trimEnd('\r')
}
private fun DataInputStream.chunked(): ByteArray {
val out = ByteArrayOutputStream()
while (true) {
val size = line().substringBefore(';').trim().toInt(16)
if (size == 0) break
out.write(ByteArray(size).also { readFully(it) })
line()
}
while (line().isNotEmpty()) Unit
return out.toByteArray()
}
private fun InputStream.untilEof(): ByteArray {
val out = ByteArrayOutputStream()
val buf = ByteArray(4096)
try {
while (true) {
val n = read(buf)
if (n < 0) break
out.write(buf, 0, n)
}
} catch (_: EOFException) {
// A peer that closes without TLS close_notify still ends the body.
}
return out.toByteArray()
}
Aapp/src/main/java/de/upapp/MainActivity.kt
@@ -0,0 +1,416 @@
package de.upapp
import android.Manifest
import android.annotation.SuppressLint
import android.app.Application
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.StringRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.content.edit
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.util.UUID
/** Turns all writes off. The car test on 2026-10-07 covered only the timer state. */
const val WRITES_ENABLED = true
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
val scheme = if (isSystemInDarkTheme()) dynamicDarkColorScheme(this) else dynamicLightColorScheme(this)
MaterialTheme(colorScheme = scheme) { App(viewModel()) }
}
}
}
class MainViewModel(app: Application) : AndroidViewModel(app) {
private val credentials = app.getSharedPreferences("credentials", Context.MODE_PRIVATE)
private var socket: BluetoothSocket? = null
private var tunnel: Tunnel? = null
/** Addresses of devices that connected as a car before. */
var knownCars: Set<String> = credentials.getStringSet(KNOWN_CARS, null).orEmpty()
private set
var deviceName by mutableStateOf("")
private set
var connecting by mutableStateOf(false)
private set
var pin by mutableStateOf<String?>(null)
private set
var busy by mutableStateOf(false)
private set
var car by mutableStateOf<Car?>(null)
private set
var snack by mutableStateOf<String?>(null)
var battery by mutableStateOf<Battery?>(null)
private set
var range by mutableStateOf<Range?>(null)
private set
var info by mutableStateOf<Info?>(null)
private set
var charging by mutableStateOf<ChargingManager?>(null)
private set
var status by mutableStateOf<Status?>(null)
private set
var demo by mutableStateOf(false)
private set
val writesEnabled get() = WRITES_ENABLED || demo
var consoleOut by mutableStateOf("")
private set
@SuppressLint("MissingPermission")
fun connect(device: BluetoothDevice) {
deviceName = device.name ?: device.address
connecting = true
launch {
val s = openRfcomm(device).also { socket = it }
start(Car(Tunnel(s.inputStream, s.outputStream).also { tunnel = it }, credentials))
knownCars = knownCars + device.address
credentials.edit { putStringSet(KNOWN_CARS, knownCars) }
}
}
fun connectDemo() {
deviceName = str(R.string.demo_car)
demo = true
connecting = true
launch {
val prefs = getApplication<Application>().getSharedPreferences("demo", Context.MODE_PRIVATE)
prefs.edit { putString(DEMO_VIN, DEMO_CREDENTIALS) }
start(Car(DemoCar().tunnel.also { tunnel = it }, prefs))
}
}
private fun start(c: Car) {
c.connect { pin = it }
if (pin != null) snack = str(R.string.registered, c.vin)
car = c
load(c)
viewModelScope.launch(Dispatchers.IO) {
while (car === c) {
try {
val inputs = inputs(c)
c.listen(EVENT_PATHS + inputs.keys) { path, data ->
val input = inputs[path]
if (input != null) onInput(input, data) else viewModelScope.launch(Dispatchers.IO) { reload(c, path) }
}
} catch (e: Exception) {
if (car === c) Log.w("upApp", "Event connection ended", e)
}
delay(5_000)
}
}
}
private fun update(c: Car, path: String) {
when (path) {
"/car/batteries/" -> battery = c.battery()
"/car/ranges/" -> range = c.range()
in STATUS_PATHS -> status = c.status()
else -> charging = c.chargingManager()
}
}
private fun reload(c: Car, path: String) = try {
update(c, path)
} catch (e: Exception) {
Log.w("upApp", "Reload of $path failed", e)
}
fun refresh() {
val c = car ?: return
launch { load(c) }
}
fun save(write: Car.() -> Unit) {
val c = car ?: return
launch {
c.write()
charging = c.chargingManager()
snack = str(R.string.saved)
}
}
fun console(method: String, path: String, body: String?) {
val c = car ?: return
launch {
val r = c.send(method, path, body?.let { JSONObject(it).toString().encodeToByteArray() })
consoleOut = "HTTP ${r.status}\n${pretty(r.text)}"
}
}
fun disconnect() {
car = null
runCatching { socket?.close() }
tunnel?.close()
socket = null
tunnel = null
demo = false
status = null
battery = null
range = null
info = null
charging = null
consoleOut = ""
}
override fun onCleared() = disconnect()
/** Loads every group. A failing group does not stop the others. Throws the first error at the end. */
private fun load(c: Car) {
info = c.info()
listOf("/car/batteries/", "/car/ranges/", STATUS_PATHS[0], "/chargingmanager/profiles/")
.mapNotNull { runCatching { update(c, it) }.exceptionOrNull() }
.firstOrNull()?.let { throw it }
}
private fun launch(block: () -> Unit) = viewModelScope.launch(Dispatchers.IO) {
busy = true
try {
block()
} catch (e: Exception) {
Log.e("upApp", "Request failed", e)
snack = str(R.string.error, e.message ?: e.javaClass.simpleName)
if (car == null) disconnect()
} finally {
busy = false
connecting = false
pin = null
}
}
private fun str(@StringRes id: Int, vararg args: Any) = getApplication<Application>().getString(id, *args)
}
private const val KNOWN_CARS = "known cars"
private val TUNNEL_SERVICE = UUID.fromString("3728ED40-E416-11E4-80A0-0002A5D5C51B")
// Same attempts and back-off as maps+more. The first connect after pairing often fails.
@SuppressLint("MissingPermission")
private fun openRfcomm(device: BluetoothDevice): BluetoothSocket {
for (attempt in 1..4) {
val socket = device.createRfcommSocketToServiceRecord(TUNNEL_SERVICE)
try {
socket.connect()
return socket
} catch (e: IOException) {
socket.close()
if (attempt == 4) throw e
Log.w("upApp", "Bluetooth connect attempt $attempt failed", e)
Thread.sleep(2_000L * attempt)
}
}
error("unreachable")
}
private fun pretty(text: String) =
runCatching { JSONObject(text).toString(2) }.recoverCatching { JSONArray(text).toString(2) }.getOrDefault(text)
private val STATUS_PATHS = listOf(
"/chargingmanager/batteryCharges/", "/chargingmanager/batteryPlugs/", "/chargingmanager/batteryClimates/", "/car/environments/",
)
private val EVENT_PATHS = listOf(
"/car/batteries/", "/car/ranges/", "/chargingmanager/timers/", "/chargingmanager/profiles/", "/chargingmanager/providers/",
) + STATUS_PATHS
/** Infotainment keys and knobs by element URI. Each one needs its own subscription, like in maps+more. */
private fun inputs(c: Car): Map<String, String> = listOf("/mechanicalinput/buttons/", "/mechanicalinput/rotarypushes/").flatMap { path ->
runCatching {
val items = JSONObject(c.get(path)).getJSONArray("data")
List(items.length()) { items.getJSONObject(it) }.map { it.getString("uri") to it.optString("meaning").ifEmpty { it.optString("name") } }
}.getOrDefault(emptyList())
}.toMap()
// TODO: only logged for now. maps+more opens the screen that matches the pressed key.
private fun onInput(name: String, data: Any?) {
val o = (data as? JSONObject) ?: (data as? org.json.JSONArray)?.optJSONObject(0)
Log.i("Input", "$name: state=${o?.optString("state")} ticks=${o?.opt("ticks")}")
}
private val TABS = listOf(R.string.tab_overview to Icons.Default.Home, R.string.tab_charging to Icons.Default.DateRange, R.string.tab_console to Icons.Default.Build)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun App(vm: MainViewModel) {
val snackbar = remember { SnackbarHostState() }
LaunchedEffect(vm.snack) {
vm.snack?.let {
snackbar.showSnackbar(it)
vm.snack = null
}
}
var tab by rememberSaveable { mutableIntStateOf(0) }
val car = vm.car
Scaffold(
topBar = {
if (car != null) TopAppBar(
title = {
Column {
Text(vm.deviceName)
Text(stringResource(R.string.connected_vin, car.vin), style = MaterialTheme.typography.bodySmall)
}
},
actions = {
IconButton(onClick = vm::refresh, enabled = !vm.busy) { Icon(Icons.Default.Refresh, stringResource(R.string.refresh)) }
IconButton(onClick = vm::disconnect) { Icon(Icons.Default.Close, stringResource(R.string.disconnect)) }
},
)
},
bottomBar = {
if (car != null) NavigationBar {
TABS.forEachIndexed { i, (label, icon) ->
NavigationBarItem(selected = tab == i, onClick = { tab = i }, icon = { Icon(icon, null) }, label = { Text(stringResource(label)) })
}
}
},
snackbarHost = { SnackbarHost(snackbar) },
) { padding ->
Box(Modifier.padding(padding).fillMaxSize()) {
when {
vm.pin != null -> PinScreen(vm.pin!!, vm::disconnect)
vm.connecting -> Waiting(stringResource(R.string.connecting, vm.deviceName))
car == null -> DevicePicker(vm.knownCars, vm::connect, vm::connectDemo)
tab == 0 -> Overview(vm)
tab == 1 -> Charging(vm)
else -> Console(vm)
}
if (vm.busy && car != null) LinearProgressIndicator(Modifier.fillMaxWidth())
}
}
}
@SuppressLint("MissingPermission")
@Composable
private fun DevicePicker(known: Set<String>, onPick: (BluetoothDevice) -> Unit, onDemo: () -> Unit) {
val ctx = LocalContext.current
var granted by remember { mutableStateOf(ctx.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted = it }
Column(Modifier.verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(R.string.select_car), style = MaterialTheme.typography.headlineSmall)
if (!granted) {
Text(stringResource(R.string.bt_permission))
Button(onClick = { launcher.launch(Manifest.permission.BLUETOOTH_CONNECT) }) { Text(stringResource(R.string.allow_bluetooth)) }
} else {
Text(stringResource(R.string.select_car_hint), color = MaterialTheme.colorScheme.onSurfaceVariant)
val devices = remember {
ctx.getSystemService(BluetoothManager::class.java).adapter?.bondedDevices.orEmpty().sortedBy { it.name }
}
if (devices.isEmpty()) Text(stringResource(R.string.no_devices))
// A car is a device that connected before, or one that offers the tunnel service.
val (cars, others) = devices.partition { d -> d.address in known || d.uuids.orEmpty().any { it.uuid == TUNNEL_SERVICE } }
listOf(R.string.your_cars to cars, R.string.other_devices to others).filter { it.second.isNotEmpty() }.forEach { (title, list) ->
Text(stringResource(title), style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
list.forEach { d ->
ListItem(
headlineContent = { Text(d.name ?: d.address) },
supportingContent = { Text(d.address, fontFamily = FontFamily.Monospace) },
modifier = Modifier.clickable { onPick(d) },
)
}
}
}
HorizontalDivider()
ListItem(
headlineContent = { Text(stringResource(R.string.demo_car)) },
supportingContent = { Text(stringResource(R.string.demo_car_hint)) },
modifier = Modifier.clickable(onClick = onDemo),
)
}
}
@Composable
internal fun Waiting(text: String?) = Column(
Modifier.fillMaxSize().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
CircularProgressIndicator()
text?.let { Text(it) }
}
@Composable
private fun PinScreen(pin: String, onCancel: () -> Unit) = Column(
Modifier.fillMaxSize().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.confirm_pin_title), style = MaterialTheme.typography.titleLarge)
InfoButton(Topic.PIN)
}
Text(stringResource(R.string.confirm_pin_text), textAlign = TextAlign.Center)
Text(pin.chunked(3).joinToString(" "), style = MaterialTheme.typography.displayLarge, fontFamily = FontFamily.Monospace)
Text(stringResource(R.string.pin_note), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodySmall)
CircularProgressIndicator()
TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) }
}
Aapp/src/main/java/de/upapp/Model.kt
@@ -0,0 +1,271 @@
package de.upapp
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
/** [soc] and [value] are null while the car has no reading. It then sends an empty string. */
data class Battery(val name: String, val soc: Double?)
data class Range(val name: String, val value: Double?, val unit: String)
data class Info(val vin: String, val date: String, val time: String, val type: String, val language: String)
/** Departure timer. The car stores [departureTime] in UTC. */
data class Timer(
val id: String, val uri: String, val index: Int, val state: String, val cyclic: Boolean,
val weekdays: Set<DayOfWeek>, val departureTime: LocalTime, val departureDate: LocalDate?, val profileId: String?,
) {
val active get() = state == TIMER_ON
}
/** Charging location. */
data class Profile(
val id: String, val uri: String, val name: String, val targetLevel: Int, val maxCurrent: Int,
val operations: List<String>, val providerId: String?,
)
/** Global charging options. The car returns them as the first profile. */
data class Options(
val id: String, val uri: String, val operations: List<String>, val maxCurrent: Int, val minLevel: Int, val temperature: Double,
val providerId: String? = null,
) {
val climateExtSupply get() = EXT_SUPPLY in operations
}
/** Off-peak power time window. The car stores [start] and [end] in UTC. */
data class Provider(val id: String, val uri: String, val cyclic: Boolean, val weekdays: Set<DayOfWeek>, val start: LocalTime, val end: LocalTime) {
// maps+more has no off switch. An empty window is off, and the car uses that for unset entries.
val active get() = start != end
fun off() = copy(start = LocalTime.MIDNIGHT, end = LocalTime.MIDNIGHT)
}
/** Live state. Values are the car's raw strings, null if the car does not report them. */
data class Status(
val charge: String?, val plug: String?, val climate: String?, val outsideTemperature: Double?, val temperatureUnit: String?,
val chargeMode: String? = null, val remainingMinutes: Int? = null,
)
/** [options] is null while the car reports no profiles. */
data class ChargingManager(val options: Options?, val profiles: List<Profile>, val timers: List<Timer>, val providers: List<Provider>)
const val TIMER_ON = "scheduled"
const val TIMER_OFF = "idle"
const val EXT_SUPPLY = "climateExtSupply"
// The values maps+more knows. The car also lists climateExtSupply and charge on normal locations and options.
val OPERATIONS = setOf(
"charge", "climate", EXT_SUPPLY, "autoDefrost", "SeatHeaterFrontLeft", "SeatHeaterFrontRight", "SeatHeaterRearLeft",
"SeatHeaterRearRight", "WindowHeaterFront", "WindowHeaterRear", "ParkHeater", "ParkHeaterAutomatic",
)
val TARGET_LEVELS = (50..100 step 10).toList()
val MIN_LEVELS = (0..100 step 10).toList()
// maps+more rule: 32 A only for the e-up! 300, i.e. VW model year L (2020) or later, and all other brands.
fun maxCurrents(vin: String) =
if (!vin.uppercase().startsWith("WVW") || vin.getOrElse(9) { 'A' }.uppercaseChar() >= 'L') listOf(5, 10, 13, 16, 32) else listOf(5, 10, 13, 16)
val TEMPERATURES = (31..60).map { it / 2.0 }
// maps+more allows this many locations besides the options entry.
const val MAX_LOCATIONS = 10
// TODO: guessed limit. maps+more has none. Check the longest name the car accepts.
const val NAME_MAX = 20
private val HMS = DateTimeFormatter.ofPattern("HH:mm:ss")
private val DATE_IN = DateTimeFormatter.ofPattern("d MMM yyyy", Locale.ENGLISH)
private val DATE_OUT = DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH)
private fun JSONObject.list(key: String): List<String> =
optJSONArray(key)?.let { a -> List(a.length()) { a.getString(it) } } ?: emptyList()
private fun JSONObject.days() = list("weekdays").map { DayOfWeek.valueOf(it.uppercase()) }.toSet()
private fun JSONObject.linkId(key: String) = optJSONObject(key)?.optString("id")?.ifEmpty { null }
private fun Set<DayOfWeek>.toJson() = JSONArray(sorted().map { it.name.lowercase() })
private fun JSONObject.number(key: String) = optDouble(key).takeUnless { it.isNaN() }
fun parseBattery(o: JSONObject) = Battery(o.optString("name"), o.number("soc"))
fun parseRange(o: JSONObject) = Range(o.optString("name"), o.number("value"), o.optString("valueUnit"))
fun parseInfo(o: JSONObject) = Info(
o.optString("vehicleIdenticationNumber"), o.optString("vehicleDate"), o.optString("vehicleTime"),
o.optString("vehicleType"), o.optString("language"),
)
fun parseTimer(o: JSONObject) = Timer(
id = o.getString("id"),
uri = o.getString("uri"),
index = o.getString("name").last().digitToInt(),
state = o.getString("state"),
cyclic = o.optBoolean("cyclic"),
weekdays = o.days(),
departureTime = LocalTime.parse(o.getString("departureTime"), HMS),
departureDate = o.optString("departureDate").ifEmpty { null }?.let { LocalDate.parse(it, DATE_IN) },
profileId = o.linkId("profile"),
)
fun parseProfile(o: JSONObject) = Profile(
o.getString("id"), o.getString("uri"), o.getString("name"), o.getInt("targetLevel"), o.getInt("maxCurrent"),
o.list("operations"), o.linkId("powerProvider"),
)
fun parseOptions(o: JSONObject) = Options(
o.getString("id"), o.getString("uri"), o.list("operations"), o.getInt("maxCurrent"), o.getInt("minLevel"), o.getDouble("temperature"),
)
fun parseProvider(o: JSONObject) = Provider(
o.getString("id"), o.getString("uri"), o.optBoolean("cyclic"), o.days(),
LocalTime.parse(o.getString("preferredTimeStart"), HMS), LocalTime.parse(o.getString("preferredTimeEnd"), HMS),
)
private fun Car.items(path: String): List<JSONObject> =
JSONObject(get(path)).getJSONArray("data").let { a -> List(a.length()) { a.getJSONObject(it) } }
fun Car.battery() = parseBattery(items("/car/batteries/").first())
fun Car.range() = parseRange(items("/car/ranges/").first())
fun Car.info() = parseInfo(items("/car/info/").first())
fun Car.status(): Status {
fun first(path: String) = try {
items(path).firstOrNull()
} catch (e: IOException) {
null
}
val env = first("/car/environments/")
val charge = first("/chargingmanager/batteryCharges/")
return Status(
charge?.optString("state"),
first("/chargingmanager/batteryPlugs/")?.optString("plug"),
first("/chargingmanager/batteryClimates/")?.optString("state"),
env?.number("outsideTemperature"),
env?.optString("outsideTemperatureUnit"),
charge?.optString("mode")?.ifEmpty { null },
charge?.number("remainingTime")?.toInt(),
)
}
fun Car.chargingManager() =
chargingManagerOf(items("/chargingmanager/profiles/"), items("/chargingmanager/timers/"), items("/chargingmanager/providers/"))
internal fun chargingManagerOf(profiles: List<JSONObject>, timers: List<JSONObject>, providers: List<JSONObject>): ChargingManager {
// Some cars send no powerProvider link. maps+more then pairs both lists by position, options included.
fun link(i: Int, id: String?) = id ?: providers.getOrNull(i)?.optString("id")?.takeIf { profiles.size == providers.size }
return ChargingManager(
profiles.firstOrNull()?.let { valid(it, ::parseOptions) }?.copy(providerId = link(0, null)),
profiles.withIndex().drop(1).mapNotNull { (i, o) -> valid(o, ::parseProfile)?.let { it.copy(providerId = link(i, it.providerId)) } },
timers.mapNotNull { valid(it, ::parseTimer) },
providers.mapNotNull { valid(it, ::parseProvider) },
)
}
// Without ignition the car lists placeholder entries with empty strings. maps+more drops them too.
private fun <T> valid(o: JSONObject, parse: (JSONObject) -> T): T? = try {
parse(o)
} catch (e: Exception) {
Log.d("Model", "Skipping incomplete entry ${o.optString("uri")}: $e")
null
}
fun Car.write(t: Timer) {
require(t.cyclic || t.departureDate != null) { "A one-time timer needs a date" }
require(!t.cyclic || t.weekdays.isNotEmpty()) { "A weekly timer needs at least one day" }
require(t.state == TIMER_ON || t.state == TIMER_OFF) { "Unknown timer state ${t.state}" }
// maps+more never sends the state together with the schedule.
update(t.uri, JSONObject()
.put("cyclic", t.cyclic)
.put("weekdays", t.weekdays.toJson())
.put("departureTime", t.departureTime.format(HMS))
.apply { t.departureDate?.let { put("departureDate", it.format(DATE_OUT)) } }
.apply { t.profileId?.let { put("profile", it) } })
update(t.uri, JSONObject().put("state", t.state))
}
fun Car.write(p: Profile) {
require(p.maxCurrent in maxCurrents(vin)) { "Invalid max current ${p.maxCurrent}" }
update(p.uri, p.toJson())
}
/** Adds a charging location. The car creates the linked off-peak time itself. */
fun Car.create(p: Profile) {
require(p.maxCurrent in maxCurrents(vin)) { "Invalid max current ${p.maxCurrent}" }
val before = chargingManager().profiles.map { it.id }.toSet()
require(before.size < MAX_LOCATIONS) { "The car has at most $MAX_LOCATIONS charging locations" }
post("/chargingmanager/profiles/", p.toJson())
if (chargingManager().profiles.none { it.id !in before && it.name == p.name }) throw IOException("The car did not add ${p.name}")
}
fun Car.delete(p: Profile) {
require(chargingManager().timers.none { it.profileId == p.id }) { "A timer uses this charging location" }
send("DELETE", p.uri).ok()
if (chargingManager().profiles.any { it.id == p.id }) throw IOException("The car did not delete ${p.name}")
}
/** A new charging location with the maps+more defaults. */
fun newProfile(vin: String) = Profile("", "", "", 100, maxCurrents(vin).last(), listOf("charge"), null)
private fun Profile.toJson(): JSONObject {
require(name.isNotBlank() && name.length <= NAME_MAX) { "Name must have 1 to $NAME_MAX characters" }
require(targetLevel in TARGET_LEVELS) { "Invalid target level $targetLevel" }
require(operations.all { it in OPERATIONS }) { "Invalid operations $operations" }
return JSONObject()
.put("name", name)
.put("targetLevel", targetLevel)
.put("maxCurrent", maxCurrent)
.put("operations", JSONArray(operations))
}
fun Car.write(o: Options) {
require(o.maxCurrent in maxCurrents(vin)) { "Invalid max current ${o.maxCurrent}" }
require(o.minLevel in MIN_LEVELS) { "Invalid min level ${o.minLevel}" }
require(o.temperature in TEMPERATURES) { "Invalid temperature ${o.temperature}" }
require(o.operations.all { it in OPERATIONS }) { "Invalid operations ${o.operations}" }
update(o.uri, JSONObject()
.put("operations", JSONArray(o.operations))
.put("maxCurrent", o.maxCurrent)
.put("minLevel", o.minLevel)
.put("temperature", o.temperature))
}
fun Car.write(p: Provider) = update(p.uri, JSONObject()
.put("weekdays", p.weekdays.toJson())
.put("preferredTimeStart", p.start.format(HMS))
.put("preferredTimeEnd", p.end.format(HMS)))
// Like maps+more: only the time moves. Weekdays and dates stay local, even across midnight.
fun Timer.shifted(offsetSeconds: Int) = copy(departureTime = departureTime.plusSeconds(offsetSeconds.toLong()))
fun Provider.shifted(offsetSeconds: Int) = copy(start = start.plusSeconds(offsetSeconds.toLong()), end = end.plusSeconds(offsetSeconds.toLong()))
/** The next active departure after [now]. [timers] must be in local time. */
fun nextDeparture(timers: List<Timer>, now: ZonedDateTime): Pair<Timer, ZonedDateTime>? =
timers.filter { it.active }.mapNotNull { t ->
val dates = if (t.cyclic) (0L..7L).map { now.toLocalDate().plusDays(it) }.filter { it.dayOfWeek in t.weekdays }
else listOfNotNull(t.departureDate)
dates.map { ZonedDateTime.of(it, t.departureTime, now.zone) }.firstOrNull { it.isAfter(now) }?.let { t to it }
}.minByOrNull { it.second }
// The car wraps single elements in {"status": "ok", "data": {...}}.
private fun Car.element(uri: String) = JSONObject(get(uri)).let { it.optJSONObject("data") ?: it }
/** POSTs the fields of [fields] that differ on the car, then reads the element back to check them. */
private fun Car.update(uri: String, fields: JSONObject) {
val before = element(uri)
val changes = JSONObject()
fields.keys().forEach { if (!matches(fields.get(it), before.opt(it))) changes.put(it, fields.get(it)) }
if (changes.length() == 0) return
post(uri, changes)
val actual = element(uri)
if (!matches(changes, actual)) throw IOException("The car did not apply all changes. Sent $changes, car has $actual")
}
/** True if every value in [sent] is also in [actual]. [actual] may have more keys. A sent ID matches a linked object. */
internal fun matches(sent: Any?, actual: Any?): Boolean = when (sent) {
is String -> sent == actual || (actual is JSONObject && sent == actual.opt("id"))
is JSONObject -> actual is JSONObject && sent.keys().asSequence().all { matches(sent.get(it), actual.opt(it)) }
is JSONArray -> actual is JSONArray && sent.length() == actual.length() && (0 until sent.length()).all { matches(sent.get(it), actual.get(it)) }
is Number -> actual is Number && sent.toDouble() == actual.toDouble()
else -> sent == actual
}
Aapp/src/main/java/de/upapp/Screens.kt
@@ -0,0 +1,638 @@
@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
package de.upapp
import android.text.format.DateFormat
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import java.time.DayOfWeek
import java.time.Instant
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.format.TextStyle
import java.util.Locale
import kotlin.math.roundToInt
enum class Topic(@StringRes val title: Int, @StringRes val body: Int, @StringRes val note: Int? = null) {
BATTERY(R.string.battery, R.string.info_battery),
STATUS(R.string.charging_status, R.string.info_status),
RANGE(R.string.range, R.string.info_range),
NEXT(R.string.next_departure, R.string.info_next),
CAR(R.string.car, R.string.info_car),
TIMERS(R.string.departure_timers, R.string.info_timers, R.string.note_timers_utc),
PROFILES(R.string.charging_locations, R.string.info_profiles),
OPTIONS(R.string.options, R.string.info_options),
EXT_SUPPLY(R.string.climate_ext_supply, R.string.info_ext_supply),
MAX_CURRENT(R.string.max_current, R.string.info_max_current),
MIN_LEVEL(R.string.min_level, R.string.info_min_level),
TEMPERATURE(R.string.temperature, R.string.info_temperature),
PROVIDERS(R.string.offpeak, R.string.info_providers, R.string.note_offpeak_utc),
PATH(R.string.path, R.string.info_path),
POST(R.string.json_body, R.string.info_post, R.string.note_post),
PIN(R.string.registration, R.string.info_pin, R.string.note_pin),
READ_ONLY(R.string.read_only_title, R.string.info_read_only),
}
private val TIME = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
private val DATE = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
private fun localOffset() = ZoneId.systemDefault().rules.getOffset(Instant.now()).totalSeconds
private fun temperatureLabel(t: Double) = "$t °C"
private fun operationsLabel(ops: List<String>) =
listOfNotNull("🔌".takeIf { "charge" in ops }, "❄️/🔥".takeIf { "climate" in ops }).joinToString(" ")
// Shared shell for screens
@Composable
private fun Screen(content: @Composable ColumnScope.() -> Unit) = Column(
Modifier.verticalScroll(rememberScrollState()).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
content = content,
)
@Composable
fun InfoButton(topic: Topic) {
var open by remember { mutableStateOf(false) }
IconButton(onClick = { open = true }, modifier = Modifier.size(32.dp)) {
Icon(Icons.Outlined.Info, stringResource(R.string.more_info), Modifier.size(18.dp))
}
if (open) Sheet(onDismiss = { open = false }) {
Text(stringResource(topic.title), style = MaterialTheme.typography.headlineSmall)
stringResource(topic.body).split("\n\n").forEach { Text(it) }
topic.note?.let { Note(stringResource(it)) }
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
TextButton(onClick = { open = false }) { Text(stringResource(R.string.close)) }
}
}
}
@Composable
private fun Sheet(onDismiss: () -> Unit, content: @Composable ColumnScope.() -> Unit) =
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
Column(
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 24.dp).padding(bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
content = content,
)
}
@Composable
private fun Note(text: String) = Surface(color = MaterialTheme.colorScheme.tertiaryContainer, shape = MaterialTheme.shapes.small) {
Text(text, Modifier.padding(horizontal = 12.dp, vertical = 8.dp), style = MaterialTheme.typography.bodySmall)
}
@Composable
private fun Section(@StringRes title: Int, topic: Topic, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) =
Card(modifier.fillMaxWidth()) {
Column(Modifier.padding(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(title), style = MaterialTheme.typography.titleSmall)
InfoButton(topic)
}
content()
}
}
@Composable
private fun SectionTitle(@StringRes title: Int, topic: Topic) = Row(Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(title), style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
InfoButton(topic)
}
@Composable
private fun KeyValue(@StringRes key: Int, value: String, topic: Topic? = null) =
Row(Modifier.fillMaxWidth().padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(key), color = MaterialTheme.colorScheme.onSurfaceVariant)
topic?.let { InfoButton(it) }
Spacer(Modifier.weight(1f))
Text(value)
}
@Composable
private fun EditButton(onClick: () -> Unit) = FilledTonalButton(onClick = onClick) {
Icon(Icons.Default.Edit, null, Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.edit))
}
@Composable
private fun locale(): Locale = LocalConfiguration.current.locales[0]
@Composable
private fun dayLetter(d: DayOfWeek) = d.getDisplayName(TextStyle.NARROW, locale())
@Composable
private fun Days(days: Set<DayOfWeek>) = Row(Modifier.padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
DayOfWeek.entries.forEach { d ->
val on = d in days
Box(
Modifier.size(28.dp).background(if (on) MaterialTheme.colorScheme.primary else Color.Transparent, CircleShape),
contentAlignment = Alignment.Center,
) {
Text(dayLetter(d), style = MaterialTheme.typography.labelMedium, color = if (on) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
// Overview
private val PLUG_STATES = mapOf("plugged" to R.string.plugged_in, "unPlugged" to R.string.not_plugged_in)
private val CHARGE_STATES = mapOf(
"idle" to R.string.state_not_charging, "running" to R.string.state_charging, "completed" to R.string.state_completed,
"conservating" to R.string.state_conserving,
)
private val CLIMATE_STATES = mapOf(
"idle" to R.string.climate_off, "running" to R.string.state_running, "completed" to R.string.state_completed,
"abortedIgnitionOn" to R.string.climate_ignition_on, "abortedNoExternalSupply" to R.string.climate_no_supply,
"abortedBatteryLow" to R.string.climate_battery_low,
)
@Composable
private fun stateLabel(value: String, known: Map<String, Int>) = when {
value in known -> stringResource(known.getValue(value))
value.startsWith("aborted") -> stringResource(R.string.state_aborted)
else -> "–"
}
@Composable
fun Overview(vm: MainViewModel) = Screen {
vm.battery?.let { b ->
Section(R.string.battery, Topic.BATTERY) {
Text(b.soc?.let { "${it.roundToInt()} %" } ?: "–", style = MaterialTheme.typography.displayMedium)
b.soc?.let { soc -> LinearProgressIndicator(progress = { (soc / 100).toFloat() }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) }
}
}
vm.status?.let { s ->
Section(R.string.charging_status, Topic.STATUS) {
s.plug?.let { KeyValue(R.string.plug, stateLabel(it, PLUG_STATES)) }
s.charge?.let { KeyValue(R.string.charging_state, listOfNotNull(stateLabel(it, CHARGE_STATES), s.chargeMode).joinToString(" · ")) }
s.remainingMinutes?.takeIf { s.charge == "running" }?.let { KeyValue(R.string.remaining_time, "%d:%02d h".format(it / 60, it % 60)) }
s.climate?.let { KeyValue(R.string.climate_state, stateLabel(it, CLIMATE_STATES)) }
s.outsideTemperature?.let { t ->
KeyValue(R.string.outside_temperature, "$t " + if (s.temperatureUnit?.contains("fahrenheit", true) == true) "°F" else "°C")
}
}
}
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Section(R.string.range, Topic.RANGE, Modifier.weight(1f)) {
Text(vm.range?.value?.let { "${it.roundToInt()} ${vm.range?.unit}" } ?: "–", style = MaterialTheme.typography.headlineMedium)
}
Section(R.string.next_departure, Topic.NEXT, Modifier.weight(1f)) {
val cm = vm.charging
val next = cm?.let { nextDeparture(it.timers.map { t -> t.shifted(localOffset()) }, ZonedDateTime.now()) }
if (next == null) {
Text(stringResource(R.string.none), style = MaterialTheme.typography.headlineMedium)
} else {
Text(next.second.format(TIME), style = MaterialTheme.typography.headlineMedium)
val day = next.second.dayOfWeek.getDisplayName(TextStyle.SHORT, locale())
Text("$day · ${cm.profiles.find { it.id == next.first.profileId }?.name ?: "–"}", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
vm.info?.let { i ->
Section(R.string.car, Topic.CAR) {
KeyValue(R.string.vin, i.vin)
KeyValue(R.string.type, i.type)
KeyValue(R.string.car_clock, "${i.date} ${i.time}")
KeyValue(R.string.language, i.language)
}
}
}
// Charging manager
@Composable
fun Charging(vm: MainViewModel) {
val cm = vm.charging ?: return Waiting(null)
val offset = remember { localOffset() }
var timer by remember { mutableStateOf<Timer?>(null) }
var provider by remember { mutableStateOf<Provider?>(null) }
var profile by remember { mutableStateOf<Profile?>(null) }
var options by remember { mutableStateOf<Options?>(null) }
val vin = vm.car?.vin.orEmpty()
val unnamed = stringResource(R.string.offpeak)
fun owner(p: Provider) = cm.profiles.find { it.providerId == p.id }?.name ?: unnamed
val off = stringResource(R.string.off)
fun window(p: Provider) = if (p.active) "${p.start.format(TIME)} – ${p.end.format(TIME)}" else off
fun offpeak(id: String?) = cm.providers.find { it.id == id }?.shifted(offset)?.let(::window)
val currents = remember(vin) { maxCurrents(vin) }
Screen {
if (!vm.writesEnabled) Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)) {
Row(Modifier.padding(start = 16.dp, end = 4.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Default.Lock, null, Modifier.size(18.dp))
Text(stringResource(R.string.read_only), Modifier.weight(1f).padding(horizontal = 12.dp), style = MaterialTheme.typography.bodyMedium)
InfoButton(Topic.READ_ONLY)
}
}
if (cm.timers.isEmpty() && cm.profiles.isEmpty()) Note(stringResource(R.string.no_charging_data))
SectionTitle(R.string.departure_timers, Topic.TIMERS)
cm.timers.forEach { utc ->
val t = utc.shifted(offset)
Card {
Row(Modifier.padding(16.dp)) {
Column(Modifier.weight(1f)) {
Text(t.departureTime.format(TIME), style = MaterialTheme.typography.displaySmall)
val name = cm.profiles.find { it.id == t.profileId }?.name ?: "–"
Text("${stringResource(R.string.timer_n, t.index)} · $name", color = MaterialTheme.colorScheme.onSurfaceVariant)
if (t.cyclic) Days(t.weekdays) else Text(t.departureDate?.format(DATE) ?: "–")
if (vm.writesEnabled) Box(Modifier.padding(top = 12.dp)) { EditButton { timer = t } }
}
Switch(
checked = t.active,
onCheckedChange = if (vm.writesEnabled) { on -> vm.save { write(utc.copy(state = if (on) TIMER_ON else TIMER_OFF)) } } else null,
enabled = vm.writesEnabled,
)
}
}
}
SectionTitle(R.string.charging_locations, Topic.PROFILES)
cm.profiles.forEach { p ->
Card {
Column(Modifier.padding(16.dp)) {
Row {
Text(p.name, Modifier.weight(1f), style = MaterialTheme.typography.titleMedium)
Text(operationsLabel(p.operations))
}
KeyValue(R.string.charge_to, "${p.targetLevel} %")
KeyValue(R.string.max_current, "${p.maxCurrent} A")
offpeak(p.providerId)?.let { KeyValue(R.string.offpeak_short, it) }
if (vm.writesEnabled) EditButton { profile = p }
}
}
}
if (vm.writesEnabled && cm.profiles.size < MAX_LOCATIONS) OutlinedButton(onClick = { profile = newProfile(vin) }) {
Text(stringResource(R.string.add_location))
}
SectionTitle(R.string.options, Topic.OPTIONS)
cm.options?.let { o -> Card {
Column(Modifier.padding(16.dp)) {
KeyValue(R.string.climate_ext_supply, stringResource(if (o.climateExtSupply) R.string.yes else R.string.no), Topic.EXT_SUPPLY)
KeyValue(R.string.max_current, "${o.maxCurrent} A", Topic.MAX_CURRENT)
KeyValue(R.string.min_level, "${o.minLevel} %", Topic.MIN_LEVEL)
KeyValue(R.string.temperature, temperatureLabel(o.temperature), Topic.TEMPERATURE)
if (vm.writesEnabled) EditButton { options = o }
}
} }
SectionTitle(R.string.offpeak, Topic.PROVIDERS)
Card {
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
// The car answers 403 to writes on the entry of the options profile.
cm.providers.filter { it.id != cm.options?.providerId }.forEachIndexed { i, utc ->
val p = utc.shifted(offset)
if (i > 0) HorizontalDivider()
Row(Modifier.padding(vertical = 8.dp)) {
Column(Modifier.weight(1f)) {
Text(owner(p), style = MaterialTheme.typography.titleMedium)
Text(window(p))
if (p.active) Days(p.weekdays)
if (vm.writesEnabled && p.active) Box(Modifier.padding(top = 12.dp)) { EditButton { provider = p } }
}
Switch(
checked = p.active,
onCheckedChange = if (vm.writesEnabled) { on ->
// Switching on opens the editor with the maps+more default window 22:00 to 06:00.
if (on) provider = p.copy(start = LocalTime.of(22, 0), end = LocalTime.of(6, 0), weekdays = p.weekdays.ifEmpty { DayOfWeek.entries.toSet() })
else vm.save { write(utc.off()) }
} else null,
enabled = vm.writesEnabled,
)
}
}
}
}
}
timer?.let { t ->
TimerEditor(t, cm.profiles, offset, onDismiss = { timer = null }) { edited ->
timer = null
vm.save { write(edited.shifted(-offset)) }
}
}
provider?.let { p ->
ProviderEditor(p, owner(p), onDismiss = { provider = null }) { edited ->
provider = null
vm.save { write(edited.shifted(-offset)) }
}
}
profile?.let { p ->
val deletable = p.uri.isNotEmpty() && cm.timers.none { it.profileId == p.id }
ProfileEditor(p, currents, onDismiss = { profile = null }, onDelete = if (deletable) { { profile = null; vm.save { delete(p) } } } else null) { edited ->
profile = null
vm.save { if (edited.uri.isEmpty()) create(edited) else write(edited) }
}
}
options?.let { o ->
OptionsEditor(o, currents, onDismiss = { options = null }) { edited ->
options = null
vm.save { write(edited) }
}
}
}
// Editors
@Composable
private fun Label(@StringRes text: Int) =
Text(stringResource(text), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
@Composable
private fun Actions(onCancel: () -> Unit, modifier: Modifier = Modifier, onSave: () -> Unit) =
Row(modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) }
Button(onClick = onSave) { Text(stringResource(R.string.save)) }
}
@Composable
private fun RepeatToggle(cyclic: Boolean, onChange: (Boolean) -> Unit) = SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {
SegmentedButton(selected = cyclic, onClick = { onChange(true) }, shape = SegmentedButtonDefaults.itemShape(0, 2)) { Text(stringResource(R.string.weekly)) }
SegmentedButton(selected = !cyclic, onClick = { onChange(false) }, shape = SegmentedButtonDefaults.itemShape(1, 2)) { Text(stringResource(R.string.once)) }
}
@Composable
private fun DayPicker(days: Set<DayOfWeek>, onChange: (Set<DayOfWeek>) -> Unit) = FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
DayOfWeek.entries.forEach { d ->
FilterChip(selected = d in days, onClick = { onChange(if (d in days) days - d else days + d) }, label = { Text(dayLetter(d)) })
}
}
@Composable
private fun <T> Dropdown(@StringRes label: Int, options: List<T>, selected: T, text: (T) -> String, onSelect: (T) -> Unit) {
var open by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it }) {
OutlinedTextField(
text(selected), {}, readOnly = true, singleLine = true,
label = { Text(stringResource(label)) },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) },
modifier = Modifier.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable).fillMaxWidth(),
)
ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
options.forEach { DropdownMenuItem(text = { Text(text(it)) }, onClick = { onSelect(it); open = false }) }
}
}
}
/** A time as a button. Opens the clock dial, so no keyboard pops up. */
@Composable
private fun TimeField(@StringRes label: Int, value: LocalTime, onChange: (LocalTime) -> Unit) {
var open by remember { mutableStateOf(false) }
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(label), Modifier.weight(1f))
OutlinedButton(onClick = { open = true }) { Text(value.format(TIME), style = MaterialTheme.typography.titleLarge) }
}
if (open) {
val state = rememberTimePickerState(value.hour, value.minute, DateFormat.is24HourFormat(LocalContext.current))
AlertDialog(
onDismissRequest = { open = false },
confirmButton = { TextButton(onClick = { onChange(LocalTime.of(state.hour, state.minute)); open = false }) { Text(stringResource(R.string.ok)) } },
dismissButton = { TextButton(onClick = { open = false }) { Text(stringResource(R.string.cancel)) } },
text = { TimePicker(state) },
)
}
}
@Composable
private fun SwitchRow(@StringRes text: Int, checked: Boolean, onChange: (Boolean) -> Unit) =
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(text), Modifier.weight(1f))
Switch(checked = checked, onCheckedChange = onChange)
}
@Composable
private fun Error(@StringRes text: Int?) = text?.let { Text(stringResource(it), color = MaterialTheme.colorScheme.error) }
/** Edits [local], a timer already moved to local time. */
@Composable
private fun TimerEditor(local: Timer, profiles: List<Profile>, offset: Int, onDismiss: () -> Unit, onSave: (Timer) -> Unit) {
var draft by remember { mutableStateOf(local) }
var pickDate by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<Int?>(null) }
Sheet(onDismiss) {
Text(stringResource(R.string.timer_n, draft.index), style = MaterialTheme.typography.headlineSmall)
TimeField(R.string.departure_time_local, draft.departureTime) { draft = draft.copy(departureTime = it) }
Text(
stringResource(R.string.car_stores_utc, draft.shifted(-offset).departureTime.format(TIME)),
style = MaterialTheme.typography.bodySmall,
)
Label(R.string.repeat)
RepeatToggle(draft.cyclic) { draft = draft.copy(cyclic = it) }
if (draft.cyclic) {
Label(R.string.days)
DayPicker(draft.weekdays) { draft = draft.copy(weekdays = it) }
} else {
Label(R.string.date)
OutlinedButton(onClick = { pickDate = true }) {
Text(draft.departureDate?.format(DATE) ?: stringResource(R.string.pick_date))
}
}
Dropdown(R.string.charging_location, profiles, profiles.find { it.id == draft.profileId }, { it?.name ?: "–" }) { draft = draft.copy(profileId = it?.id) }
SwitchRow(R.string.timer_active, draft.active) { draft = draft.copy(state = if (it) TIMER_ON else TIMER_OFF) }
Error(error)
Actions(onDismiss) {
val result = draft
error = when {
result.cyclic && result.weekdays.isEmpty() -> R.string.err_pick_day
!result.cyclic && result.departureDate == null -> R.string.err_pick_date
else -> null
}
if (error == null) onSave(result)
}
}
if (pickDate) {
val state = rememberDatePickerState(draft.departureDate?.atStartOfDay(ZoneOffset.UTC)?.toInstant()?.toEpochMilli())
DatePickerDialog(
onDismissRequest = { pickDate = false },
confirmButton = {
TextButton(onClick = {
state.selectedDateMillis?.let { draft = draft.copy(departureDate = Instant.ofEpochMilli(it).atZone(ZoneOffset.UTC).toLocalDate()) }
pickDate = false
}) { Text(stringResource(R.string.ok)) }
},
) { DatePicker(state) }
}
}
@Composable
private fun ProviderEditor(p: Provider, title: String, onDismiss: () -> Unit, onSave: (Provider) -> Unit) {
var draft by remember { mutableStateOf(p) }
Sheet(onDismiss) {
Text(title, style = MaterialTheme.typography.headlineSmall)
TimeField(R.string.start, draft.start) { draft = draft.copy(start = it) }
TimeField(R.string.end, draft.end) { draft = draft.copy(end = it) }
when {
draft.start == draft.end -> Text(stringResource(R.string.empty_window), style = MaterialTheme.typography.bodySmall)
draft.end < draft.start -> Text(stringResource(R.string.overnight), style = MaterialTheme.typography.bodySmall)
}
Label(R.string.days)
DayPicker(draft.weekdays) { draft = draft.copy(weekdays = it) }
Actions(onDismiss) { onSave(draft) }
}
}
@Composable
private fun ProfileEditor(p: Profile, currents: List<Int>, onDismiss: () -> Unit, onDelete: (() -> Unit)?, onSave: (Profile) -> Unit) {
var draft by remember { mutableStateOf(p) }
var error by remember { mutableStateOf<Int?>(null) }
var confirmDelete by remember { mutableStateOf(false) }
Sheet(onDismiss) {
Text(if (p.uri.isEmpty()) stringResource(R.string.new_location) else p.name, style = MaterialTheme.typography.headlineSmall)
OutlinedTextField(
draft.name,
{ draft = draft.copy(name = it.take(NAME_MAX)) },
Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.name)) },
singleLine = true,
)
Dropdown(R.string.charge_to, TARGET_LEVELS, draft.targetLevel, { "$it %" }) { draft = draft.copy(targetLevel = it) }
Dropdown(R.string.max_current, currents, draft.maxCurrent, { "$it A" }) { draft = draft.copy(maxCurrent = it) }
SwitchRow(R.string.op_charge, "charge" in draft.operations) { draft = draft.copy(operations = draft.operations.toggle("charge", it)) }
SwitchRow(R.string.op_climate, "climate" in draft.operations) { draft = draft.copy(operations = draft.operations.toggle("climate", it)) }
Error(error)
if (p.uri.isNotEmpty() && onDelete == null) Text(stringResource(R.string.location_in_use), style = MaterialTheme.typography.bodySmall)
Row(verticalAlignment = Alignment.CenterVertically) {
if (onDelete != null) TextButton(onClick = { confirmDelete = true }) {
Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error)
}
Actions(onDismiss, Modifier.weight(1f)) {
error = if (draft.name.isBlank()) R.string.err_name else null
if (error == null) onSave(draft.copy(name = draft.name.trim()))
}
}
}
if (confirmDelete && onDelete != null) AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text(stringResource(R.string.delete_location_title, p.name)) },
text = { Text(stringResource(R.string.delete_location_text)) },
confirmButton = { TextButton(onClick = onDelete) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) } },
dismissButton = { TextButton(onClick = { confirmDelete = false }) { Text(stringResource(R.string.cancel)) } },
)
}
@Composable
private fun OptionsEditor(o: Options, currents: List<Int>, onDismiss: () -> Unit, onSave: (Options) -> Unit) {
var draft by remember { mutableStateOf(o) }
Sheet(onDismiss) {
Text(stringResource(R.string.options), style = MaterialTheme.typography.headlineSmall)
SwitchRow(R.string.climate_ext_supply, draft.climateExtSupply) { draft = draft.copy(operations = draft.operations.toggle(EXT_SUPPLY, it)) }
Dropdown(R.string.max_current, currents, draft.maxCurrent, { "$it A" }) { draft = draft.copy(maxCurrent = it) }
Dropdown(R.string.min_level, MIN_LEVELS, draft.minLevel, { "$it %" }) { draft = draft.copy(minLevel = it) }
Dropdown(R.string.temperature, TEMPERATURES, draft.temperature, ::temperatureLabel) { draft = draft.copy(temperature = it) }
Actions(onDismiss) { onSave(draft) }
}
}
private fun List<String>.toggle(value: String, on: Boolean) = if (on) (this - value) + value else this - value
// Console
@Composable
fun Console(vm: MainViewModel) = Screen {
var path by rememberSaveable { mutableStateOf("/car/batteries") }
var body by rememberSaveable { mutableStateOf("{}") }
OutlinedTextField(
path, { path = it }, Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.path)) },
trailingIcon = { InfoButton(Topic.PATH) },
singleLine = true,
textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace),
)
Button(onClick = { vm.console("GET", path, null) }, enabled = !vm.busy) { Text("GET") }
OutlinedTextField(
body, { body = it }, Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.json_body)) },
trailingIcon = { InfoButton(Topic.POST) },
enabled = vm.writesEnabled,
minLines = 3,
textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace),
)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
FilledTonalButton(onClick = { vm.console("POST", path, body) }, enabled = vm.writesEnabled && !vm.busy) { Text("POST") }
if (!vm.writesEnabled) Text(stringResource(R.string.post_disabled), style = MaterialTheme.typography.bodySmall)
}
Surface(color = MaterialTheme.colorScheme.inverseSurface, shape = MaterialTheme.shapes.medium, modifier = Modifier.fillMaxWidth()) {
Text(
vm.consoleOut.ifEmpty { stringResource(R.string.response_hint) },
Modifier.horizontalScroll(rememberScrollState()).padding(12.dp),
fontFamily = FontFamily.Monospace,
style = MaterialTheme.typography.bodySmall,
)
}
}
Aapp/src/main/java/de/upapp/Tls.kt
@@ -0,0 +1,124 @@
package de.upapp
import android.util.Log
import org.bouncycastle.tls.AlertDescription
import org.bouncycastle.tls.BasicTlsPSKIdentity
import org.bouncycastle.tls.CertificateRequest
import org.bouncycastle.tls.CipherSuite
import org.bouncycastle.tls.DefaultTlsClient
import org.bouncycastle.tls.PSKTlsClient
import org.bouncycastle.tls.ProtocolVersion
import org.bouncycastle.tls.TlsAuthentication
import org.bouncycastle.tls.TlsClientProtocol
import org.bouncycastle.tls.TlsContext
import org.bouncycastle.tls.TlsCredentials
import org.bouncycastle.tls.TlsFatalAlert
import org.bouncycastle.tls.TlsServerCertificate
import org.bouncycastle.tls.TlsUtils
import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto
import java.io.InputStream
import java.io.OutputStream
import java.security.GeneralSecurityException
import java.security.MessageDigest
import java.security.SecureRandom
import java.security.cert.CertPathValidator
import java.security.cert.CertificateFactory
import java.security.cert.PKIXParameters
import java.security.cert.TrustAnchor
import java.security.cert.X509Certificate
private val crypto = BcTlsCrypto(SecureRandom())
/** Root CA of the car's registration certificate, bundled in maps+more. */
val VIWI_ROOT_CA: X509Certificate = parseCertificate("""
-----BEGIN CERTIFICATE-----
MIIFATCCA2mgAwIBAgIJAKwA93QEg4cmMA0GCSqGSIb3DQEBCwUAMIGVMQswCQYD
VQQGEwJERTEWMBQGA1UECAwNTmllZGVyc2FjaHNlbjESMBAGA1UEBwwJV29sZnNi
dXJnMSQwIgYDVQQKDBtWb2xrc3dhZ2VuIEdtYkggRGV1dHNjaGxhbmQxDzANBgNV
BAsMBkVFQ0YvMTEjMCEGA1UEAwwaVmlXaSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkw
IBcNMTUwMjI0MTI1MzQzWhgPMjA1NTAyMTQxMjUzNDNaMIGVMQswCQYDVQQGEwJE
RTEWMBQGA1UECAwNTmllZGVyc2FjaHNlbjESMBAGA1UEBwwJV29sZnNidXJnMSQw
IgYDVQQKDBtWb2xrc3dhZ2VuIEdtYkggRGV1dHNjaGxhbmQxDzANBgNVBAsMBkVF
Q0YvMTEjMCEGA1UEAwwaVmlXaSBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggGiMA0G
CSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQC9YRvqG7dq9BVRn/vJJ05v5bG8o7ls
zzgBGgPnEYF1HGB9fYrpmSfoL0kdmifD0AzAnwkhb7281hBVV6v+HcXQVrLSQVL1
xVPOEbm/FDCb4ZI2tKuOeg97P6npZuW/tGf8Lk47dlkTSdPg94XgyJ3rIJgtjhTX
8r1EtlL/pP0D8AF360SmEJyEYF9CfU9U6/yKMjzjdUuaQRwEqKXUakQlJaRy3GQd
OGbgy0Eukkew5kiZO3dQhTq3NsiKB3YUIgYxK3PJzL35OMzmN5kxkR72AUtbnoO/
FwT6G060WPuRI+nENUlX8DQaR3fPaBat30eRFk5dQvd8Cmwd/qqm77DWS65R2xyS
+jzNx7mtPjVmVPzBY/K+rj5tWgf3QXCNaClqu+wwnIgX0Wgu22BhJNVRGDmJi9xP
RV9obiHvqBPO2SDo6AVEpIi+r8pOL3/iaQ/nS4a00SaAL31jW1hk0+N7bsknRk7P
5tlHZKXETVS0jSZ/dXgAQTmYygwmlyyiijsCAwEAAaNQME4wHQYDVR0OBBYEFFkw
1GxlgBqWBHf1gkv4XqKEGTWzMB8GA1UdIwQYMBaAFFkw1GxlgBqWBHf1gkv4XqKE
GTWzMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggGBACBWE/bexDK0EHXM
KKHMjYtg4a0xtBmdY2sQFrni2bbUc1myLISM7iI2WfPnWC4UnuMFfI/004TqdZej
MCTntsdSW7+qCDWDEqrYJEVxkLF9vCYeNLzzVr0tBo0TwjachGNBz4y9cO16LQBO
dfgYD7Dw6JXQptjEJgpg0AHgtrErCmVa4VF2aRadBKkon/41LKsBXxvOjHrK9gi2
EHASasuKYKQfqb117fRXbfbqIAh5p+oWZ2Ko9mafIjRE0b2q0HsDqm31Z7R0XuiS
m53o2FSj0Uk1cX3A9a+7h9YjALGLebkmfnZ4hD1LHVVLBuvErlPnIvSyUsKO0pue
mZGrLvJNSMEW+VR7uAb36dxHAr0f+E4+dV/WSXL+XXUMjzEYKyHc0bby2lZKx+TK
4dqI1xtQVO2uEff/JJHqyWBlXnSiNWGx5Bnu+C5oFOQmX+hE5A6jb9aad/nqYCHh
O0dgtlde6OVRrf6GSzWJZr7pK/IMuDfF6Y1Fa1wNhpyCMxeXkw==
-----END CERTIFICATE-----
""".trim().byteInputStream())
private fun parseCertificate(input: InputStream) = CertificateFactory.getInstance("X.509").generateCertificate(input) as X509Certificate
/** TLS for the one-time registration. Returns the connection and the PIN that the car display also shows. */
fun registrationTls(input: InputStream, output: OutputStream, root: X509Certificate = VIWI_ROOT_CA): Pair<TlsClientProtocol, String> {
lateinit var pin: String
val tls = TlsClientProtocol(input, output)
tls.connect(object : DefaultTlsClient(crypto) {
override fun getSupportedVersions(): Array<ProtocolVersion> = ProtocolVersion.TLSv12.only()
override fun getSupportedCipherSuites() = intArrayOf(CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
// The car does not support RFC 5746.
override fun notifySecureRenegotiation(secureRenegotiation: Boolean) {}
override fun getAuthentication() = object : TlsAuthentication {
override fun notifyServerCertificate(serverCertificate: TlsServerCertificate) =
verifyChain(serverCertificate.certificate.certificateList.map { parseCertificate(it.encoded.inputStream()) }, root)
override fun getClientCredentials(certificateRequest: CertificateRequest): TlsCredentials? = null
}
override fun notifyHandshakeComplete() {
super.notifyHandshakeComplete()
pin = registrationPin(context)
}
})
return tls to pin
}
// Checks the VW signatures only. The car cannot renew its certificate, so dates and host name are ignored.
private fun verifyChain(chain: List<X509Certificate>, root: X509Certificate) {
chain.forEach { Log.i("Tls", "Car certificate: ${it.subjectX500Principal}, valid ${it.notBefore} to ${it.notAfter}") }
val path = CertificateFactory.getInstance("X.509").generateCertPath(chain.filter { it != root })
val params = PKIXParameters(setOf(TrustAnchor(root, null))).apply {
isRevocationEnabled = false
date = (chain + root).maxOf { it.notBefore }
}
try {
CertPathValidator.getInstance("PKIX").validate(path, params)
} catch (e: GeneralSecurityException) {
throw TlsFatalAlert(AlertDescription.bad_certificate, "The car certificate is not signed by Volkswagen: ${e.message}", e)
}
}
// AES-128-GCM key block: client write key, then server write key, 16 bytes each, no MAC keys.
internal fun registrationPin(context: TlsContext): String {
val sp = context.securityParametersConnection
val keys = TlsUtils.PRF(sp, sp.masterSecret, "key expansion", sp.serverRandom + sp.clientRandom, 32).extract()
return pin(keys.copyOfRange(0, 16), keys.copyOfRange(16, 32))
}
internal fun pin(clientWriteKey: ByteArray, serverWriteKey: ByteArray): String {
val d = MessageDigest.getInstance("SHA-256").digest(clientWriteKey + serverWriteKey)
val t = (0..3).sumOf { (d[it].toLong() and 0xFF) shl (8 * it) }
return (t % 1_000_000).toString().padStart(6, '0')
}
/** TLS with the pre-shared key from registration. */
fun sessionTls(input: InputStream, output: OutputStream, identity: String, key: String) = TlsClientProtocol(input, output).apply {
connect(object : PSKTlsClient(crypto, BasicTlsPSKIdentity(identity, key.toByteArray())) {
override fun getSupportedVersions(): Array<ProtocolVersion> = ProtocolVersion.TLSv12.only()
override fun getSupportedCipherSuites() = intArrayOf(CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256)
override fun notifySecureRenegotiation(secureRenegotiation: Boolean) {}
})
}
Aapp/src/main/java/de/upapp/Tunnel.kt
@@ -0,0 +1,230 @@
package de.upapp
import android.util.Log
import java.io.Closeable
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.SocketTimeoutException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread
internal const val TRANSMIT = 0
internal const val OPEN = 1
internal const val CLOSE = 2
internal const val HEARTBEAT = 3
private const val MAX_PAYLOAD = 0xFFFF
// Values from maps+more.
private const val HEARTBEAT_MS = 5_000L
private const val SILENCE_MS = 15_000L
internal class Segment(val port: Int, val type: Int, val data: ByteArray)
internal fun frame(port: Int, type: Int, extra: ByteArray = ByteArray(0)) =
byteArrayOf(port.toByte(), (port shr 8).toByte(), type.toByte()) + extra
internal fun u16(v: Int) = byteArrayOf(v.toByte(), (v shr 8).toByte())
private fun u16(b: ByteArray, at: Int) = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
/** Returns the first segment in [b] and its encoded size, or null if [b] holds no complete segment. */
internal fun decode(b: ByteArray): Pair<Segment, Int>? {
if (b.size < 3) return null
val port = u16(b, 0)
return when (val type = b[2].toInt() and 0xFF) {
CLOSE, HEARTBEAT -> Segment(port, type, ByteArray(0)) to 3
OPEN -> if (b.size < 5) null else Segment(port, type, b.copyOfRange(3, 5)) to 5
TRANSMIT -> {
if (b.size < 5) return null
val end = 5 + u16(b, 3)
if (b.size < end) null else Segment(port, type, b.copyOfRange(5, end)) to end
}
else -> throw IOException("Unknown segment type $type")
}
}
/** MIBBridge protocol: multiplexes virtual TCP connections to the car over one RFCOMM stream. */
class Tunnel(private val input: InputStream, private val output: OutputStream) : Closeable {
private val channels = ConcurrentHashMap<Int, Channel>()
private val nextPort = AtomicInteger()
@Volatile var closed = false
private set
@Volatile private var lastReceived = System.currentTimeMillis()
init {
thread(isDaemon = true, name = "tunnel") { readLoop() }
thread(isDaemon = true, name = "heartbeat") { heartbeatLoop() }
}
/** Opens a connection to [remotePort] on the car. Reads fail after [timeoutMs] without data. */
fun open(remotePort: Int, timeoutMs: Long = 15_000): Channel {
if (closed) throw IOException("Bluetooth connection closed")
while (true) {
val ch = Channel(0xC000 + (nextPort.getAndIncrement() and 0x3FFF), timeoutMs)
if (channels.putIfAbsent(ch.port, ch) == null) {
send(frame(ch.port, OPEN, u16(remotePort)))
return ch
}
}
}
override fun close() {
if (closed) return
closed = true
channels.values.forEach { it.pipe.end() }
channels.clear()
runCatching { input.close() }
runCatching { output.close() }
}
private fun send(bytes: ByteArray) = synchronized(output) {
output.write(bytes)
output.flush()
}
private fun heartbeatLoop() {
try {
while (!closed) {
send(frame(0, HEARTBEAT))
Thread.sleep(HEARTBEAT_MS)
if (System.currentTimeMillis() - lastReceived > SILENCE_MS) {
Log.w(TAG, "No data from the car for ${SILENCE_MS / 1000} s")
break
}
}
} catch (e: IOException) {
if (!closed) Log.w(TAG, "Heartbeat failed", e)
} finally {
close()
}
}
private fun readLoop() {
val chunk = ByteArray(4096)
var buf = ByteArray(0)
try {
while (true) {
val n = input.read(chunk)
if (n < 0) break
lastReceived = System.currentTimeMillis()
buf += chunk.copyOf(n)
while (true) {
val (segment, size) = decode(buf) ?: break
buf = buf.copyOfRange(size, buf.size)
handle(segment)
}
}
} catch (e: IOException) {
if (!closed) Log.w(TAG, "Tunnel read failed", e)
} finally {
close()
}
}
private fun handle(s: Segment) {
when (s.type) {
HEARTBEAT -> {}
TRANSMIT -> channels[s.port]?.pipe?.put(s.data) ?: Log.w(TAG, "Data for unknown port ${s.port}")
CLOSE -> channels[s.port]?.onCarClose()
else -> Log.w(TAG, "Unexpected segment type ${s.type}")
}
}
inner class Channel(val port: Int, timeoutMs: Long) : Closeable {
internal val pipe = Pipe(timeoutMs)
@Volatile private var closedByCar = false
@Volatile private var closedByUs = false
val input: InputStream = pipe.input
val output: OutputStream = object : OutputStream() {
override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
override fun write(b: ByteArray, off: Int, len: Int) {
if (closedByCar || closed) throw IOException("Connection closed by the car")
var at = off
while (at < off + len) {
val n = minOf(MAX_PAYLOAD, off + len - at)
send(frame(port, TRANSMIT, u16(n) + b.copyOfRange(at, at + n)))
at += n
}
}
}
override fun close() {
if (closedByUs) return
closedByUs = true
pipe.end()
if (closedByCar) return
// The car acknowledges with its own CLOSE. onCarClose then unregisters the port.
runCatching { send(frame(port, CLOSE)) }.onFailure { channels.remove(port) }
}
internal fun onCarClose() {
if (!closedByUs) {
closedByCar = true
pipe.end()
runCatching { send(frame(port, CLOSE)) }
}
channels.remove(port)
}
}
private companion object {
const val TAG = "Tunnel"
}
}
/** In-memory byte stream between threads. Reads fail after [timeoutMs] without data. */
internal class Pipe(private val timeoutMs: Long = Long.MAX_VALUE) {
private val queue = LinkedBlockingQueue<ByteArray>()
private var current = ByteArray(0)
private var pos = 0
private var ended = false
fun put(bytes: ByteArray) {
if (bytes.isNotEmpty()) queue.add(bytes)
}
fun end() {
queue.add(END)
}
val input: InputStream = object : InputStream() {
override fun read(): Int {
val b = ByteArray(1)
return if (read(b, 0, 1) < 0) -1 else b[0].toInt() and 0xFF
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (len == 0) return 0
while (pos == current.size) {
if (ended) return -1
val next = queue.poll(timeoutMs, TimeUnit.MILLISECONDS)
?: throw SocketTimeoutException("No answer from the car for ${timeoutMs / 1000} s")
ended = next === END
current = next
pos = 0
}
val n = minOf(len, current.size - pos)
current.copyInto(b, off, pos, pos + n)
pos += n
return n
}
override fun close() = end()
}
val output: OutputStream = object : OutputStream() {
override fun write(b: Int) = put(byteArrayOf(b.toByte()))
override fun write(b: ByteArray, off: Int, len: Int) = put(b.copyOfRange(off, off + len))
override fun close() = end()
}
private companion object {
val END = ByteArray(0)
}
}
Aapp/src/main/java/de/upapp/WebSocket.kt
@@ -0,0 +1,133 @@
package de.upapp
import android.util.Log
import org.json.JSONObject
import org.json.JSONTokener
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.EOFException
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
internal const val WS_TEXT = 1
internal const val WS_CLOSE = 8
internal const val WS_PING = 9
internal const val WS_PONG = 10
internal fun wsAccept(key: String): String = Base64.getEncoder().encodeToString(
MessageDigest.getInstance("SHA-1").digest((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").toByteArray())
)
/** Writes one unfragmented frame. Clients must [mask], servers must not. */
internal fun writeFrame(out: OutputStream, opcode: Int, payload: ByteArray, mask: Boolean) = synchronized(out) {
val frame = ByteArrayOutputStream()
frame.write(0x80 or opcode)
val m = if (mask) 0x80 else 0
val n = payload.size
when {
n < 126 -> frame.write(m or n)
n < 0x10000 -> frame.write(byteArrayOf((m or 126).toByte(), (n shr 8).toByte(), n.toByte()))
else -> {
frame.write(m or 127)
for (i in 7 downTo 0) frame.write((n.toLong() shr (8 * i)).toInt())
}
}
if (mask) {
val key = ByteArray(4).also { SecureRandom().nextBytes(it) }
frame.write(key)
frame.write(ByteArray(n) { (payload[it].toInt() xor key[it % 4].toInt()).toByte() })
} else {
frame.write(payload)
}
out.write(frame.toByteArray())
out.flush()
}
/** Reads the next data message. Answers pings. Throws [EOFException] on a close frame. */
internal fun readMessage(input: InputStream, output: OutputStream, mask: Boolean): Pair<Int, ByteArray> {
val inp = DataInputStream(input)
var opcode = 0
val message = ByteArrayOutputStream()
while (true) {
val b0 = inp.readUnsignedByte()
val b1 = inp.readUnsignedByte()
val len = when (val l = b1 and 0x7F) {
126 -> inp.readUnsignedShort()
127 -> inp.readLong().toInt()
else -> l
}
val key = if (b1 and 0x80 != 0) ByteArray(4).also { inp.readFully(it) } else null
val data = ByteArray(len).also { inp.readFully(it) }
key?.let { k -> for (i in data.indices) data[i] = (data[i].toInt() xor k[i % 4].toInt()).toByte() }
when (val op = b0 and 0x0F) {
WS_CLOSE -> {
runCatching { writeFrame(output, WS_CLOSE, data, mask) }
throw EOFException("WebSocket closed")
}
WS_PING -> writeFrame(output, WS_PONG, data, mask)
WS_PONG -> {}
else -> {
if (op != 0) opcode = op
message.write(data)
if (b0 and 0x80 != 0) return opcode to message.toByteArray()
}
}
}
}
/**
* Subscribes to [paths], collections or single elements, and calls [onEvent] with the subscribed path and the event data.
* Blocks until the connection ends, then throws.
*/
fun Car.listen(paths: List<String>, onEvent: (String, Any?) -> Unit) {
// Events can be minutes apart, so this channel has no read timeout.
val ch = tunnel.open(443, Long.MAX_VALUE)
try {
val tls = sessionTls(ch.input, ch.output, psk.first, psk.second)
val key = Base64.getEncoder().encodeToString(ByteArray(16).also { SecureRandom().nextBytes(it) })
val r = exchange(
tls.inputStream, tls.outputStream, "GET", HTTPS_HOST, "/", keepAlive = true,
extraHeaders = listOf("Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Key: $key", "Sec-WebSocket-Version: 13"),
)
if (r.status != 101 || r.headers["sec-websocket-accept"] != wsAccept(key)) throw IOException("WebSocket upgrade failed: HTTP ${r.status}")
// Like maps+more: one subscription at a time. The car answers 409 Conflict to overlapping ones.
val pending = ArrayDeque(paths)
fun subscribeNext() = pending.removeFirstOrNull()?.let {
// Inputs need a short limit. Otherwise the car merges "pushed" and "released" into one event.
val limit = if (it.startsWith("/mechanicalinput/")) 100 else 1000
val subscribe = JSONObject().put("type", "subscribe").put("event", "$it#42").put("updatelimit", limit)
writeFrame(tls.outputStream, WS_TEXT, subscribe.toString().toByteArray(), mask = true)
}
subscribeNext()
while (true) {
val (op, data) = readMessage(tls.inputStream, tls.outputStream, mask = true)
if (op != WS_TEXT) continue
val text = data.decodeToString()
if (BuildConfig.DEBUG) Log.d("Events", text.take(4000))
// The car joins several messages in one frame without a separator.
val messages = JSONTokener(text)
while (true) {
val m = (runCatching { messages.nextValue() }.getOrNull() as? JSONObject) ?: break
val line = m.toString()
val event = m.optString("event").substringBefore('#').substringBefore('?')
when (m.optString("type")) {
"data" -> (paths.firstOrNull { event == it } ?: paths.firstOrNull { event.startsWith(it) })?.let { onEvent(it, m.opt("data")) }
"subscribe" -> {
if (m.optString("status") != "ok") Log.w("Events", "Subscription failed: $line")
subscribeNext()
}
"error" -> {
Log.w("Events", "Event error: $line")
subscribeNext()
}
}
}
}
} finally {
ch.close()
}
}
Aapp/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#FFFFFF"
android:pathData="M58,30L38,58L52,58L48,78L70,48L56,48Z" />
</vector>
Aapp/src/main/res/mipmap-anydpi/ic_launcher.xml
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Aapp/src/main/res/values-de/strings.xml
@@ -0,0 +1,132 @@
<resources>
<string name="select_car">Fahrzeug wählen</string>
<string name="select_car_hint">Gekoppelte Bluetooth-Geräte. Kopple das Telefon zuerst in den Systemeinstellungen mit dem Fahrzeug.</string>
<string name="bt_permission">Die App braucht Bluetooth-Zugriff, um mit dem Fahrzeug zu kommunizieren.</string>
<string name="allow_bluetooth">Bluetooth erlauben</string>
<string name="no_devices">Keine gekoppelten Geräte.</string>
<string name="connecting">Verbinde mit %1$s…</string>
<string name="confirm_pin_title">Am Fahrzeugdisplay bestätigen</string>
<string name="confirm_pin_text">Dieses Telefon ist noch nicht im Fahrzeug registriert. Prüfe, ob das Fahrzeugdisplay dieselbe PIN zeigt. Bestätige sie dann im Fahrzeug.</string>
<string name="pin_note">Wenn die PINs abweichen, brich ab. Dann ist eventuell ein anderes Gerät zwischen Telefon und Fahrzeug.</string>
<string name="registration">Registrierung</string>
<string name="registered">Registriert. Schlüssel für %1$s gespeichert.</string>
<string name="connected_vin">Verbunden · %1$s</string>
<string name="refresh">Aktualisieren</string>
<string name="disconnect">Trennen</string>
<string name="tab_overview">Übersicht</string>
<string name="tab_charging">Laden</string>
<string name="tab_console">Konsole</string>
<string name="saved">Gespeichert. Durch erneutes Lesen geprüft.</string>
<string name="error">Fehler: %1$s</string>
<string name="more_info">Mehr Infos</string>
<string name="close">Schließen</string>
<string name="cancel">Abbrechen</string>
<string name="save">Speichern</string>
<string name="ok">OK</string>
<string name="edit">Bearbeiten</string>
<string name="yes">Ja</string>
<string name="no">Nein</string>
<string name="none">Keine</string>
<string name="battery">Batterie</string>
<string name="range">Reichweite</string>
<string name="next_departure">Nächste Abfahrt</string>
<string name="car">Fahrzeug</string>
<string name="vin">FIN</string>
<string name="type">Typ</string>
<string name="car_clock">Fahrzeuguhr</string>
<string name="language">Sprache</string>
<string name="read_only_title">Nur lesen</string>
<string name="read_only">Nur lesen. Einstellungen ändern ist in dieser Version deaktiviert.</string>
<string name="departure_timers">Abfahrtszeiten</string>
<string name="timer_n">Timer %1$d</string>
<string name="weekly">Wöchentlich</string>
<string name="once">Einmalig</string>
<string name="charging_locations">Ladeorte</string>
<string name="charging_location">Ladeort</string>
<string name="charge_to">Laden bis</string>
<string name="max_current">Max. Ladestrom</string>
<string name="options">Optionen</string>
<string name="climate_ext_supply">Klimatisieren mit Batteriestrom</string>
<string name="min_level">Min. Ladestand</string>
<string name="temperature">Temperatur</string>
<string name="offpeak">Bevorzugte Ladezeiten</string>
<string name="op_charge">Batterie laden</string>
<string name="op_climate">Klimatisierung</string>
<string name="name">Name</string>
<string name="departure_time_local">Abfahrtszeit (Ortszeit)</string>
<string name="car_stores_utc">Das Fahrzeug speichert %1$s UTC.</string>
<string name="repeat">Wiederholen</string>
<string name="days">Tage</string>
<string name="date">Datum</string>
<string name="pick_date">Datum wählen</string>
<string name="timer_active">Timer aktiv</string>
<string name="start">Beginn</string>
<string name="end">Ende</string>
<string name="empty_window">Beginn und Ende sind gleich. Die Ladezeit ist aus.</string>
<string name="overnight">Läuft über Mitternacht in den nächsten Tag.</string>
<string name="err_pick_day">Wähle mindestens einen Tag.</string>
<string name="err_name">Gib einen Namen ein.</string>
<string name="err_pick_date">Wähle ein Datum.</string>
<string name="path">Pfad</string>
<string name="json_body">JSON-Body</string>
<string name="post_disabled">POST ist in dieser Version deaktiviert.</string>
<string name="response_hint">Die Antwort erscheint hier.</string>
<string name="info_battery">Ladestand der Hochvoltbatterie in Prozent.</string>
<string name="info_range">Verbleibende elektrische Reichweite, die das Fahrzeug berechnet.\n\nSie hängt von der letzten Fahrweise und der Außentemperatur ab.</string>
<string name="info_next">Der nächste aktive Abfahrtstimer in Ortszeit.\n\nDas Fahrzeug versucht, bis dahin den Ziel-Ladestand und die Innentemperatur zu erreichen.</string>
<string name="info_car">Grunddaten, die das Infotainmentsystem meldet.\n\nDie Fahrzeuguhr ist Datum und Uhrzeit des Infotainmentsystems. Sie kann vom Telefon abweichen.</string>
<string name="info_timers">Das Fahrzeug hat drei Abfahrtstimer. Jeder Timer gehört zu einem Ladeort.\n\nIst ein Timer aktiv, plant das Fahrzeug Laden und Klimatisierung. Beides ist zur Abfahrtszeit fertig.\n\nWöchentliche Timer wiederholen sich an den markierten Tagen. Einmalige Timer laufen einmal an einem festen Datum.</string>
<string name="note_timers_utc">Das Fahrzeug speichert die Zeiten in UTC. Die App zeigt sie in deiner Ortszeit.</string>
<string name="info_profiles">Einstellungen für jeden Ort, an dem du lädst, zum Beispiel Zuhause oder Arbeit.\n\nLaden bis: der Ladestand, bis zu dem das Fahrzeug lädt, wenn ein Timer diesen Ort nutzt.\n\nMax. Ladestrom: der höchste Ladestrom in Ampere. Nutze an schwachen Steckdosen einen niedrigen Wert.\n\n🔌 bedeutet, der Timer lädt die Batterie. ❄️/🔥 bedeutet, der Timer heizt oder kühlt auch den Innenraum.</string>
<string name="info_options">Globale Einstellungen für alle Timer und Ladeorte.</string>
<string name="info_ext_supply">Erlaubt Klimaanlage und Heizung, die Hochvoltbatterie zu nutzen. Ist es aus, läuft die Klimatisierung nur mit Netzstrom bei angeschlossenem Ladekabel.</string>
<string name="info_max_current">Standardwert für den höchsten Ladestrom in Ampere.</string>
<string name="info_min_level" formatted="false">Das Fahrzeug lädt sofort bis zu diesem Ladestand, unabhängig von Timern und Ladezeiten.\n\nBei 100 % lädt das Fahrzeug nach dem Einstecken immer sofort voll.</string>
<string name="info_temperature">Ziel-Innentemperatur für die Klimatisierung zur Abfahrt. LO und HI sind die kleinste und größte Einstellung.</string>
<string name="info_providers">Zeitfenster, in denen Strom günstiger ist, zum Beispiel ein Nachttarif.\n\nDas Fahrzeug lädt bevorzugt in diesen Fenstern, wenn die Abfahrtszeit es zulässt.</string>
<string name="note_offpeak_utc">Das Fahrzeug speichert die Zeiten in UTC. Die App zeigt sie in deiner Ortszeit.</string>
<string name="info_path">Ein REST-Pfad im Fahrzeug, zum Beispiel /car/batteries.\n\nGET liest die Daten und zeigt die rohe JSON-Antwort. Damit kannst du erkunden, was das Fahrzeug anbietet.</string>
<string name="info_post">Sendet den JSON-Body an den Pfad. Das ändert Einstellungen im Fahrzeug.</string>
<string name="note_post">POST ist in dieser Version deaktiviert. Falsche Werte können das Fahrzeug verwirren.</string>
<string name="info_pin">Das Fahrzeug spricht nur mit registrierten Telefonen. Die Registrierung erfolgt einmal pro Fahrzeug.\n\nDas Fahrzeug zeigt eine PIN auf seinem Display. Prüfe, ob die App dieselbe PIN zeigt, und bestätige sie dann im Fahrzeug. Die App erhält dann einen Schlüssel und speichert ihn auf diesem Telefon.</string>
<string name="note_pin">Telefon und Fahrzeug berechnen die PIN aus der verschlüsselten Verbindung. Gleiche PINs beweisen, dass niemand dazwischen sitzt. Die App prüft außerdem das Fahrzeugzertifikat gegen das VW-Stammzertifikat.</string>
<string name="info_read_only">Diese Version liest nur Daten aus dem Fahrzeug.\n\nDer Code zum Ändern von Einstellungen ist vorhanden. Er bleibt deaktiviert, bis wir ihn in einem echten Fahrzeug getestet haben.</string>
<string name="charging_status">Ladestatus</string>
<string name="plug">Stecker</string>
<string name="plugged_in">Eingesteckt</string>
<string name="not_plugged_in">Nicht eingesteckt</string>
<string name="charging_state">Laden</string>
<string name="climate_state">Standklimatisierung</string>
<string name="outside_temperature">Außentemperatur</string>
<string name="state_not_charging">Lädt nicht</string>
<string name="state_charging">Lädt</string>
<string name="state_completed">Abgeschlossen</string>
<string name="state_conserving">Ladeerhaltung</string>
<string name="state_aborted">Abgebrochen</string>
<string name="climate_off">Aus</string>
<string name="state_running">Läuft</string>
<string name="add_location">+ Ladeort hinzufügen</string>
<string name="new_location">Neuer Ladeort</string>
<string name="delete">Löschen</string>
<string name="delete_location_title">%1$s löschen?</string>
<string name="delete_location_text">Das Fahrzeug löscht auch die Ladezeit dieses Ladeorts.</string>
<string name="location_in_use">Ein Timer nutzt diesen Ladeort. Verknüpfe den Timer mit einem anderen Ladeort, um ihn zu löschen.</string>
<string name="demo_car">Demo-Fahrzeug</string>
<string name="demo_car_hint">Teste die App ohne Fahrzeug. Die App sendet nichts an ein Fahrzeug.</string>
<string name="info_status">Live-Zustand des Fahrzeugs. Er aktualisiert sich selbst, solange die App offen ist.\n\nStandklimatisierung ist die Klimafunktion, die Timer und die App starten. Bei eingeschalteter Zündung läuft stattdessen die normale Klimaanlage, daher steht hier aus.\n\nAbgebrochen bedeutet, dass das Fahrzeug Laden oder Klimatisierung vorzeitig beendet hat, zum Beispiel weil die Stromversorgung ausfiel.</string>
<string name="no_charging_data">Das Fahrzeug sendet keine Ladedaten. Schalte die Zündung ein und aktualisiere.</string>
<string name="remaining_time">Restzeit</string>
<string name="climate_ignition_on">Aus, Zündung ist an</string>
<string name="climate_no_supply">Abgebrochen, kein Netzstrom</string>
<string name="climate_battery_low">Abgebrochen, Batterie leer</string>
<string name="offpeak_short">Ladezeit</string>
<string name="off">Aus</string>
<string name="your_cars">Deine Fahrzeuge</string>
<string name="other_devices">Andere gekoppelte Geräte</string>
</resources>
Aapp/src/main/res/values/colors.xml
@@ -0,0 +1,3 @@
<resources>
<color name="ic_launcher_background">#3A6A1E</color>
</resources>
Aapp/src/main/res/values/strings.xml
@@ -0,0 +1,133 @@
<resources>
<string name="app_name" translatable="false">upApp</string>
<string name="select_car">Select your car</string>
<string name="select_car_hint">Paired Bluetooth devices. Pair the phone with the car in the system settings first.</string>
<string name="bt_permission">The app needs Bluetooth access to talk to the car.</string>
<string name="allow_bluetooth">Allow Bluetooth</string>
<string name="no_devices">No paired devices.</string>
<string name="connecting">Connecting to %1$s…</string>
<string name="confirm_pin_title">Confirm on the car display</string>
<string name="confirm_pin_text">This phone is not registered with the car yet. Check that the car display shows the same PIN. Then confirm it on the car.</string>
<string name="pin_note">If the PINs differ, cancel. Another device may be between the phone and the car.</string>
<string name="registration">Registration</string>
<string name="registered">Registered. Key saved for %1$s.</string>
<string name="connected_vin">Connected · %1$s</string>
<string name="refresh">Refresh</string>
<string name="disconnect">Disconnect</string>
<string name="tab_overview">Overview</string>
<string name="tab_charging">Charging</string>
<string name="tab_console">Console</string>
<string name="saved">Saved. Verified by reading it back.</string>
<string name="error">Error: %1$s</string>
<string name="more_info">More info</string>
<string name="close">Close</string>
<string name="cancel">Cancel</string>
<string name="save">Save</string>
<string name="ok">OK</string>
<string name="edit">Edit</string>
<string name="yes">Yes</string>
<string name="no">No</string>
<string name="none">None</string>
<string name="battery">Battery</string>
<string name="range">Range</string>
<string name="next_departure">Next departure</string>
<string name="car">Car</string>
<string name="vin">VIN</string>
<string name="type">Type</string>
<string name="car_clock">Car clock</string>
<string name="language">Language</string>
<string name="read_only_title">Read only</string>
<string name="read_only">Read only. Changing settings is disabled in this version.</string>
<string name="departure_timers">Departure timers</string>
<string name="timer_n">Timer %1$d</string>
<string name="weekly">Weekly</string>
<string name="once">Once</string>
<string name="charging_locations">Charging locations</string>
<string name="charging_location">Charging location</string>
<string name="charge_to">Charge to</string>
<string name="max_current">Max current</string>
<string name="options">Options</string>
<string name="climate_ext_supply">Climate from battery</string>
<string name="min_level">Min. battery level</string>
<string name="temperature">Temperature</string>
<string name="offpeak">Off-peak power times</string>
<string name="op_charge">Charge battery</string>
<string name="op_climate">Climate control</string>
<string name="name">Name</string>
<string name="departure_time_local">Departure time (local)</string>
<string name="car_stores_utc">The car stores %1$s UTC.</string>
<string name="repeat">Repeat</string>
<string name="days">Days</string>
<string name="date">Date</string>
<string name="pick_date">Pick a date</string>
<string name="timer_active">Timer active</string>
<string name="start">Start</string>
<string name="end">End</string>
<string name="empty_window">Start equals end. The off-peak time is off.</string>
<string name="overnight">Runs over midnight into the next day.</string>
<string name="err_pick_day">Pick at least one day.</string>
<string name="err_name">Enter a name.</string>
<string name="err_pick_date">Pick a date.</string>
<string name="path">Path</string>
<string name="json_body">JSON body</string>
<string name="post_disabled">POST is disabled in this version.</string>
<string name="response_hint">The response appears here.</string>
<string name="info_battery">State of charge of the high-voltage battery in percent.</string>
<string name="info_range">Remaining electric range that the car calculates.\n\nIt depends on your recent driving style and the outside temperature.</string>
<string name="info_next">The next active departure timer, in local time.\n\nThe car tries to reach the target charge and cabin temperature by this time.</string>
<string name="info_car">Basic data that the infotainment system reports.\n\nThe car clock is the date and time of the infotainment unit. It can differ from your phone.</string>
<string name="info_timers">The car has three departure timers. Each timer links to one charging location.\n\nWhen a timer is on, the car plans charging and climate control. Both are ready at the departure time.\n\nWeekly timers repeat on the marked days. One-time timers run once on a set date.</string>
<string name="note_timers_utc">The car stores the times in UTC. The app shows them in your local time.</string>
<string name="info_profiles">Settings for each place where you charge, for example home or work.\n\nCharge to: the battery level the car charges to when a timer uses this location.\n\nMax current: the highest charging current in ampere. Use a low value on weak sockets.\n\n🔌 means the timer charges the battery. ❄️/🔥 means the timer also heats or cools the cabin.</string>
<string name="info_options">Global settings for all timers and locations.</string>
<string name="info_ext_supply">Allows air conditioning and heating to use the high-voltage battery. When off, climate control runs only on mains power while the car is plugged in.</string>
<string name="info_max_current">Default highest charging current in ampere.</string>
<string name="info_min_level" formatted="false">The car charges immediately up to this level, regardless of timers and off-peak times.\n\nAt 100 %, the car always charges fully right after you plug in.</string>
<string name="info_temperature">Target cabin temperature for climate control at departure. LO and HI are the minimum and maximum settings.</string>
<string name="info_providers">Time windows when electricity is cheaper, for example a night tariff.\n\nThe car prefers these windows for charging if the departure time still allows it.</string>
<string name="note_offpeak_utc">The car stores the times in UTC. The app shows them in your local time.</string>
<string name="info_path">A REST path on the car, for example /car/batteries.\n\nGET reads the data and shows the raw JSON answer. Use it to explore what the car offers.</string>
<string name="info_post">Sends the JSON body to the path. This changes settings in the car.</string>
<string name="note_post">POST is disabled in this version. Wrong values can confuse the car.</string>
<string name="info_pin">The car only talks to registered phones. Registration happens once per car.\n\nThe car shows a PIN on its display. Check that the app shows the same PIN. Then confirm it on the car. The app then receives a key and stores it on this phone.</string>
<string name="note_pin">The phone and the car calculate the PIN from the encrypted connection. Equal PINs prove that nobody sits in between. The app also checks the car certificate against the VW root certificate.</string>
<string name="info_read_only">This version only reads data from the car.\n\nThe code to change settings exists. It stays disabled until we test it in a real car.</string>
<string name="charging_status">Charging status</string>
<string name="plug">Plug</string>
<string name="plugged_in">Plugged in</string>
<string name="not_plugged_in">Not plugged in</string>
<string name="charging_state">Charging</string>
<string name="climate_state">Parked climate control</string>
<string name="outside_temperature">Outside temperature</string>
<string name="state_not_charging">Not charging</string>
<string name="state_charging">Charging</string>
<string name="state_completed">Completed</string>
<string name="state_conserving">Maintaining charge</string>
<string name="state_aborted">Stopped</string>
<string name="climate_off">Off</string>
<string name="state_running">Running</string>
<string name="add_location">+ Add charging location</string>
<string name="new_location">New charging location</string>
<string name="delete">Delete</string>
<string name="delete_location_title">Delete %1$s?</string>
<string name="delete_location_text">The car also deletes the off-peak time of this location.</string>
<string name="location_in_use">A timer uses this location. Link the timer to another location to delete it.</string>
<string name="demo_car">Demo car</string>
<string name="demo_car_hint">Try the app without a car. The app sends nothing to a car.</string>
<string name="info_status">Live state from the car. It updates by itself while the app is open.\n\nParked climate control is the climate function that timers and the app start. While the ignition is on, the normal climate control runs instead, so this shows off.\n\nStopped means the car ended charging or climate control early, for example because the power supply failed.</string>
<string name="no_charging_data">The car sends no charging data. Switch the ignition on and refresh.</string>
<string name="remaining_time">Time left</string>
<string name="climate_ignition_on">Off, ignition is on</string>
<string name="climate_no_supply">Stopped, no mains power</string>
<string name="climate_battery_low">Stopped, battery low</string>
<string name="offpeak_short">Off-peak time</string>
<string name="off">Off</string>
<string name="your_cars">Your cars</string>
<string name="other_devices">Other paired devices</string>
</resources>
Aapp/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The stored car keys must not leave the phone. -->
<data-extraction-rules>
<cloud-backup>
<exclude domain="sharedpref" path="credentials.xml" />
</cloud-backup>
<device-transfer>
<exclude domain="sharedpref" path="credentials.xml" />
</device-transfer>
</data-extraction-rules>
Aapp/src/test/java/de/upapp/DemoTest.kt
@@ -0,0 +1,63 @@
package de.upapp
import android.content.SharedPreferences
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import java.lang.reflect.Proxy
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
/** Preferences that return [credentials] for every VIN. */
fun storedCredentials(credentials: String) =
Proxy.newProxyInstance(SharedPreferences::class.java.classLoader, arrayOf(SharedPreferences::class.java)) { _, m, _ ->
if (m.name == "getString") credentials else null
} as SharedPreferences
class DemoTest {
private val car = Car(DemoCar().tunnel, storedCredentials(DEMO_CREDENTIALS)).apply { connect {} }
@Test
fun readsAllData() {
assertEquals(DEMO_VIN, car.vin)
assertEquals(64.0, car.battery().soc!!, 1.0)
assertEquals(Status("running", "plugged", "idle", 12.5, "celsius"), car.status().copy(charge = "running"))
val cm = car.chargingManager()
assertEquals(listOf("Zuhause", "Arbeit"), cm.profiles.map { it.name })
assertEquals(3, cm.timers.size)
assertEquals(2, cm.providers.size)
}
@Test
fun createsAndDeletesLocations() {
car.create(newProfile(car.vin).copy(name = "Oma"))
val added = car.chargingManager().profiles.single { it.name == "Oma" }
assertEquals(3, car.chargingManager().providers.size)
car.delete(added)
assertEquals(listOf("Zuhause", "Arbeit"), car.chargingManager().profiles.map { it.name })
assertEquals(2, car.chargingManager().providers.size)
val used = car.chargingManager().profiles.first()
assertThrows(IllegalArgumentException::class.java) { car.delete(used) }
}
@Test
fun writesTimerAndPushesEvent() {
val changed = CountDownLatch(1)
thread(isDaemon = true) { runCatching { car.listen(listOf("/chargingmanager/timers/")) { _, _ -> changed.countDown() } } }
val cm = car.chargingManager()
val timer = cm.timers.first()
val work = cm.profiles.last()
var on = timer.active
// Writes until the event connection is up and reports a change.
repeat(25) {
on = !on
car.write(timer.copy(state = if (on) TIMER_ON else TIMER_OFF, profileId = work.id))
if (changed.await(200, TimeUnit.MILLISECONDS)) return@repeat
}
assertEquals(0, changed.count)
val stored = car.chargingManager().timers.first()
assertEquals(work.id, stored.profileId)
assertEquals(on, stored.active)
}
}
Aapp/src/test/java/de/upapp/ModelTest.kt
@@ -0,0 +1,116 @@
package de.upapp
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.DayOfWeek.FRIDAY
import java.time.DayOfWeek.MONDAY
import java.time.DayOfWeek.SUNDAY
import java.time.DayOfWeek.THURSDAY
import java.time.DayOfWeek.TUESDAY
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZonedDateTime
// Fixtures from the upXlink test suite.
class ModelTest {
private val timer = parseTimer(JSONObject("""
{"id": "20a560c1", "name": "Timer1", "uri": "/chargingmanager/timers/20a560c1", "state": "idle",
"departureTime": "06:35:00", "profile": {"id": "63cf948c", "name": "Ladelimit 80, HVAC", "uri": "/x"},
"cyclic": true, "weekdays": ["monday", "tuesday", "thursday", "friday"]}
"""))
@Test
fun parsesTimer() {
assertEquals(1, timer.index)
assertFalse(timer.active)
assertEquals(setOf(MONDAY, TUESDAY, THURSDAY, FRIDAY), timer.weekdays)
assertEquals(LocalTime.of(6, 35), timer.departureTime)
assertNull(timer.departureDate)
assertEquals("63cf948c", timer.profileId)
}
@Test
fun parsesProfilesAndOptions() {
val p = parseProfile(JSONObject("""
{"id": "8269b474", "name": "Ladeort 3", "uri": "/p/8269b474", "operations": ["charge", "climate"], "maxCurrent": 16,
"minLevel": 0, "targetLevel": 100, "temperature": 10.0, "powerProvider": {"id": "c8876782", "name": "", "uri": "/x"}}
"""))
assertEquals(Profile("8269b474", "/p/8269b474", "Ladeort 3", 100, 16, listOf("charge", "climate"), "c8876782"), p)
val o = parseOptions(JSONObject("""
{"id": "3900b210", "name": "Optionen", "uri": "/p/3900b210", "operations": ["climateExtSupply", "climate"],
"maxCurrent": 32, "minLevel": 100, "targetLevel": 0, "temperature": 30.0}
"""))
assertTrue(o.climateExtSupply)
assertEquals(100, o.minLevel)
assertEquals(30.0, o.temperature, 0.0)
}
@Test
fun parsesProviderAndCarData() {
val p = parseProvider(JSONObject("""
{"id": "c8876782", "uri": "/pr/c8876782", "cyclic": false, "preferredTimeStart": "22:00:00", "preferredTimeEnd": "05:00:00",
"weekdays": ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]}
"""))
assertEquals(7, p.weekdays.size)
assertEquals(LocalTime.of(22, 0), p.start)
assertEquals(84.0, parseBattery(JSONObject("""{"name": "BEV battery", "soc": 84.0}""")).soc!!, 0.0)
assertNull(parseBattery(JSONObject("""{"soc": ""}""")).soc)
assertEquals("MATSRSECBFQTIXLFYF", parseInfo(JSONObject("""{"vehicleIdenticationNumber": "MATSRSECBFQTIXLFYF"}""")).vin)
assertEquals(LocalDate.of(2025, 11, 1), parseTimer(JSONObject(
"""{"id": "a", "name": "Timer2", "uri": "/t", "state": "scheduled", "departureTime": "07:00:00", "departureDate": "01 Nov 2025"}"""
)).departureDate)
}
@Test
fun shiftsOnlyTheTime() {
val late = timer.copy(departureTime = LocalTime.of(23, 30), weekdays = setOf(FRIDAY, SUNDAY), departureDate = LocalDate.of(2025, 12, 31))
val local = late.shifted(2 * 3600)
assertEquals(LocalTime.of(1, 30), local.departureTime)
assertEquals(late.weekdays, local.weekdays)
assertEquals(late.departureDate, local.departureDate)
assertEquals(late, local.shifted(-2 * 3600))
}
@Test
fun allows32AmpsOnlyForEUp300() {
assertEquals(16, maxCurrents("WVWZZZAAZKD000001").last())
assertEquals(32, maxCurrents("WVWZZZAAZLD000001").last())
assertEquals(32, maxCurrents("TMBZZZAAZKD000001").last())
}
@Test
fun findsNextDeparture() {
val berlin = ZoneId.of("Europe/Berlin")
// Wednesday 2025-11-12 12:00. Timer runs Mon, Tue, Thu, Fri at 06:35.
val now = ZonedDateTime.of(2025, 11, 12, 12, 0, 0, 0, berlin)
assertNull(nextDeparture(listOf(timer), now))
val (_, at) = nextDeparture(listOf(timer.copy(state = TIMER_ON)), now)!!
assertEquals(ZonedDateTime.of(2025, 11, 13, 6, 35, 0, 0, berlin), at)
}
@Test
fun pairsUnlinkedProvidersByPosition() {
fun profile(id: String) = JSONObject("""{"id": "$id", "uri": "/p/$id", "name": "$id", "operations": [], "maxCurrent": 16, "minLevel": 0, "targetLevel": 80, "temperature": 21.0}""")
fun provider(id: String) = JSONObject("""{"id": "$id", "uri": "/pr/$id", "cyclic": false, "preferredTimeStart": "00:00:00", "preferredTimeEnd": "00:00:00"}""")
val cm = chargingManagerOf(listOf(profile("options"), profile("home")), emptyList(), listOf(provider("a"), provider("b")))
assertEquals("a", cm.options!!.providerId)
assertEquals("b", cm.profiles.single().providerId)
assertNull(chargingManagerOf(listOf(profile("options"), profile("home")), emptyList(), listOf(provider("a"))).profiles.single().providerId)
}
@Test
fun matchesIgnoresExtraKeysAndNumberTypes() {
val actual = JSONObject("""{"temperature": 24, "profile": {"id": "a", "name": "Home"}, "weekdays": ["monday"]}""")
assertTrue(matches(JSONObject("""{"temperature": 24.0, "profile": {"id": "a"}, "weekdays": ["monday"]}"""), actual))
assertFalse(matches(JSONObject("""{"temperature": 25.0}"""), actual))
assertFalse(matches(JSONObject("""{"weekdays": ["monday", "friday"]}"""), actual))
assertTrue(matches(JSONObject("""{"profile": "a"}"""), actual))
assertFalse(matches(JSONObject("""{"profile": "b"}"""), actual))
}
}
Aapp/src/test/java/de/upapp/ProtocolTest.kt
@@ -0,0 +1,181 @@
package de.upapp
import org.bouncycastle.asn1.x500.X500Name
import org.bouncycastle.asn1.x509.BasicConstraints
import org.bouncycastle.asn1.x509.Extension
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder
import org.bouncycastle.crypto.util.PrivateKeyFactory
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
import org.bouncycastle.tls.Certificate
import org.bouncycastle.tls.CipherSuite
import org.bouncycastle.tls.DefaultTlsServer
import org.bouncycastle.tls.HashAlgorithm
import org.bouncycastle.tls.SignatureAlgorithm
import org.bouncycastle.tls.SignatureAndHashAlgorithm
import org.bouncycastle.tls.TlsContext
import org.bouncycastle.tls.crypto.TlsCryptoParameters
import org.bouncycastle.tls.crypto.impl.bc.BcDefaultTlsCredentialedSigner
import org.bouncycastle.tls.PSKTlsServer
import org.bouncycastle.tls.TlsPSKIdentityManager
import org.bouncycastle.tls.TlsServerProtocol
import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Test
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.math.BigInteger
import java.security.KeyPairGenerator
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.Date
class ProtocolTest {
@Test
fun decodesSegments() {
assertNull(decode(frame(7, TRANSMIT, u16(3) + byteArrayOf(1, 2))))
val (s, size) = decode(frame(0xC0E1, TRANSMIT, u16(2) + byteArrayOf(1, 2)) + frame(0, HEARTBEAT))!!
assertEquals(0xC0E1, s.port)
assertArrayEquals(byteArrayOf(1, 2), s.data)
assertEquals(7, size)
// Example from the MIBBridge protocol notes: OPEN from port 0xC0E1 to port 80.
assertArrayEquals(byteArrayOf(0xE1.toByte(), 0xC0.toByte(), 1, 0x50, 0), frame(0xC0E1, OPEN, u16(80)))
}
@Test
fun plainHttpWithChunkedBody() {
val tunnel = fakeCar { _, input, output ->
input.readHead()
output.write("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nWVW\r\n2\r\nZZ\r\n0\r\n\r\n".toByteArray())
}
val r = tunnel.open(80).use { exchange(it.input, it.output, "GET", "h", "/car/info/vin") }
assertEquals(200, r.status)
assertEquals("WVWZZ", r.text)
}
@Test
fun pskSessionMatchesCarCipher() {
val tunnel = fakeCar { _, input, output ->
val tls = TlsServerProtocol(input, output)
tls.accept(object : PSKTlsServer(BcTlsCrypto(SecureRandom()), object : TlsPSKIdentityManager {
override fun getHint(): ByteArray? = null
override fun getPSK(identity: ByteArray) = if (identity.decodeToString() == "user") "secret".toByteArray() else null
}) {
override fun getSupportedCipherSuites() = intArrayOf(CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256)
})
val head = tls.inputStream.readHead()!!
val body = """{"data": [], "request": "${head.lines().first()}"}"""
tls.outputStream.write("HTTP/1.1 200 OK\r\nContent-Length: ${body.length}\r\n\r\n$body".toByteArray())
tls.close()
}
val r = tunnel.open(443).use { ch ->
val tls = sessionTls(ch.input, ch.output, "user", "secret")
exchange(tls.inputStream, tls.outputStream, "GET", "h", "/car/batteries").also { runCatching { tls.close() } }
}
assertEquals("""{"data": [], "request": "GET /car/batteries HTTP/1.1"}""", r.text)
}
@Test
fun pinMatchesMapsAndMore() {
// Computed with the maps+more algorithm in Python.
assertEquals("304163", pin(ByteArray(16) { it.toByte() }, ByteArray(16) { (it + 16).toByte() }))
}
@Test
fun registrationChecksCertificateAndAgreesOnPin() {
val ca = TestCa()
var serverPin = ""
val tunnel = fakeCar { _, input, output ->
val tls = TlsServerProtocol(input, output)
tls.accept(object : DefaultTlsServer(BcTlsCrypto(SecureRandom())) {
override fun getSupportedCipherSuites() = intArrayOf(CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
override fun getRSASignerCredentials() = ca.signer(context, crypto as BcTlsCrypto)
override fun notifyHandshakeComplete() {
super.notifyHandshakeComplete()
serverPin = registrationPin(context)
}
})
tls.inputStream.readHead()
tls.outputStream.write("HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nuser,pass".toByteArray())
tls.close()
}
val r = tunnel.open(443).use { ch ->
val (tls, pin) = registrationTls(ch.input, ch.output, ca.root)
assertEquals(serverPin, pin)
assertEquals(6, pin.length)
exchange(tls.inputStream, tls.outputStream, "GET", "h", "/auth/x").also { runCatching { tls.close() } }
}
assertEquals("user,pass", r.text)
val stranger = TestCa()
val ch = tunnel.open(443)
assertThrows(IOException::class.java) { registrationTls(ch.input, ch.output, stranger.root) }
}
/** A root CA and a server certificate signed by it. The server certificate expired an hour ago. */
private class TestCa {
private val gen = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }
private val rootKey = gen.generateKeyPair()
private val leafKey = gen.generateKeyPair()
private val now = System.currentTimeMillis()
val root = cert("CN=Test CA", rootKey.public, true, now - 86_400_000, now + 86_400_000)
private val leaf = cert("CN=Car", leafKey.public, false, now - 7_200_000, now - 3_600_000)
private fun cert(subject: String, key: java.security.PublicKey, ca: Boolean, from: Long, to: Long): X509Certificate {
val builder = JcaX509v3CertificateBuilder(X500Name("CN=Test CA"), BigInteger.valueOf(from), Date(from), Date(to), X500Name(subject), key)
.addExtension(Extension.basicConstraints, true, BasicConstraints(ca))
return JcaX509CertificateConverter().getCertificate(builder.build(JcaContentSignerBuilder("SHA256withRSA").build(rootKey.private)))
}
fun signer(context: TlsContext, crypto: BcTlsCrypto) = BcDefaultTlsCredentialedSigner(
TlsCryptoParameters(context), crypto, PrivateKeyFactory.createKey(leafKey.private.encoded),
Certificate(arrayOf(crypto.createCertificate(leaf.encoded), crypto.createCertificate(root.encoded))),
SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.rsa),
)
}
@Test
fun reusesSessionAndRetriesAfterCarCloses() {
var connections = 0
val tunnel = fakeCar { port, input, output ->
if (port == 80) {
input.readHead()
output.write("HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nVIN".toByteArray())
return@fakeCar
}
val n = ++connections
val tls = TlsServerProtocol(input, output)
tls.accept(object : PSKTlsServer(BcTlsCrypto(SecureRandom()), object : TlsPSKIdentityManager {
override fun getHint(): ByteArray? = null
override fun getPSK(identity: ByteArray) = "secret".toByteArray()
}) {
override fun getSupportedCipherSuites() = intArrayOf(CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256)
})
// The car closes after three requests without notice.
repeat(3) {
val path = tls.inputStream.readHead()?.lines()?.first()?.split(' ')?.get(1) ?: return@repeat
val body = "$n $path"
tls.outputStream.write("HTTP/1.1 200 OK\r\nContent-Length: ${body.length}\r\n\r\n$body".toByteArray())
}
tls.close()
}
val car = Car(tunnel, storedCredentials("user,secret"))
car.connect {}
assertEquals("1 /a", car.get("a"))
assertEquals("1 /b", car.get("b"))
assertEquals("2 /c", car.get("c"))
assertEquals(2, connections)
}
private fun InputStream.readHead(): String? {
val sb = StringBuilder()
while (!sb.endsWith("\r\n\r\n")) sb.append(read().takeIf { it >= 0 }?.toChar() ?: return null)
return sb.toString()
}
private fun fakeCar(serve: (port: Int, InputStream, OutputStream) -> Unit) = CarSide(serve).tunnel
}
Abuild.gradle.kts
@@ -0,0 +1,4 @@
plugins {
id("com.android.application") version "9.4.1" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.4.20" apply false
}
Adocs/maps-and-more.md
@@ -0,0 +1,108 @@
# Findings from the maps+more app
Source: `de.volkswagen.mapsandmore`, decompiled with jadx 1.5.6.
The car protocol lives in `de.vwag.viwi.*`. The app layer lives in `vwg.vw.prerelease.app4entry.*`.
TLS runs on wolfSSL through JNI.
## Bluetooth
- `createRfcommSocketToServiceRecord(3728ED40-E416-11E4-80A0-0002A5D5C51B)`. Secure socket, bonded devices only.
- 4 attempts with 2, 4, 6, 8 s back-off (`SPPConnectThread`).
## Tunnel (`proxy/SPPConnection`)
- Same framing as MIBBridge: `port u16le | type u8`. DATA 0, CONNECT 1, CLOSE 2, HEARTBEAT 3.
- The app sends a heartbeat (`00 00 03`) every 5 s. It does not echo heartbeats.
- It drops the link after 15 s without heartbeats from the car.
- The virtual port is any unique u16.
## Registration (`ViwiRegistrationProcess`)
1. `GET /car/info/vin` on port 80 with `Connection: close`.
2. `POST /auth/registration` without a body. Expects 303 and `content-location`.
3. TLS 1.2 `ECDHE-RSA-AES128-GCM-SHA256` on port 443, then `GET <content-location>`. The body is `username,password`.
The app verifies the car certificate against a bundled root CA (`TlsSocket.ROOT_CA`, `SSL_VERIFY_PEER`):
- `CN=ViWi Certificate Authority, OU=EECF/1, O=Volkswagen GmbH Deutschland, L=Wolfsburg, ST=Niedersachsen, C=DE`
- Valid 2015-02-24 to 2055-02-14.
- SHA-256 `E7:03:40:9C:26:FB:B7:3F:57:9C:EE:6E:0C:3E:63:D1:E5:1C:E5:29:E2:66:7A:57:F1:E6:95:CA:4B:78:F7:66`
PIN (`computePin`), from the registration handshake key block:
```
digest = SHA-256(client_write_key || server_write_key) # 16 bytes each
t = little-endian uint32 of digest[0..4]
pin = t mod 1000000, left-padded to 6 digits
```
## Session
- TLS 1.2 `PSK-AES128-CBC-SHA256`. Identity = username. Key = UTF-8 bytes of the password.
- The car sends the VIN as the PSK identity hint.
- maps+more keeps one HTTP connection open. upApp does the same and reconnects once if the car closed it.
## HTTP
- Paths have one leading and one trailing slash, for example `/chargingmanager/profiles/`.
- No custom headers. POST bodies are `text/plain; charset=UTF-8`.
- Bluetooth mode uses `127.0.0.1:4080` and `127.0.0.1:4443` as hosts.
## Charging manager writes
All writes are POSTs to the element `uri`. Updates send only the changed fields.
- Timer: `{"departureDate", "departureTime", "profile": "<profile id>", "cyclic", "weekdays"}`. State alone: `{"state": "scheduled" | "idle"}`.
- Profile: changed fields of `name, operations, maxCurrent, targetLevel, powerProvider, temperature, minLevel`.
Create: `POST /chargingmanager/profiles/`. Delete: `DELETE <uri>`.
- Provider: `{"weekdays", "preferredTimeStart", "preferredTimeEnd"}`.
- Timer and provider times are UTC `HH:mm:ss`. Only the time moves. Weekdays and dates are not shifted.
- `climateExtSupply` in the first profile: "Allow AC and heating from battery" / "Klimatisieren mit Batteriestrom".
- maxCurrent: 5, 10, 13, 16. 32 only for the e-up! 300: VIN not `WVW`, or VIN[9] >= `L`.
- Temperature: 15.5 to 30.0 °C in 0.5 steps.
- Names: must not be empty. The app has no length limit.
## Other endpoints
- `/car/{info,batteries,ranges,engines,consumptions,distances,drivingstates,environments,gearboxes}/`
- `/chargingmanager/{profiles,timers,providers,batteryCharges,batteryClimates,batteryPlugs}/`
- `/media/collections/`, `/media/renderers/`, `/medialibrary/sources/`, `/mixer/audiosources/`, `/mixer/positioners`
- WebSocket `wss://host/` over the PSK session. Subscribe with
`{"type":"subscribe","event":"<path>[?fields=a,b]#<sessionId>","interval":n,"updatelimit":n}`.
Server frames have `type` subscribe, unsubscribe or data.
## Car test, 2026-10-07 (e-up! 2020, MIB2 Entry, Pixel 8a with Android 17)
- Bluetooth by service UUID, registration, PIN, certificate check and PSK session work.
- The car certificate is `CN=MIB2 Entry ViWi Server`, valid 2015-02-24 to 2055-02-14.
- Without ignition, all car values are empty strings and the profile and provider lists are empty. Timers are placeholders with empty fields.
- With ignition on, all data arrives. `batteryCharges` also has `mode` (for example `DC`), `remainingTime` (minutes), `targetSOC`, `isActive`.
- `batteryClimates.state` is `abortedIgnitionOn` while the ignition is on.
- Normal profiles can contain `climateExtSupply`. The options profile contains `charge`.
- Profiles have no `powerProvider` link on this car. There is one provider per profile, without a visible link.
- WebSocket: the car puts several JSON messages into one frame without a separator. `data` is a JSON array, not a string.
- WebSocket: subscriptions must be sent one at a time. Overlapping ones get `409 Conflict`.
- Element GETs are wrapped too: `{"status": "ok", "data": {...}}`. POST answers `{"status": "ok"}`.
- Writing a timer `state` (`scheduled` / `idle`) works and the car sends a timer event.
### Infotainment keys (`/mechanicalinput/`)
Subscribe to each element with `updatelimit` 100. With a higher limit the car merges `pushed` and `released`.
| Key | `meaning` |
|---|---|
| RADIO | `radio` |
| MEDIA | `media` |
| PHONE | `phone` |
| Soft key with flag icon | `navigation` |
| Soft key with gauge icon | `thinkBlueTrainer` |
| Soft key with car icon | `car` |
| Soft key with battery icon | `energyflow` |
| Soft key with search icon | `search` |
| MENU, X | no event |
The car also lists `gauges`, which has no key on this car.
`Right Rotary Encoder` (the right knob) sends `ticks` +1/-1 per click and `pushed`/`released`. `Left Rotary Encoder` (volume) was not tested.
- Off-peak times: maps+more has no off switch, only start and end. Start = end means off. The car uses `00:00:00`–`00:00:00` UTC for unset entries.
- The off-peak entry at the position of the options profile answers `403 Forbidden` to POST. Only the location entries are writable.
- Writing provider `weekdays`, profile create and DELETE work on the car.
Agradle.properties
@@ -0,0 +1,2 @@
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
android.useAndroidX=true
Agradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Agradlew
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# 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
if ! command -v java >/dev/null 2>&1
then
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
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Agradlew.bat
@@ -0,0 +1,93 @@
@rem^M
@rem Copyright 2015 the original author or authors.^M
@rem^M
@rem Licensed under the Apache License, Version 2.0 (the "License");^M
@rem you may not use this file except in compliance with the License.^M
@rem You may obtain a copy of the License at^M
@rem^M
@rem https://www.apache.org/licenses/LICENSE-2.0^M
@rem^M
@rem Unless required by applicable law or agreed to in writing, software^M
@rem distributed under the License is distributed on an "AS IS" BASIS,^M
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.^M
@rem See the License for the specific language governing permissions and^M
@rem limitations under the License.^M
@rem^M
@rem SPDX-License-Identifier: Apache-2.0^M
@rem^M
^M
@if "%DEBUG%"=="" @echo off^M
@rem ##########################################################################^M
@rem^M
@rem Gradle startup script for Windows^M
@rem^M
@rem ##########################################################################^M
^M
@rem Set local scope for the variables with windows NT shell^M
if "%OS%"=="Windows_NT" setlocal^M
^M
set DIRNAME=%~dp0^M
if "%DIRNAME%"=="" set DIRNAME=.^M
@rem This is normally unused^M
set APP_BASE_NAME=%~n0^M
set APP_HOME=%DIRNAME%^M
^M
@rem Resolve any "." and ".." in APP_HOME to make it shorter.^M
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi^M
^M
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.^M
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"^M
^M
@rem Find java.exe^M
if defined JAVA_HOME goto findJavaFromJavaHome^M
^M
set JAVA_EXE=java.exe^M
%JAVA_EXE% -version >NUL 2>&1^M
if %ERRORLEVEL% equ 0 goto execute^M
^M
echo. 1>&2^M
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2^M
echo. 1>&2^M
echo Please set the JAVA_HOME variable in your environment to match the 1>&2^M
echo location of your Java installation. 1>&2^M
^M
goto fail^M
^M
:findJavaFromJavaHome^M
set JAVA_HOME=%JAVA_HOME:"=%^M
set JAVA_EXE=%JAVA_HOME%/bin/java.exe^M
^M
if exist "%JAVA_EXE%" goto execute^M
^M
echo. 1>&2^M
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2^M
echo. 1>&2^M
echo Please set the JAVA_HOME variable in your environment to match the 1>&2^M
echo location of your Java installation. 1>&2^M
^M
goto fail^M
^M
:execute^M
@rem Setup the command line^M
^M
^M
^M
@rem Execute Gradle^M
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*^M
^M
:end^M
@rem End local scope for the variables with windows NT shell^M
if %ERRORLEVEL% equ 0 goto mainEnd^M
^M
:fail^M
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of^M
rem the _cmd.exe /c_ return code!^M
set EXIT_CODE=%ERRORLEVEL%^M
if %EXIT_CODE% equ 0 set EXIT_CODE=1^M
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%^M
exit /b %EXIT_CODE%^M
^M
:mainEnd^M
if "%OS%"=="Windows_NT" endlocal^M
^M
:omega^M
Asettings.gradle.kts
@@ -0,0 +1,16 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "upApp"
include(":app")