diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..13c162f
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,27 @@
+---
+BasedOnStyle: WebKit
+AccessModifierOffset: -2
+AlignEscapedNewlines: Left
+AlignOperands: Align
+AllowShortEnumsOnASingleLine: false
+RemoveBracesLLVM: true
+AllowShortFunctionsOnASingleLine: Empty
+BraceWrapping:
+ AfterFunction: false
+BreakBeforeBraces: Attach
+CompactNamespaces: true
+ConstructorInitializerAllOnOneLineOrOnePerLine: true
+Cpp11BracedListStyle: true
+IndentCaseBlocks: true
+IndentCaseLabels: true
+IndentPPDirectives: BeforeHash
+PackConstructorInitializers: Never
+SpaceBeforeCpp11BracedList: false
+SpaceInEmptyBlock: false
+SpacesInContainerLiterals: false
+NamespaceIndentation: Inner
+AlignConsecutiveMacros:
+ Enabled: true
+InsertTrailingCommas: Wrapped
+BinPackArguments: false
+BinPackParameters: false
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d90e867
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+build/
+.cache/
+.vscode
+.vs
\ No newline at end of file
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..05f42b0
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "external/imgui"]
+ path = external/imgui
+ url = https://github.com/ocornut/imgui/
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..d79ea1f
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,31 @@
+cmake_minimum_required(VERSION 3.20 FATAL_ERROR)
+
+project(DeckTX LANGUAGES CXX C VERSION 1.0.0)
+
+# Dependencies
+set(BUILD_TESTS OFF)
+set(BUILD_SHARED_LIBS OFF)
+
+# CPM
+include(external/CPM.cmake)
+
+CPMAddPackage("gh:fmtlib/fmt#11.0.1")
+CPMAddPackage("gh:libsdl-org/SDL#9406a9d527fc4436ade12ca3ce1e6c2e617e8ead")
+
+# IMGUI
+include(external/imgui.cmake)
+
+# DeckTX
+add_executable(DeckTX src/main.cpp src/crsf/crsf.cpp src/serial/serial.cpp)
+target_include_directories(DeckTX PRIVATE src)
+
+set_property(TARGET DeckTX PROPERTY CXX_STANDARD 23)
+target_link_libraries(DeckTX fmt imgui SDL3::SDL3)
+
+# Install
+if(WIN32 AND CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
+ set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Default install path" FORCE)
+endif()
+
+install(TARGETS DeckTX DESTINATION "${CMAKE_INSTALL_PREFIX}")
+install(FILES "${PROJECT_SOURCE_DIR}/LICENSE" "${PROJECT_SOURCE_DIR}/README.md" DESTINATION "${CMAKE_INSTALL_PREFIX}")
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..e72bfdd
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ef32cf9
--- /dev/null
+++ b/README.md
@@ -0,0 +1,17 @@
+### DeckTX
+
+#### Description
+
+A dedicated radio transmitter (TX) is conventionally needed to control drones, but any PC (such as the [Steam Deck](https://store.steampowered.com/steamdeck)) can operate as a TX when connected to a TX module, the component that's responsible for communicating with a drone over radio waves. This is plausible using external TX modules (such as the [BetaFPV SuperG Nano](https://betafpv.com/products/superg-nano-transmitter)) which are sold seperately from the radio transmitter, these often contain a USB port for flashing firmware but can be repurposed for communicating with the module itself.
+
+[ExpressLRS](https://www.expresslrs.org/) is the open-source firmware that most modern TX modules run, these are the target of the project and any device configuration is entirely limited to these devices. The process for connecting the module to a PC involves changing the TX/RX pins to the USB ones if available alongside disabling the backpack since it uses the USB RX/TX pins by default, which needs to be done via changing these values within the ExpressLRS's firmware directly and flashing it or if the TX module supports WiFi then using the `{DEVICE_IP}/hardware.html` page. All approaches are covered in more detail [here](https://github.com/kaack/elrs-joystick-control/blob/2b8031a285bde361b8e9e5339518a4fddbdd51d0/README.md#connecting-to-the-elrs-transmitter).
+
+#### Similar Projects
+
+The core approach is identical to [ELRS Joystick Control](https://github.com/kaack/elrs-joystick-control), the primary difference is that DeckTX is a standalone C++ application that has an integrated UI, any external applications aren't needed to utilize it. On the other hand, ELRS Joystick Control hosts a gRPC server and web-app which needs to be connected to via a browser. Another major difference, is that DeckTX can work directly on a Steam Deck running SteamOS, while ELRS Joystick Control can only work on the Steam Deck when running Windows, at the time of writing.
+
+It should be noted that both approaches have different tradeoffs, a browser-based UI isn't as lightweight or performant as a native application but has far more flexibility in terms of UI design and certain rich components such as maps to display GPS data can be trivially added, while being far more difficult to do on the UI framework used by DeckTX.
+
+#### License
+
+DeckTX is licensed at GPL 3.0 as a whole package, since the vast majority of the ecosystem (ExpressLRS, EdgeTX, etc) uses GPL licenses. Certain files are individually licensed at MIT/MPL 2.0 out of preference for a more open license, this is indicated in the SPDX header.
\ No newline at end of file
diff --git a/external/CPM.cmake b/external/CPM.cmake
new file mode 100644
index 0000000..55b883d
--- /dev/null
+++ b/external/CPM.cmake
@@ -0,0 +1,1225 @@
+# CPM.cmake - CMake's missing package manager
+# ===========================================
+# See https://github.com/cpm-cmake/CPM.cmake for usage and update instructions.
+#
+# MIT License
+# -----------
+#[[
+ Copyright (c) 2019-2023 Lars Melchior and contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+]]
+
+cmake_minimum_required(VERSION 3.14 FATAL_ERROR)
+
+# Initialize logging prefix
+if(NOT CPM_INDENT)
+ set(CPM_INDENT
+ "CPM:"
+ CACHE INTERNAL ""
+ )
+endif()
+
+if(NOT COMMAND cpm_message)
+ function(cpm_message)
+ message(${ARGV})
+ endfunction()
+endif()
+
+set(CURRENT_CPM_VERSION 0.40.0)
+
+get_filename_component(CPM_CURRENT_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}" REALPATH)
+if(CPM_DIRECTORY)
+ if(NOT CPM_DIRECTORY STREQUAL CPM_CURRENT_DIRECTORY)
+ if(CPM_VERSION VERSION_LESS CURRENT_CPM_VERSION)
+ message(
+ AUTHOR_WARNING
+ "${CPM_INDENT} \
+A dependency is using a more recent CPM version (${CURRENT_CPM_VERSION}) than the current project (${CPM_VERSION}). \
+It is recommended to upgrade CPM to the most recent version. \
+See https://github.com/cpm-cmake/CPM.cmake for more information."
+ )
+ endif()
+ if(${CMAKE_VERSION} VERSION_LESS "3.17.0")
+ include(FetchContent)
+ endif()
+ return()
+ endif()
+
+ get_property(
+ CPM_INITIALIZED GLOBAL ""
+ PROPERTY CPM_INITIALIZED
+ SET
+ )
+ if(CPM_INITIALIZED)
+ return()
+ endif()
+endif()
+
+if(CURRENT_CPM_VERSION MATCHES "development-version")
+ message(
+ WARNING "${CPM_INDENT} Your project is using an unstable development version of CPM.cmake. \
+Please update to a recent release if possible. \
+See https://github.com/cpm-cmake/CPM.cmake for details."
+ )
+endif()
+
+set_property(GLOBAL PROPERTY CPM_INITIALIZED true)
+
+macro(cpm_set_policies)
+ # the policy allows us to change options without caching
+ cmake_policy(SET CMP0077 NEW)
+ set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)
+
+ # the policy allows us to change set(CACHE) without caching
+ if(POLICY CMP0126)
+ cmake_policy(SET CMP0126 NEW)
+ set(CMAKE_POLICY_DEFAULT_CMP0126 NEW)
+ endif()
+
+ # The policy uses the download time for timestamp, instead of the timestamp in the archive. This
+ # allows for proper rebuilds when a projects url changes
+ if(POLICY CMP0135)
+ cmake_policy(SET CMP0135 NEW)
+ set(CMAKE_POLICY_DEFAULT_CMP0135 NEW)
+ endif()
+
+ # treat relative git repository paths as being relative to the parent project's remote
+ if(POLICY CMP0150)
+ cmake_policy(SET CMP0150 NEW)
+ set(CMAKE_POLICY_DEFAULT_CMP0150 NEW)
+ endif()
+endmacro()
+cpm_set_policies()
+
+option(CPM_USE_LOCAL_PACKAGES "Always try to use `find_package` to get dependencies"
+ $ENV{CPM_USE_LOCAL_PACKAGES}
+)
+option(CPM_LOCAL_PACKAGES_ONLY "Only use `find_package` to get dependencies"
+ $ENV{CPM_LOCAL_PACKAGES_ONLY}
+)
+option(CPM_DOWNLOAD_ALL "Always download dependencies from source" $ENV{CPM_DOWNLOAD_ALL})
+option(CPM_DONT_UPDATE_MODULE_PATH "Don't update the module path to allow using find_package"
+ $ENV{CPM_DONT_UPDATE_MODULE_PATH}
+)
+option(CPM_DONT_CREATE_PACKAGE_LOCK "Don't create a package lock file in the binary path"
+ $ENV{CPM_DONT_CREATE_PACKAGE_LOCK}
+)
+option(CPM_INCLUDE_ALL_IN_PACKAGE_LOCK
+ "Add all packages added through CPM.cmake to the package lock"
+ $ENV{CPM_INCLUDE_ALL_IN_PACKAGE_LOCK}
+)
+option(CPM_USE_NAMED_CACHE_DIRECTORIES
+ "Use additional directory of package name in cache on the most nested level."
+ $ENV{CPM_USE_NAMED_CACHE_DIRECTORIES}
+)
+
+set(CPM_VERSION
+ ${CURRENT_CPM_VERSION}
+ CACHE INTERNAL ""
+)
+set(CPM_DIRECTORY
+ ${CPM_CURRENT_DIRECTORY}
+ CACHE INTERNAL ""
+)
+set(CPM_FILE
+ ${CMAKE_CURRENT_LIST_FILE}
+ CACHE INTERNAL ""
+)
+set(CPM_PACKAGES
+ ""
+ CACHE INTERNAL ""
+)
+set(CPM_DRY_RUN
+ OFF
+ CACHE INTERNAL "Don't download or configure dependencies (for testing)"
+)
+
+if(DEFINED ENV{CPM_SOURCE_CACHE})
+ set(CPM_SOURCE_CACHE_DEFAULT $ENV{CPM_SOURCE_CACHE})
+else()
+ set(CPM_SOURCE_CACHE_DEFAULT OFF)
+endif()
+
+set(CPM_SOURCE_CACHE
+ ${CPM_SOURCE_CACHE_DEFAULT}
+ CACHE PATH "Directory to download CPM dependencies"
+)
+
+if(NOT CPM_DONT_UPDATE_MODULE_PATH)
+ set(CPM_MODULE_PATH
+ "${CMAKE_BINARY_DIR}/CPM_modules"
+ CACHE INTERNAL ""
+ )
+ # remove old modules
+ file(REMOVE_RECURSE ${CPM_MODULE_PATH})
+ file(MAKE_DIRECTORY ${CPM_MODULE_PATH})
+ # locally added CPM modules should override global packages
+ set(CMAKE_MODULE_PATH "${CPM_MODULE_PATH};${CMAKE_MODULE_PATH}")
+endif()
+
+if(NOT CPM_DONT_CREATE_PACKAGE_LOCK)
+ set(CPM_PACKAGE_LOCK_FILE
+ "${CMAKE_BINARY_DIR}/cpm-package-lock.cmake"
+ CACHE INTERNAL ""
+ )
+ file(WRITE ${CPM_PACKAGE_LOCK_FILE}
+ "# CPM Package Lock\n# This file should be committed to version control\n\n"
+ )
+endif()
+
+include(FetchContent)
+
+# Try to infer package name from git repository uri (path or url)
+function(cpm_package_name_from_git_uri URI RESULT)
+ if("${URI}" MATCHES "([^/:]+)/?.git/?$")
+ set(${RESULT}
+ ${CMAKE_MATCH_1}
+ PARENT_SCOPE
+ )
+ else()
+ unset(${RESULT} PARENT_SCOPE)
+ endif()
+endfunction()
+
+# Try to infer package name and version from a url
+function(cpm_package_name_and_ver_from_url url outName outVer)
+ if(url MATCHES "[/\\?]([a-zA-Z0-9_\\.-]+)\\.(tar|tar\\.gz|tar\\.bz2|zip|ZIP)(\\?|/|$)")
+ # We matched an archive
+ set(filename "${CMAKE_MATCH_1}")
+
+ if(filename MATCHES "([a-zA-Z0-9_\\.-]+)[_-]v?(([0-9]+\\.)*[0-9]+[a-zA-Z0-9]*)")
+ # We matched - (ie foo-1.2.3)
+ set(${outName}
+ "${CMAKE_MATCH_1}"
+ PARENT_SCOPE
+ )
+ set(${outVer}
+ "${CMAKE_MATCH_2}"
+ PARENT_SCOPE
+ )
+ elseif(filename MATCHES "(([0-9]+\\.)+[0-9]+[a-zA-Z0-9]*)")
+ # We couldn't find a name, but we found a version
+ #
+ # In many cases (which we don't handle here) the url would look something like
+ # `irrelevant/ACTUAL_PACKAGE_NAME/irrelevant/1.2.3.zip`. In such a case we can't possibly
+ # distinguish the package name from the irrelevant bits. Moreover if we try to match the
+ # package name from the filename, we'd get bogus at best.
+ unset(${outName} PARENT_SCOPE)
+ set(${outVer}
+ "${CMAKE_MATCH_1}"
+ PARENT_SCOPE
+ )
+ else()
+ # Boldly assume that the file name is the package name.
+ #
+ # Yes, something like `irrelevant/ACTUAL_NAME/irrelevant/download.zip` will ruin our day, but
+ # such cases should be quite rare. No popular service does this... we think.
+ set(${outName}
+ "${filename}"
+ PARENT_SCOPE
+ )
+ unset(${outVer} PARENT_SCOPE)
+ endif()
+ else()
+ # No ideas yet what to do with non-archives
+ unset(${outName} PARENT_SCOPE)
+ unset(${outVer} PARENT_SCOPE)
+ endif()
+endfunction()
+
+function(cpm_find_package NAME VERSION)
+ string(REPLACE " " ";" EXTRA_ARGS "${ARGN}")
+ find_package(${NAME} ${VERSION} ${EXTRA_ARGS} QUIET)
+ if(${CPM_ARGS_NAME}_FOUND)
+ if(DEFINED ${CPM_ARGS_NAME}_VERSION)
+ set(VERSION ${${CPM_ARGS_NAME}_VERSION})
+ endif()
+ cpm_message(STATUS "${CPM_INDENT} Using local package ${CPM_ARGS_NAME}@${VERSION}")
+ CPMRegisterPackage(${CPM_ARGS_NAME} "${VERSION}")
+ set(CPM_PACKAGE_FOUND
+ YES
+ PARENT_SCOPE
+ )
+ else()
+ set(CPM_PACKAGE_FOUND
+ NO
+ PARENT_SCOPE
+ )
+ endif()
+endfunction()
+
+# Create a custom FindXXX.cmake module for a CPM package This prevents `find_package(NAME)` from
+# finding the system library
+function(cpm_create_module_file Name)
+ if(NOT CPM_DONT_UPDATE_MODULE_PATH)
+ # erase any previous modules
+ file(WRITE ${CPM_MODULE_PATH}/Find${Name}.cmake
+ "include(\"${CPM_FILE}\")\n${ARGN}\nset(${Name}_FOUND TRUE)"
+ )
+ endif()
+endfunction()
+
+# Find a package locally or fallback to CPMAddPackage
+function(CPMFindPackage)
+ set(oneValueArgs NAME VERSION GIT_TAG FIND_PACKAGE_ARGUMENTS)
+
+ cmake_parse_arguments(CPM_ARGS "" "${oneValueArgs}" "" ${ARGN})
+
+ if(NOT DEFINED CPM_ARGS_VERSION)
+ if(DEFINED CPM_ARGS_GIT_TAG)
+ cpm_get_version_from_git_tag("${CPM_ARGS_GIT_TAG}" CPM_ARGS_VERSION)
+ endif()
+ endif()
+
+ set(downloadPackage ${CPM_DOWNLOAD_ALL})
+ if(DEFINED CPM_DOWNLOAD_${CPM_ARGS_NAME})
+ set(downloadPackage ${CPM_DOWNLOAD_${CPM_ARGS_NAME}})
+ elseif(DEFINED ENV{CPM_DOWNLOAD_${CPM_ARGS_NAME}})
+ set(downloadPackage $ENV{CPM_DOWNLOAD_${CPM_ARGS_NAME}})
+ endif()
+ if(downloadPackage)
+ CPMAddPackage(${ARGN})
+ cpm_export_variables(${CPM_ARGS_NAME})
+ return()
+ endif()
+
+ cpm_find_package(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}" ${CPM_ARGS_FIND_PACKAGE_ARGUMENTS})
+
+ if(NOT CPM_PACKAGE_FOUND)
+ CPMAddPackage(${ARGN})
+ cpm_export_variables(${CPM_ARGS_NAME})
+ endif()
+
+endfunction()
+
+# checks if a package has been added before
+function(cpm_check_if_package_already_added CPM_ARGS_NAME CPM_ARGS_VERSION)
+ if("${CPM_ARGS_NAME}" IN_LIST CPM_PACKAGES)
+ CPMGetPackageVersion(${CPM_ARGS_NAME} CPM_PACKAGE_VERSION)
+ if("${CPM_PACKAGE_VERSION}" VERSION_LESS "${CPM_ARGS_VERSION}")
+ message(
+ WARNING
+ "${CPM_INDENT} Requires a newer version of ${CPM_ARGS_NAME} (${CPM_ARGS_VERSION}) than currently included (${CPM_PACKAGE_VERSION})."
+ )
+ endif()
+ cpm_get_fetch_properties(${CPM_ARGS_NAME})
+ set(${CPM_ARGS_NAME}_ADDED NO)
+ set(CPM_PACKAGE_ALREADY_ADDED
+ YES
+ PARENT_SCOPE
+ )
+ cpm_export_variables(${CPM_ARGS_NAME})
+ else()
+ set(CPM_PACKAGE_ALREADY_ADDED
+ NO
+ PARENT_SCOPE
+ )
+ endif()
+endfunction()
+
+# Parse the argument of CPMAddPackage in case a single one was provided and convert it to a list of
+# arguments which can then be parsed idiomatically. For example gh:foo/bar@1.2.3 will be converted
+# to: GITHUB_REPOSITORY;foo/bar;VERSION;1.2.3
+function(cpm_parse_add_package_single_arg arg outArgs)
+ # Look for a scheme
+ if("${arg}" MATCHES "^([a-zA-Z]+):(.+)$")
+ string(TOLOWER "${CMAKE_MATCH_1}" scheme)
+ set(uri "${CMAKE_MATCH_2}")
+
+ # Check for CPM-specific schemes
+ if(scheme STREQUAL "gh")
+ set(out "GITHUB_REPOSITORY;${uri}")
+ set(packageType "git")
+ elseif(scheme STREQUAL "gl")
+ set(out "GITLAB_REPOSITORY;${uri}")
+ set(packageType "git")
+ elseif(scheme STREQUAL "bb")
+ set(out "BITBUCKET_REPOSITORY;${uri}")
+ set(packageType "git")
+ # A CPM-specific scheme was not found. Looks like this is a generic URL so try to determine
+ # type
+ elseif(arg MATCHES ".git/?(@|#|$)")
+ set(out "GIT_REPOSITORY;${arg}")
+ set(packageType "git")
+ else()
+ # Fall back to a URL
+ set(out "URL;${arg}")
+ set(packageType "archive")
+
+ # We could also check for SVN since FetchContent supports it, but SVN is so rare these days.
+ # We just won't bother with the additional complexity it will induce in this function. SVN is
+ # done by multi-arg
+ endif()
+ else()
+ if(arg MATCHES ".git/?(@|#|$)")
+ set(out "GIT_REPOSITORY;${arg}")
+ set(packageType "git")
+ else()
+ # Give up
+ message(FATAL_ERROR "${CPM_INDENT} Can't determine package type of '${arg}'")
+ endif()
+ endif()
+
+ # For all packages we interpret @... as version. Only replace the last occurrence. Thus URIs
+ # containing '@' can be used
+ string(REGEX REPLACE "@([^@]+)$" ";VERSION;\\1" out "${out}")
+
+ # Parse the rest according to package type
+ if(packageType STREQUAL "git")
+ # For git repos we interpret #... as a tag or branch or commit hash
+ string(REGEX REPLACE "#([^#]+)$" ";GIT_TAG;\\1" out "${out}")
+ elseif(packageType STREQUAL "archive")
+ # For archives we interpret #... as a URL hash.
+ string(REGEX REPLACE "#([^#]+)$" ";URL_HASH;\\1" out "${out}")
+ # We don't try to parse the version if it's not provided explicitly. cpm_get_version_from_url
+ # should do this at a later point
+ else()
+ # We should never get here. This is an assertion and hitting it means there's a problem with the
+ # code above. A packageType was set, but not handled by this if-else.
+ message(FATAL_ERROR "${CPM_INDENT} Unsupported package type '${packageType}' of '${arg}'")
+ endif()
+
+ set(${outArgs}
+ ${out}
+ PARENT_SCOPE
+ )
+endfunction()
+
+# Check that the working directory for a git repo is clean
+function(cpm_check_git_working_dir_is_clean repoPath gitTag isClean)
+
+ find_package(Git REQUIRED)
+
+ if(NOT GIT_EXECUTABLE)
+ # No git executable, assume directory is clean
+ set(${isClean}
+ TRUE
+ PARENT_SCOPE
+ )
+ return()
+ endif()
+
+ # check for uncommitted changes
+ execute_process(
+ COMMAND ${GIT_EXECUTABLE} status --porcelain
+ RESULT_VARIABLE resultGitStatus
+ OUTPUT_VARIABLE repoStatus
+ OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET
+ WORKING_DIRECTORY ${repoPath}
+ )
+ if(resultGitStatus)
+ # not supposed to happen, assume clean anyway
+ message(WARNING "${CPM_INDENT} Calling git status on folder ${repoPath} failed")
+ set(${isClean}
+ TRUE
+ PARENT_SCOPE
+ )
+ return()
+ endif()
+
+ if(NOT "${repoStatus}" STREQUAL "")
+ set(${isClean}
+ FALSE
+ PARENT_SCOPE
+ )
+ return()
+ endif()
+
+ # check for committed changes
+ execute_process(
+ COMMAND ${GIT_EXECUTABLE} diff -s --exit-code ${gitTag}
+ RESULT_VARIABLE resultGitDiff
+ OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_QUIET
+ WORKING_DIRECTORY ${repoPath}
+ )
+
+ if(${resultGitDiff} EQUAL 0)
+ set(${isClean}
+ TRUE
+ PARENT_SCOPE
+ )
+ else()
+ set(${isClean}
+ FALSE
+ PARENT_SCOPE
+ )
+ endif()
+
+endfunction()
+
+# Add PATCH_COMMAND to CPM_ARGS_UNPARSED_ARGUMENTS. This method consumes a list of files in ARGN
+# then generates a `PATCH_COMMAND` appropriate for `ExternalProject_Add()`. This command is appended
+# to the parent scope's `CPM_ARGS_UNPARSED_ARGUMENTS`.
+function(cpm_add_patches)
+ # Return if no patch files are supplied.
+ if(NOT ARGN)
+ return()
+ endif()
+
+ # Find the patch program.
+ find_program(PATCH_EXECUTABLE patch)
+ if(WIN32 AND NOT PATCH_EXECUTABLE)
+ # The Windows git executable is distributed with patch.exe. Find the path to the executable, if
+ # it exists, then search `../../usr/bin` for patch.exe.
+ find_package(Git QUIET)
+ if(GIT_EXECUTABLE)
+ get_filename_component(extra_search_path ${GIT_EXECUTABLE} DIRECTORY)
+ get_filename_component(extra_search_path ${extra_search_path} DIRECTORY)
+ get_filename_component(extra_search_path ${extra_search_path} DIRECTORY)
+ find_program(PATCH_EXECUTABLE patch HINTS "${extra_search_path}/usr/bin")
+ endif()
+ endif()
+ if(NOT PATCH_EXECUTABLE)
+ message(FATAL_ERROR "Couldn't find `patch` executable to use with PATCHES keyword.")
+ endif()
+
+ # Create a temporary
+ set(temp_list ${CPM_ARGS_UNPARSED_ARGUMENTS})
+
+ # Ensure each file exists (or error out) and add it to the list.
+ set(first_item True)
+ foreach(PATCH_FILE ${ARGN})
+ # Make sure the patch file exists, if we can't find it, try again in the current directory.
+ if(NOT EXISTS "${PATCH_FILE}")
+ if(NOT EXISTS "${CMAKE_CURRENT_LIST_DIR}/${PATCH_FILE}")
+ message(FATAL_ERROR "Couldn't find patch file: '${PATCH_FILE}'")
+ endif()
+ set(PATCH_FILE "${CMAKE_CURRENT_LIST_DIR}/${PATCH_FILE}")
+ endif()
+
+ # Convert to absolute path for use with patch file command.
+ get_filename_component(PATCH_FILE "${PATCH_FILE}" ABSOLUTE)
+
+ # The first patch entry must be preceded by "PATCH_COMMAND" while the following items are
+ # preceded by "&&".
+ if(first_item)
+ set(first_item False)
+ list(APPEND temp_list "PATCH_COMMAND")
+ else()
+ list(APPEND temp_list "&&")
+ endif()
+ # Add the patch command to the list
+ list(APPEND temp_list "${PATCH_EXECUTABLE}" "-p1" "<" "${PATCH_FILE}")
+ endforeach()
+
+ # Move temp out into parent scope.
+ set(CPM_ARGS_UNPARSED_ARGUMENTS
+ ${temp_list}
+ PARENT_SCOPE
+ )
+
+endfunction()
+
+# method to overwrite internal FetchContent properties, to allow using CPM.cmake to overload
+# FetchContent calls. As these are internal cmake properties, this method should be used carefully
+# and may need modification in future CMake versions. Source:
+# https://github.com/Kitware/CMake/blob/dc3d0b5a0a7d26d43d6cfeb511e224533b5d188f/Modules/FetchContent.cmake#L1152
+function(cpm_override_fetchcontent contentName)
+ cmake_parse_arguments(PARSE_ARGV 1 arg "" "SOURCE_DIR;BINARY_DIR" "")
+ if(NOT "${arg_UNPARSED_ARGUMENTS}" STREQUAL "")
+ message(FATAL_ERROR "${CPM_INDENT} Unsupported arguments: ${arg_UNPARSED_ARGUMENTS}")
+ endif()
+
+ string(TOLOWER ${contentName} contentNameLower)
+ set(prefix "_FetchContent_${contentNameLower}")
+
+ set(propertyName "${prefix}_sourceDir")
+ define_property(
+ GLOBAL
+ PROPERTY ${propertyName}
+ BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
+ FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
+ )
+ set_property(GLOBAL PROPERTY ${propertyName} "${arg_SOURCE_DIR}")
+
+ set(propertyName "${prefix}_binaryDir")
+ define_property(
+ GLOBAL
+ PROPERTY ${propertyName}
+ BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
+ FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
+ )
+ set_property(GLOBAL PROPERTY ${propertyName} "${arg_BINARY_DIR}")
+
+ set(propertyName "${prefix}_populated")
+ define_property(
+ GLOBAL
+ PROPERTY ${propertyName}
+ BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
+ FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
+ )
+ set_property(GLOBAL PROPERTY ${propertyName} TRUE)
+endfunction()
+
+# Download and add a package from source
+function(CPMAddPackage)
+ cpm_set_policies()
+
+ list(LENGTH ARGN argnLength)
+ if(argnLength EQUAL 1)
+ cpm_parse_add_package_single_arg("${ARGN}" ARGN)
+
+ # The shorthand syntax implies EXCLUDE_FROM_ALL and SYSTEM
+ set(ARGN "${ARGN};EXCLUDE_FROM_ALL;YES;SYSTEM;YES;")
+ endif()
+
+ set(oneValueArgs
+ NAME
+ FORCE
+ VERSION
+ GIT_TAG
+ DOWNLOAD_ONLY
+ GITHUB_REPOSITORY
+ GITLAB_REPOSITORY
+ BITBUCKET_REPOSITORY
+ GIT_REPOSITORY
+ SOURCE_DIR
+ FIND_PACKAGE_ARGUMENTS
+ NO_CACHE
+ SYSTEM
+ GIT_SHALLOW
+ EXCLUDE_FROM_ALL
+ SOURCE_SUBDIR
+ CUSTOM_CACHE_KEY
+ )
+
+ set(multiValueArgs URL OPTIONS DOWNLOAD_COMMAND PATCHES)
+
+ cmake_parse_arguments(CPM_ARGS "" "${oneValueArgs}" "${multiValueArgs}" "${ARGN}")
+
+ # Set default values for arguments
+
+ if(NOT DEFINED CPM_ARGS_VERSION)
+ if(DEFINED CPM_ARGS_GIT_TAG)
+ cpm_get_version_from_git_tag("${CPM_ARGS_GIT_TAG}" CPM_ARGS_VERSION)
+ endif()
+ endif()
+
+ if(CPM_ARGS_DOWNLOAD_ONLY)
+ set(DOWNLOAD_ONLY ${CPM_ARGS_DOWNLOAD_ONLY})
+ else()
+ set(DOWNLOAD_ONLY NO)
+ endif()
+
+ if(DEFINED CPM_ARGS_GITHUB_REPOSITORY)
+ set(CPM_ARGS_GIT_REPOSITORY "https://github.com/${CPM_ARGS_GITHUB_REPOSITORY}.git")
+ elseif(DEFINED CPM_ARGS_GITLAB_REPOSITORY)
+ set(CPM_ARGS_GIT_REPOSITORY "https://gitlab.com/${CPM_ARGS_GITLAB_REPOSITORY}.git")
+ elseif(DEFINED CPM_ARGS_BITBUCKET_REPOSITORY)
+ set(CPM_ARGS_GIT_REPOSITORY "https://bitbucket.org/${CPM_ARGS_BITBUCKET_REPOSITORY}.git")
+ endif()
+
+ if(DEFINED CPM_ARGS_GIT_REPOSITORY)
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_REPOSITORY ${CPM_ARGS_GIT_REPOSITORY})
+ if(NOT DEFINED CPM_ARGS_GIT_TAG)
+ set(CPM_ARGS_GIT_TAG v${CPM_ARGS_VERSION})
+ endif()
+
+ # If a name wasn't provided, try to infer it from the git repo
+ if(NOT DEFINED CPM_ARGS_NAME)
+ cpm_package_name_from_git_uri(${CPM_ARGS_GIT_REPOSITORY} CPM_ARGS_NAME)
+ endif()
+ endif()
+
+ set(CPM_SKIP_FETCH FALSE)
+
+ if(DEFINED CPM_ARGS_GIT_TAG)
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_TAG ${CPM_ARGS_GIT_TAG})
+ # If GIT_SHALLOW is explicitly specified, honor the value.
+ if(DEFINED CPM_ARGS_GIT_SHALLOW)
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_SHALLOW ${CPM_ARGS_GIT_SHALLOW})
+ endif()
+ endif()
+
+ if(DEFINED CPM_ARGS_URL)
+ # If a name or version aren't provided, try to infer them from the URL
+ list(GET CPM_ARGS_URL 0 firstUrl)
+ cpm_package_name_and_ver_from_url(${firstUrl} nameFromUrl verFromUrl)
+ # If we fail to obtain name and version from the first URL, we could try other URLs if any.
+ # However multiple URLs are expected to be quite rare, so for now we won't bother.
+
+ # If the caller provided their own name and version, they trump the inferred ones.
+ if(NOT DEFINED CPM_ARGS_NAME)
+ set(CPM_ARGS_NAME ${nameFromUrl})
+ endif()
+ if(NOT DEFINED CPM_ARGS_VERSION)
+ set(CPM_ARGS_VERSION ${verFromUrl})
+ endif()
+
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS URL "${CPM_ARGS_URL}")
+ endif()
+
+ # Check for required arguments
+
+ if(NOT DEFINED CPM_ARGS_NAME)
+ message(
+ FATAL_ERROR
+ "${CPM_INDENT} 'NAME' was not provided and couldn't be automatically inferred for package added with arguments: '${ARGN}'"
+ )
+ endif()
+
+ # Check if package has been added before
+ cpm_check_if_package_already_added(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}")
+ if(CPM_PACKAGE_ALREADY_ADDED)
+ cpm_export_variables(${CPM_ARGS_NAME})
+ return()
+ endif()
+
+ # Check for manual overrides
+ if(NOT CPM_ARGS_FORCE AND NOT "${CPM_${CPM_ARGS_NAME}_SOURCE}" STREQUAL "")
+ set(PACKAGE_SOURCE ${CPM_${CPM_ARGS_NAME}_SOURCE})
+ set(CPM_${CPM_ARGS_NAME}_SOURCE "")
+ CPMAddPackage(
+ NAME "${CPM_ARGS_NAME}"
+ SOURCE_DIR "${PACKAGE_SOURCE}"
+ EXCLUDE_FROM_ALL "${CPM_ARGS_EXCLUDE_FROM_ALL}"
+ SYSTEM "${CPM_ARGS_SYSTEM}"
+ PATCHES "${CPM_ARGS_PATCHES}"
+ OPTIONS "${CPM_ARGS_OPTIONS}"
+ SOURCE_SUBDIR "${CPM_ARGS_SOURCE_SUBDIR}"
+ DOWNLOAD_ONLY "${DOWNLOAD_ONLY}"
+ FORCE True
+ )
+ cpm_export_variables(${CPM_ARGS_NAME})
+ return()
+ endif()
+
+ # Check for available declaration
+ if(NOT CPM_ARGS_FORCE AND NOT "${CPM_DECLARATION_${CPM_ARGS_NAME}}" STREQUAL "")
+ set(declaration ${CPM_DECLARATION_${CPM_ARGS_NAME}})
+ set(CPM_DECLARATION_${CPM_ARGS_NAME} "")
+ CPMAddPackage(${declaration})
+ cpm_export_variables(${CPM_ARGS_NAME})
+ # checking again to ensure version and option compatibility
+ cpm_check_if_package_already_added(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}")
+ return()
+ endif()
+
+ if(NOT CPM_ARGS_FORCE)
+ if(CPM_USE_LOCAL_PACKAGES OR CPM_LOCAL_PACKAGES_ONLY)
+ cpm_find_package(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}" ${CPM_ARGS_FIND_PACKAGE_ARGUMENTS})
+
+ if(CPM_PACKAGE_FOUND)
+ cpm_export_variables(${CPM_ARGS_NAME})
+ return()
+ endif()
+
+ if(CPM_LOCAL_PACKAGES_ONLY)
+ message(
+ SEND_ERROR
+ "${CPM_INDENT} ${CPM_ARGS_NAME} not found via find_package(${CPM_ARGS_NAME} ${CPM_ARGS_VERSION})"
+ )
+ endif()
+ endif()
+ endif()
+
+ CPMRegisterPackage("${CPM_ARGS_NAME}" "${CPM_ARGS_VERSION}")
+
+ if(DEFINED CPM_ARGS_GIT_TAG)
+ set(PACKAGE_INFO "${CPM_ARGS_GIT_TAG}")
+ elseif(DEFINED CPM_ARGS_SOURCE_DIR)
+ set(PACKAGE_INFO "${CPM_ARGS_SOURCE_DIR}")
+ else()
+ set(PACKAGE_INFO "${CPM_ARGS_VERSION}")
+ endif()
+
+ if(DEFINED FETCHCONTENT_BASE_DIR)
+ # respect user's FETCHCONTENT_BASE_DIR if set
+ set(CPM_FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR})
+ else()
+ set(CPM_FETCHCONTENT_BASE_DIR ${CMAKE_BINARY_DIR}/_deps)
+ endif()
+
+ cpm_add_patches(${CPM_ARGS_PATCHES})
+
+ if(DEFINED CPM_ARGS_DOWNLOAD_COMMAND)
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS DOWNLOAD_COMMAND ${CPM_ARGS_DOWNLOAD_COMMAND})
+ elseif(DEFINED CPM_ARGS_SOURCE_DIR)
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS SOURCE_DIR ${CPM_ARGS_SOURCE_DIR})
+ if(NOT IS_ABSOLUTE ${CPM_ARGS_SOURCE_DIR})
+ # Expand `CPM_ARGS_SOURCE_DIR` relative path. This is important because EXISTS doesn't work
+ # for relative paths.
+ get_filename_component(
+ source_directory ${CPM_ARGS_SOURCE_DIR} REALPATH BASE_DIR ${CMAKE_CURRENT_BINARY_DIR}
+ )
+ else()
+ set(source_directory ${CPM_ARGS_SOURCE_DIR})
+ endif()
+ if(NOT EXISTS ${source_directory})
+ string(TOLOWER ${CPM_ARGS_NAME} lower_case_name)
+ # remove timestamps so CMake will re-download the dependency
+ file(REMOVE_RECURSE "${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-subbuild")
+ endif()
+ elseif(CPM_SOURCE_CACHE AND NOT CPM_ARGS_NO_CACHE)
+ string(TOLOWER ${CPM_ARGS_NAME} lower_case_name)
+ set(origin_parameters ${CPM_ARGS_UNPARSED_ARGUMENTS})
+ list(SORT origin_parameters)
+ if(CPM_ARGS_CUSTOM_CACHE_KEY)
+ # Application set a custom unique directory name
+ set(download_directory ${CPM_SOURCE_CACHE}/${lower_case_name}/${CPM_ARGS_CUSTOM_CACHE_KEY})
+ elseif(CPM_USE_NAMED_CACHE_DIRECTORIES)
+ string(SHA1 origin_hash "${origin_parameters};NEW_CACHE_STRUCTURE_TAG")
+ set(download_directory ${CPM_SOURCE_CACHE}/${lower_case_name}/${origin_hash}/${CPM_ARGS_NAME})
+ else()
+ string(SHA1 origin_hash "${origin_parameters}")
+ set(download_directory ${CPM_SOURCE_CACHE}/${lower_case_name}/${origin_hash})
+ endif()
+ # Expand `download_directory` relative path. This is important because EXISTS doesn't work for
+ # relative paths.
+ get_filename_component(download_directory ${download_directory} ABSOLUTE)
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS SOURCE_DIR ${download_directory})
+
+ if(CPM_SOURCE_CACHE)
+ file(LOCK ${download_directory}/../cmake.lock)
+ endif()
+
+ if(EXISTS ${download_directory})
+ if(CPM_SOURCE_CACHE)
+ file(LOCK ${download_directory}/../cmake.lock RELEASE)
+ endif()
+
+ cpm_store_fetch_properties(
+ ${CPM_ARGS_NAME} "${download_directory}"
+ "${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-build"
+ )
+ cpm_get_fetch_properties("${CPM_ARGS_NAME}")
+
+ if(DEFINED CPM_ARGS_GIT_TAG AND NOT (PATCH_COMMAND IN_LIST CPM_ARGS_UNPARSED_ARGUMENTS))
+ # warn if cache has been changed since checkout
+ cpm_check_git_working_dir_is_clean(${download_directory} ${CPM_ARGS_GIT_TAG} IS_CLEAN)
+ if(NOT ${IS_CLEAN})
+ message(
+ WARNING "${CPM_INDENT} Cache for ${CPM_ARGS_NAME} (${download_directory}) is dirty"
+ )
+ endif()
+ endif()
+
+ cpm_add_subdirectory(
+ "${CPM_ARGS_NAME}"
+ "${DOWNLOAD_ONLY}"
+ "${${CPM_ARGS_NAME}_SOURCE_DIR}/${CPM_ARGS_SOURCE_SUBDIR}"
+ "${${CPM_ARGS_NAME}_BINARY_DIR}"
+ "${CPM_ARGS_EXCLUDE_FROM_ALL}"
+ "${CPM_ARGS_SYSTEM}"
+ "${CPM_ARGS_OPTIONS}"
+ )
+ set(PACKAGE_INFO "${PACKAGE_INFO} at ${download_directory}")
+
+ # As the source dir is already cached/populated, we override the call to FetchContent.
+ set(CPM_SKIP_FETCH TRUE)
+ cpm_override_fetchcontent(
+ "${lower_case_name}" SOURCE_DIR "${${CPM_ARGS_NAME}_SOURCE_DIR}/${CPM_ARGS_SOURCE_SUBDIR}"
+ BINARY_DIR "${${CPM_ARGS_NAME}_BINARY_DIR}"
+ )
+
+ else()
+ # Enable shallow clone when GIT_TAG is not a commit hash. Our guess may not be accurate, but
+ # it should guarantee no commit hash get mis-detected.
+ if(NOT DEFINED CPM_ARGS_GIT_SHALLOW)
+ cpm_is_git_tag_commit_hash("${CPM_ARGS_GIT_TAG}" IS_HASH)
+ if(NOT ${IS_HASH})
+ list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_SHALLOW TRUE)
+ endif()
+ endif()
+
+ # remove timestamps so CMake will re-download the dependency
+ file(REMOVE_RECURSE ${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-subbuild)
+ set(PACKAGE_INFO "${PACKAGE_INFO} to ${download_directory}")
+ endif()
+ endif()
+
+ cpm_create_module_file(${CPM_ARGS_NAME} "CPMAddPackage(\"${ARGN}\")")
+
+ if(CPM_PACKAGE_LOCK_ENABLED)
+ if((CPM_ARGS_VERSION AND NOT CPM_ARGS_SOURCE_DIR) OR CPM_INCLUDE_ALL_IN_PACKAGE_LOCK)
+ cpm_add_to_package_lock(${CPM_ARGS_NAME} "${ARGN}")
+ elseif(CPM_ARGS_SOURCE_DIR)
+ cpm_add_comment_to_package_lock(${CPM_ARGS_NAME} "local directory")
+ else()
+ cpm_add_comment_to_package_lock(${CPM_ARGS_NAME} "${ARGN}")
+ endif()
+ endif()
+
+ cpm_message(
+ STATUS "${CPM_INDENT} Adding package ${CPM_ARGS_NAME}@${CPM_ARGS_VERSION} (${PACKAGE_INFO})"
+ )
+
+ if(NOT CPM_SKIP_FETCH)
+ cpm_declare_fetch(
+ "${CPM_ARGS_NAME}" "${CPM_ARGS_VERSION}" "${PACKAGE_INFO}" "${CPM_ARGS_UNPARSED_ARGUMENTS}"
+ )
+ cpm_fetch_package("${CPM_ARGS_NAME}" populated)
+ if(CPM_SOURCE_CACHE AND download_directory)
+ file(LOCK ${download_directory}/../cmake.lock RELEASE)
+ endif()
+ if(${populated})
+ cpm_add_subdirectory(
+ "${CPM_ARGS_NAME}"
+ "${DOWNLOAD_ONLY}"
+ "${${CPM_ARGS_NAME}_SOURCE_DIR}/${CPM_ARGS_SOURCE_SUBDIR}"
+ "${${CPM_ARGS_NAME}_BINARY_DIR}"
+ "${CPM_ARGS_EXCLUDE_FROM_ALL}"
+ "${CPM_ARGS_SYSTEM}"
+ "${CPM_ARGS_OPTIONS}"
+ )
+ endif()
+ cpm_get_fetch_properties("${CPM_ARGS_NAME}")
+ endif()
+
+ set(${CPM_ARGS_NAME}_ADDED YES)
+ cpm_export_variables("${CPM_ARGS_NAME}")
+endfunction()
+
+# Fetch a previously declared package
+macro(CPMGetPackage Name)
+ if(DEFINED "CPM_DECLARATION_${Name}")
+ CPMAddPackage(NAME ${Name})
+ else()
+ message(SEND_ERROR "${CPM_INDENT} Cannot retrieve package ${Name}: no declaration available")
+ endif()
+endmacro()
+
+# export variables available to the caller to the parent scope expects ${CPM_ARGS_NAME} to be set
+macro(cpm_export_variables name)
+ set(${name}_SOURCE_DIR
+ "${${name}_SOURCE_DIR}"
+ PARENT_SCOPE
+ )
+ set(${name}_BINARY_DIR
+ "${${name}_BINARY_DIR}"
+ PARENT_SCOPE
+ )
+ set(${name}_ADDED
+ "${${name}_ADDED}"
+ PARENT_SCOPE
+ )
+ set(CPM_LAST_PACKAGE_NAME
+ "${name}"
+ PARENT_SCOPE
+ )
+endmacro()
+
+# declares a package, so that any call to CPMAddPackage for the package name will use these
+# arguments instead. Previous declarations will not be overridden.
+macro(CPMDeclarePackage Name)
+ if(NOT DEFINED "CPM_DECLARATION_${Name}")
+ set("CPM_DECLARATION_${Name}" "${ARGN}")
+ endif()
+endmacro()
+
+function(cpm_add_to_package_lock Name)
+ if(NOT CPM_DONT_CREATE_PACKAGE_LOCK)
+ cpm_prettify_package_arguments(PRETTY_ARGN false ${ARGN})
+ file(APPEND ${CPM_PACKAGE_LOCK_FILE} "# ${Name}\nCPMDeclarePackage(${Name}\n${PRETTY_ARGN})\n")
+ endif()
+endfunction()
+
+function(cpm_add_comment_to_package_lock Name)
+ if(NOT CPM_DONT_CREATE_PACKAGE_LOCK)
+ cpm_prettify_package_arguments(PRETTY_ARGN true ${ARGN})
+ file(APPEND ${CPM_PACKAGE_LOCK_FILE}
+ "# ${Name} (unversioned)\n# CPMDeclarePackage(${Name}\n${PRETTY_ARGN}#)\n"
+ )
+ endif()
+endfunction()
+
+# includes the package lock file if it exists and creates a target `cpm-update-package-lock` to
+# update it
+macro(CPMUsePackageLock file)
+ if(NOT CPM_DONT_CREATE_PACKAGE_LOCK)
+ get_filename_component(CPM_ABSOLUTE_PACKAGE_LOCK_PATH ${file} ABSOLUTE)
+ if(EXISTS ${CPM_ABSOLUTE_PACKAGE_LOCK_PATH})
+ include(${CPM_ABSOLUTE_PACKAGE_LOCK_PATH})
+ endif()
+ if(NOT TARGET cpm-update-package-lock)
+ add_custom_target(
+ cpm-update-package-lock COMMAND ${CMAKE_COMMAND} -E copy ${CPM_PACKAGE_LOCK_FILE}
+ ${CPM_ABSOLUTE_PACKAGE_LOCK_PATH}
+ )
+ endif()
+ set(CPM_PACKAGE_LOCK_ENABLED true)
+ endif()
+endmacro()
+
+# registers a package that has been added to CPM
+function(CPMRegisterPackage PACKAGE VERSION)
+ list(APPEND CPM_PACKAGES ${PACKAGE})
+ set(CPM_PACKAGES
+ ${CPM_PACKAGES}
+ CACHE INTERNAL ""
+ )
+ set("CPM_PACKAGE_${PACKAGE}_VERSION"
+ ${VERSION}
+ CACHE INTERNAL ""
+ )
+endfunction()
+
+# retrieve the current version of the package to ${OUTPUT}
+function(CPMGetPackageVersion PACKAGE OUTPUT)
+ set(${OUTPUT}
+ "${CPM_PACKAGE_${PACKAGE}_VERSION}"
+ PARENT_SCOPE
+ )
+endfunction()
+
+# declares a package in FetchContent_Declare
+function(cpm_declare_fetch PACKAGE VERSION INFO)
+ if(${CPM_DRY_RUN})
+ cpm_message(STATUS "${CPM_INDENT} Package not declared (dry run)")
+ return()
+ endif()
+
+ FetchContent_Declare(${PACKAGE} ${ARGN})
+endfunction()
+
+# returns properties for a package previously defined by cpm_declare_fetch
+function(cpm_get_fetch_properties PACKAGE)
+ if(${CPM_DRY_RUN})
+ return()
+ endif()
+
+ set(${PACKAGE}_SOURCE_DIR
+ "${CPM_PACKAGE_${PACKAGE}_SOURCE_DIR}"
+ PARENT_SCOPE
+ )
+ set(${PACKAGE}_BINARY_DIR
+ "${CPM_PACKAGE_${PACKAGE}_BINARY_DIR}"
+ PARENT_SCOPE
+ )
+endfunction()
+
+function(cpm_store_fetch_properties PACKAGE source_dir binary_dir)
+ if(${CPM_DRY_RUN})
+ return()
+ endif()
+
+ set(CPM_PACKAGE_${PACKAGE}_SOURCE_DIR
+ "${source_dir}"
+ CACHE INTERNAL ""
+ )
+ set(CPM_PACKAGE_${PACKAGE}_BINARY_DIR
+ "${binary_dir}"
+ CACHE INTERNAL ""
+ )
+endfunction()
+
+# adds a package as a subdirectory if viable, according to provided options
+function(
+ cpm_add_subdirectory
+ PACKAGE
+ DOWNLOAD_ONLY
+ SOURCE_DIR
+ BINARY_DIR
+ EXCLUDE
+ SYSTEM
+ OPTIONS
+)
+
+ if(NOT DOWNLOAD_ONLY AND EXISTS ${SOURCE_DIR}/CMakeLists.txt)
+ set(addSubdirectoryExtraArgs "")
+ if(EXCLUDE)
+ list(APPEND addSubdirectoryExtraArgs EXCLUDE_FROM_ALL)
+ endif()
+ if("${SYSTEM}" AND "${CMAKE_VERSION}" VERSION_GREATER_EQUAL "3.25")
+ # https://cmake.org/cmake/help/latest/prop_dir/SYSTEM.html#prop_dir:SYSTEM
+ list(APPEND addSubdirectoryExtraArgs SYSTEM)
+ endif()
+ if(OPTIONS)
+ foreach(OPTION ${OPTIONS})
+ cpm_parse_option("${OPTION}")
+ set(${OPTION_KEY} "${OPTION_VALUE}")
+ endforeach()
+ endif()
+ set(CPM_OLD_INDENT "${CPM_INDENT}")
+ set(CPM_INDENT "${CPM_INDENT} ${PACKAGE}:")
+ add_subdirectory(${SOURCE_DIR} ${BINARY_DIR} ${addSubdirectoryExtraArgs})
+ set(CPM_INDENT "${CPM_OLD_INDENT}")
+ endif()
+endfunction()
+
+# downloads a previously declared package via FetchContent and exports the variables
+# `${PACKAGE}_SOURCE_DIR` and `${PACKAGE}_BINARY_DIR` to the parent scope
+function(cpm_fetch_package PACKAGE populated)
+ set(${populated}
+ FALSE
+ PARENT_SCOPE
+ )
+ if(${CPM_DRY_RUN})
+ cpm_message(STATUS "${CPM_INDENT} Package ${PACKAGE} not fetched (dry run)")
+ return()
+ endif()
+
+ FetchContent_GetProperties(${PACKAGE})
+
+ string(TOLOWER "${PACKAGE}" lower_case_name)
+
+ if(NOT ${lower_case_name}_POPULATED)
+ FetchContent_Populate(${PACKAGE})
+ set(${populated}
+ TRUE
+ PARENT_SCOPE
+ )
+ endif()
+
+ cpm_store_fetch_properties(
+ ${CPM_ARGS_NAME} ${${lower_case_name}_SOURCE_DIR} ${${lower_case_name}_BINARY_DIR}
+ )
+
+ set(${PACKAGE}_SOURCE_DIR
+ ${${lower_case_name}_SOURCE_DIR}
+ PARENT_SCOPE
+ )
+ set(${PACKAGE}_BINARY_DIR
+ ${${lower_case_name}_BINARY_DIR}
+ PARENT_SCOPE
+ )
+endfunction()
+
+# splits a package option
+function(cpm_parse_option OPTION)
+ string(REGEX MATCH "^[^ ]+" OPTION_KEY "${OPTION}")
+ string(LENGTH "${OPTION}" OPTION_LENGTH)
+ string(LENGTH "${OPTION_KEY}" OPTION_KEY_LENGTH)
+ if(OPTION_KEY_LENGTH STREQUAL OPTION_LENGTH)
+ # no value for key provided, assume user wants to set option to "ON"
+ set(OPTION_VALUE "ON")
+ else()
+ math(EXPR OPTION_KEY_LENGTH "${OPTION_KEY_LENGTH}+1")
+ string(SUBSTRING "${OPTION}" "${OPTION_KEY_LENGTH}" "-1" OPTION_VALUE)
+ endif()
+ set(OPTION_KEY
+ "${OPTION_KEY}"
+ PARENT_SCOPE
+ )
+ set(OPTION_VALUE
+ "${OPTION_VALUE}"
+ PARENT_SCOPE
+ )
+endfunction()
+
+# guesses the package version from a git tag
+function(cpm_get_version_from_git_tag GIT_TAG RESULT)
+ string(LENGTH ${GIT_TAG} length)
+ if(length EQUAL 40)
+ # GIT_TAG is probably a git hash
+ set(${RESULT}
+ 0
+ PARENT_SCOPE
+ )
+ else()
+ string(REGEX MATCH "v?([0123456789.]*).*" _ ${GIT_TAG})
+ set(${RESULT}
+ ${CMAKE_MATCH_1}
+ PARENT_SCOPE
+ )
+ endif()
+endfunction()
+
+# guesses if the git tag is a commit hash or an actual tag or a branch name.
+function(cpm_is_git_tag_commit_hash GIT_TAG RESULT)
+ string(LENGTH "${GIT_TAG}" length)
+ # full hash has 40 characters, and short hash has at least 7 characters.
+ if(length LESS 7 OR length GREATER 40)
+ set(${RESULT}
+ 0
+ PARENT_SCOPE
+ )
+ else()
+ if(${GIT_TAG} MATCHES "^[a-fA-F0-9]+$")
+ set(${RESULT}
+ 1
+ PARENT_SCOPE
+ )
+ else()
+ set(${RESULT}
+ 0
+ PARENT_SCOPE
+ )
+ endif()
+ endif()
+endfunction()
+
+function(cpm_prettify_package_arguments OUT_VAR IS_IN_COMMENT)
+ set(oneValueArgs
+ NAME
+ FORCE
+ VERSION
+ GIT_TAG
+ DOWNLOAD_ONLY
+ GITHUB_REPOSITORY
+ GITLAB_REPOSITORY
+ BITBUCKET_REPOSITORY
+ GIT_REPOSITORY
+ SOURCE_DIR
+ FIND_PACKAGE_ARGUMENTS
+ NO_CACHE
+ SYSTEM
+ GIT_SHALLOW
+ EXCLUDE_FROM_ALL
+ SOURCE_SUBDIR
+ )
+ set(multiValueArgs URL OPTIONS DOWNLOAD_COMMAND)
+ cmake_parse_arguments(CPM_ARGS "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ foreach(oneArgName ${oneValueArgs})
+ if(DEFINED CPM_ARGS_${oneArgName})
+ if(${IS_IN_COMMENT})
+ string(APPEND PRETTY_OUT_VAR "#")
+ endif()
+ if(${oneArgName} STREQUAL "SOURCE_DIR")
+ string(REPLACE ${CMAKE_SOURCE_DIR} "\${CMAKE_SOURCE_DIR}" CPM_ARGS_${oneArgName}
+ ${CPM_ARGS_${oneArgName}}
+ )
+ endif()
+ string(APPEND PRETTY_OUT_VAR " ${oneArgName} ${CPM_ARGS_${oneArgName}}\n")
+ endif()
+ endforeach()
+ foreach(multiArgName ${multiValueArgs})
+ if(DEFINED CPM_ARGS_${multiArgName})
+ if(${IS_IN_COMMENT})
+ string(APPEND PRETTY_OUT_VAR "#")
+ endif()
+ string(APPEND PRETTY_OUT_VAR " ${multiArgName}\n")
+ foreach(singleOption ${CPM_ARGS_${multiArgName}})
+ if(${IS_IN_COMMENT})
+ string(APPEND PRETTY_OUT_VAR "#")
+ endif()
+ string(APPEND PRETTY_OUT_VAR " \"${singleOption}\"\n")
+ endforeach()
+ endif()
+ endforeach()
+
+ if(NOT "${CPM_ARGS_UNPARSED_ARGUMENTS}" STREQUAL "")
+ if(${IS_IN_COMMENT})
+ string(APPEND PRETTY_OUT_VAR "#")
+ endif()
+ string(APPEND PRETTY_OUT_VAR " ")
+ foreach(CPM_ARGS_UNPARSED_ARGUMENT ${CPM_ARGS_UNPARSED_ARGUMENTS})
+ string(APPEND PRETTY_OUT_VAR " ${CPM_ARGS_UNPARSED_ARGUMENT}")
+ endforeach()
+ string(APPEND PRETTY_OUT_VAR "\n")
+ endif()
+
+ set(${OUT_VAR}
+ ${PRETTY_OUT_VAR}
+ PARENT_SCOPE
+ )
+
+endfunction()
diff --git a/external/imgui b/external/imgui
new file mode 160000
index 0000000..126569a
--- /dev/null
+++ b/external/imgui
@@ -0,0 +1 @@
+Subproject commit 126569ad5b3a2c5329cc8ee914dd5b2075f4dd50
diff --git a/external/imgui.cmake b/external/imgui.cmake
new file mode 100644
index 0000000..e5b0049
--- /dev/null
+++ b/external/imgui.cmake
@@ -0,0 +1,17 @@
+set(IMGUI_SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/imgui)
+
+add_library(imgui STATIC)
+
+target_sources(imgui PRIVATE
+ ${IMGUI_SOURCE_DIR}/imgui.cpp
+ ${IMGUI_SOURCE_DIR}/imgui_demo.cpp
+ ${IMGUI_SOURCE_DIR}/imgui_draw.cpp
+ ${IMGUI_SOURCE_DIR}/imgui_widgets.cpp
+ ${IMGUI_SOURCE_DIR}/imgui_tables.cpp
+ ${IMGUI_SOURCE_DIR}/backends/imgui_impl_sdl3.cpp
+ ${IMGUI_SOURCE_DIR}/backends/imgui_impl_sdlrenderer3.cpp
+)
+
+target_include_directories(imgui PUBLIC ${IMGUI_SOURCE_DIR} PRIVATE ${IMGUI_SOURCE_DIR}/backends)
+
+target_link_libraries(imgui PUBLIC SDL3::SDL3)
\ No newline at end of file
diff --git a/src/common/error.h b/src/common/error.h
new file mode 100644
index 0000000..e79c9a9
--- /dev/null
+++ b/src/common/error.h
@@ -0,0 +1,27 @@
+/* SPDX-License-Identifier: MIT
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+#include
+#include
+
+/**
+ * @brief A runtime error with a formatted message.
+ */
+struct Exception : std::runtime_error {
+ template
+ constexpr explicit Exception(fmt::format_string str, Args&&... args)
+ : std::runtime_error{fmt::format(str, std::forward(args)...)} {}
+};
+
+/**
+ * @brief Checks a condition and terminates with an error message, if it is true. Designed as an alternative to exceptions in noexcept functions.
+ */
+template
+constexpr void TerminateIf(bool condition, fmt::format_string str, Args&&... args) {
+ if (condition) {
+ fmt::print(stderr, "Terminating: {}\n", fmt::format(str, std::forward(args)...));
+ std::terminate();
+ }
+}
\ No newline at end of file
diff --git a/src/common/scope.h b/src/common/scope.h
new file mode 100644
index 0000000..90d72b6
--- /dev/null
+++ b/src/common/scope.h
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: MIT
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+template
+struct ScopeExit {
+ T lambda;
+ ScopeExit(T lambda)
+ : lambda(lambda) {}
+
+ ~ScopeExit() {
+ lambda();
+ }
+};
+
+#define SCOPE_EXIT(code) ScopeExit _scopeExit ## __LINE__{[&] { code; }}
\ No newline at end of file
diff --git a/src/common/static_vector.h b/src/common/static_vector.h
new file mode 100644
index 0000000..fac07b7
--- /dev/null
+++ b/src/common/static_vector.h
@@ -0,0 +1,70 @@
+/* SPDX-License-Identifier: MIT
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+#include
+#include
+
+/**
+ * @brief A minimal implementation of boost's static_vector.
+ */
+template
+class StaticVector {
+ private:
+ std::array buffer{};
+
+ public:
+ size_t size{};
+
+ constexpr StaticVector() = default;
+
+ template
+ constexpr StaticVector(BeginIt begin, EndIt end)
+ : size{static_cast(end - begin)} {
+ if (size > MaxSize)
+ throw std::out_of_range("StaticVector size exceeds MaxSize");
+ std::copy(begin, end, buffer.begin());
+ }
+
+ constexpr bool operator==(const StaticVector& other) const {
+ if (size != other.size)
+ return false;
+ return std::equal(buffer.begin(), buffer.begin() + size, other.buffer.begin());
+ }
+
+ constexpr bool operator!=(const StaticVector& other) const {
+ return !(*this == other);
+ }
+
+ constexpr T* data() {
+ return buffer.data();
+ }
+
+ constexpr void resize(size_t newSize) {
+ if (newSize > MaxSize)
+ throw std::out_of_range("StaticVector size exceeds MaxSize");
+ size = newSize;
+ }
+
+ constexpr T* data_resize(size_t newSize) {
+ resize(newSize);
+ return data();
+ }
+
+ constexpr T* begin() {
+ return buffer.data();
+ }
+
+ constexpr T* end() {
+ return buffer.data() + size;
+ }
+
+ constexpr T& operator[](size_t index) {
+ return buffer[index];
+ }
+
+ constexpr T& at(size_t index) {
+ return buffer.at(index);
+ }
+};
diff --git a/src/common/thread_name.h b/src/common/thread_name.h
new file mode 100644
index 0000000..337c24e
--- /dev/null
+++ b/src/common/thread_name.h
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: MIT
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+#include
+
+#ifdef _WIN32
+ #include
+ #include
+#elif defined(__linux__)
+ #include
+#endif
+
+/**
+ * @brief Set the name of the calling thread.
+ * @note This may silently fail in some cases, e.g. the name is too long.
+ */
+inline void SetThreadName(const std::string& name) {
+#ifdef _WIN32
+
+ std::wstring wName{name.begin(), name.end()};
+ SetThreadDescription(GetCurrentThread(), wName.c_str());
+
+#elif defined(__linux__)
+ pthread_setname_np(pthread_self(), name.c_str());
+#endif
+}
\ No newline at end of file
diff --git a/src/common/types.h b/src/common/types.h
new file mode 100644
index 0000000..89a767a
--- /dev/null
+++ b/src/common/types.h
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: MIT
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+#include
+#include
+
+using u64 = uint64_t; //!< Unsigned 64-bit integer
+using u32 = uint32_t; //!< Unsigned 32-bit integer
+using u16 = uint16_t; //!< Unsigned 16-bit integer
+using u8 = uint8_t; //!< Unsigned 8-bit integer
+using i64 = int64_t; //!< Signed 64-bit integer
+using i32 = int32_t; //!< Signed 32-bit integer
+using i16 = int16_t; //!< Signed 16-bit integer
+using i8 = int8_t; //!< Signed 8-bit integer
\ No newline at end of file
diff --git a/src/crsf/crc.h b/src/crsf/crc.h
new file mode 100644
index 0000000..2772fb2
--- /dev/null
+++ b/src/crsf/crc.h
@@ -0,0 +1,42 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Copyright © ExpressLRS Developers
+ * Copyright © Mark Collins
+ * Heavily derivative of ExpressLRS, see https://github.com/ExpressLRS/ExpressLRS/tree/f3cc5e66796c93b5eaa90a3d1d519f0d0fa0e4ea/src/lib/CRC
+ */
+
+#pragma once
+
+#include
+#include
+
+namespace crsf {
+/*
+ * @brief A CRC8 implementation using a lookup table computed at compile time.
+ */
+class PolynomialCrc {
+ private:
+ std::array table; //!< A lookup table containing the mapping for every byte value.
+
+ public:
+ consteval PolynomialCrc(u8 polynomial) {
+ constexpr u8 BitsInByte{8};
+
+ for (size_t i{}; i < table.size(); i++) {
+ size_t crc{i};
+ for (size_t j{}; j < BitsInByte; j++)
+ crc = (crc << 1) ^ ((crc & (1 << (BitsInByte - 1))) ? polynomial : 0);
+ table[i] = crc & UINT8_MAX;
+ }
+ }
+
+ constexpr u8 Calculate(u8 data) const {
+ return table[data];
+ }
+
+ constexpr u8 Calculate(const u8* data, uint16_t length, u8 crc = 0) const {
+ while (length--)
+ crc = table[crc ^ *data++];
+ return crc;
+ }
+};
+}
\ No newline at end of file
diff --git a/src/crsf/crsf.cpp b/src/crsf/crsf.cpp
new file mode 100644
index 0000000..c704a63
--- /dev/null
+++ b/src/crsf/crsf.cpp
@@ -0,0 +1,164 @@
+/* SPDX-License-Identifier: MPL-2.0
+ * Copyright © Mark Collins
+ */
+#include "protocol.h"
+#include
+#include
+
+#include "crsf.h"
+
+namespace crsf {
+bool Interface::IsActive() {
+ return serial.IsOpen();
+}
+
+void Interface::ResetDevice() {
+ if (!serial.IsOpen())
+ return;
+
+ serial.SetDTR(false);
+ serial.SetRTS(false);
+ serial.WriteByte(0);
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+ serial.SetDTR(true);
+ serial.SetRTS(true);
+ serial.WriteByte(0);
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+}
+
+void Interface::SendFrame(const FrameV& frame) {
+ auto data{[&]() -> FrameData {
+ return std::visit([&](auto&& frame) {
+ return frame.GetData();
+ },
+ frame);
+ }()};
+
+ // Note: Any frames need to be sent twice to ensure they are received.
+ serial.Write(data);
+ serial.Write(data);
+}
+
+std::optional Interface::ReceiveFrame(std::chrono::time_point timeout) {
+ FrameData frame{};
+ bool readAddress{false}; //!< Whether the address has been read while looking for the sync byte.
+
+ while (true) {
+ auto optionalByte{serial.ReadByte(timeout)};
+ if (!optionalByte)
+ return std::nullopt;
+
+ u8 byte{*optionalByte};
+ if (byte == SyncByte) {
+ break;
+ } else if (static_cast(byte) == Address::CrsfTransmitter
+ || static_cast(byte) == Address::RadioTransmitter) {
+ readAddress = true;
+ frame[0] = byte;
+ break;
+ } else {
+ if (byte >= 0x20 && byte <= 0x7E)
+ fmt::print("Dropping: '{}'\n", static_cast(byte));
+ else
+ fmt::print("Dropping: 0x{:02X}\n", static_cast(byte));
+ }
+ }
+
+ Header* header{reinterpret_cast(frame.data_resize(sizeof(Header)))};
+ serial.Read(std::span(frame.data() + readAddress, sizeof(Header) - readAddress));
+
+ if (header->frameSize + FrameSizeNotCountedBytes > FrameSizeMax)
+ throw Exception("Frame size too large: 0x{:X}", header->frameSize);
+ else if (header->frameSize < FrameTypeSize + FrameCrcSize)
+ throw Exception("Frame size too small: 0x{:X}", header->frameSize);
+
+ frame.resize(header->frameSize + FrameSizeNotCountedBytes);
+ serial.Read(std::span(frame.data() + sizeof(Header), header->frameSize - FrameTypeSize));
+
+ u8 crc{CrsfCrc.Calculate(frame.data() + FrameSizeNotCountedBytes, header->frameSize - FrameCrcSize)};
+ u8 frameCrc{frame[FrameSizeNotCountedBytes + header->frameSize - FrameCrcSize]};
+ if (crc != frameCrc)
+ throw Exception("CRC mismatch: expected 0x{:02X}, got 0x{:02X}", crc, frameCrc);
+
+ if (frame == oldFrame)
+ return ReceiveFrame(timeout);
+ else
+ oldFrame = frame;
+
+ return GetFrame(std::span(frame.data(), header->frameSize + FrameSizeNotCountedBytes), header->type);
+}
+
+Interface::Interface(std::string port, size_t baud)
+ : serial(port, baud) {}
+
+Device::Device(Address address, const std::string& name, DeviceMetadata metadata)
+ : address{address}
+ , name{name}
+ , metadata{metadata} {
+ for (u8 index{1}; index <= metadata.fieldCount; index++)
+ parameters.emplace_back(Parameter{index});
+}
+
+void Device::Update(const std::string& pName, DeviceMetadata pMetadata) {
+ if (name != pName || metadata != pMetadata) {
+ name = pName;
+ metadata = pMetadata;
+
+ parameters.clear();
+ for (u8 index{1}; index <= metadata.fieldCount; index++)
+ parameters.emplace_back(Parameter{index});
+
+ parameterWrites.clear();
+ syncData.reset();
+ }
+}
+
+Parameter* Device::FindParameter(u8 fieldIndex) {
+ auto it{std::find_if(parameters.begin(), parameters.end(), [&](const Parameter& parameter) { return parameter.fieldIndex == fieldIndex; })};
+ if (it == parameters.end())
+ return nullptr;
+ return &*it;
+}
+
+void Device::WriteParameter(u8 fieldIndex, ParameterWriteFrame::WriteValue value) {
+ Parameter* parameter{FindParameter(fieldIndex)};
+ if (!parameter || !parameter->complete)
+ return;
+
+ parameterWrites.emplace_back(ParameterWriteFrame{fieldIndex, value, address});
+
+ if (parameter->type == ParameterType::Command) {
+ parameter->activeCommand = true;
+ parameter->Reset();
+ return;
+ }
+
+ // We need to reset siblings along with the parent, when a parameter is written to since their values might be interdependent.
+ // Any children, or siblings that are subfolders or commands will not be reset since they are not expected to have interdependent values.
+ u8 parentIndex{parameter->parentIndex};
+ for (Parameter& parameter : parameters)
+ if (parameter.fieldIndex == fieldIndex || (parameter.parentIndex == parentIndex && parameter.type != ParameterType::Folder && parameter.type != ParameterType::Command))
+ parameter.Reset();
+}
+
+std::optional Device::TryGetTxFrame() {
+ if (!parameterWrites.empty()) {
+ FrameV frame{parameterWrites.front()};
+ parameterWrites.pop_front();
+ return frame;
+ }
+
+ for (Parameter& parameter : parameters) {
+ constexpr auto ParameterResendTimeout{std::chrono::milliseconds(100)};
+ if (!parameter.complete) {
+ if (parameter.requestedChunk && (std::chrono::steady_clock::now() - parameter.requestTime) < ParameterResendTimeout)
+ continue;
+ parameter.requestedChunk = true;
+ parameter.requestTime = std::chrono::steady_clock::now();
+ return ParameterReadFrame{parameter.fieldIndex, parameter.chunkIndex, address};
+ }
+ }
+
+ return std::nullopt;
+}
+}
\ No newline at end of file
diff --git a/src/crsf/crsf.h b/src/crsf/crsf.h
new file mode 100644
index 0000000..6eb69dc
--- /dev/null
+++ b/src/crsf/crsf.h
@@ -0,0 +1,76 @@
+/* SPDX-License-Identifier: MPL-2.0
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+#include
+
+#include "frame.h"
+#include "parameter.h"
+#include "protocol.h"
+
+#include
+
+namespace crsf {
+class Interface {
+ private:
+ SerialPort serial;
+ FrameData oldFrame{}; //!< A copy of the previous frame, used to prevent duplicate frames from being processed.
+
+ public:
+ Interface(std::string port, size_t baud);
+
+ /**
+ * @return Whether the interface is active, i.e. the serial port is open. This should be checked after exceptions.
+ */
+ bool IsActive();
+
+ /**
+ * @brief Attempts to reset the device by asserting the DTR and RTS lines.
+ */
+ void ResetDevice();
+
+ /**
+ * @brief Sends a frame over the CRSF interface.
+ */
+ void SendFrame(const FrameV& frame);
+
+ /**
+ * @brief Receives a frame from the CRSF interface.
+ * @param timeout The time to wait for a frame before returning an empty optional.
+ * @return The received frame, or an empty optional if no frame was received.
+ */
+ std::optional ReceiveFrame(std::chrono::time_point timeout);
+};
+
+struct Device {
+ Address address;
+ std::string name;
+ DeviceMetadata metadata;
+ std::vector parameters;
+ std::list parameterWrites;
+ std::optional syncData;
+
+ Device(Address address, const std::string& name, DeviceMetadata metadata);
+
+ /**
+ * @brief Updates the device metadata, resetting all state if there are changes.
+ */
+ void Update(const std::string& name, DeviceMetadata metadata);
+
+ /**
+ * @brief Finds a parameter by its field index, returning nullptr if it does not exist.
+ */
+ Parameter* FindParameter(u8 fieldIndex);
+
+ /**
+ * @brief Writes a parameter value to the device, resetting dependent parameters.
+ */
+ void WriteParameter(u8 fieldIndex, ParameterWriteFrame::WriteValue value);
+
+ /**
+ * @brief Attempts to get a queued frame to transmit over the CRSF interface.
+ */
+ std::optional TryGetTxFrame();
+};
+} // namespace crsf
\ No newline at end of file
diff --git a/src/crsf/frame.h b/src/crsf/frame.h
new file mode 100644
index 0000000..f6562e9
--- /dev/null
+++ b/src/crsf/frame.h
@@ -0,0 +1,321 @@
+/* SPDX-License-Identifier: MPL-2.0
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+#include "protocol.h"
+
+namespace crsf {
+constexpr Address DefaultOriginAddress{Address::RadioTransmitter}; //!< Default origin address is the radio transmitter, since this is designed to emulate it.
+constexpr Address DefaultDeviceAddress{Address::CrsfTransmitter}; //!< Default device address is the CRSF TX, since the radio is going to be attached to it.
+
+using FrameData = StaticVector;
+
+/**
+ * @brief The base class for all CRSF frames.
+ * @note Any frame that needs to be recieved must have a constructor that takes a std::span as an argument.
+ * @note Any frame that needs to be sent must implement the WritePayload virtual method.
+ */
+struct Frame {
+ Address deviceAddress;
+ FrameType type;
+
+ constexpr Frame(FrameType type, Address deviceAddress = DefaultDeviceAddress)
+ : deviceAddress{deviceAddress}
+ , type{type} {}
+
+ constexpr Frame(std::span data)
+ : deviceAddress{data[0]}
+ , type{static_cast(data[2])} {}
+
+ FrameData GetData() const {
+ FrameData data{};
+ size_t payloadSize{WritePayload(std::span(data.data() + HeaderSize, PayloadSizeMax))},
+ frameSize{FrameTypeSize + payloadSize + FrameCrcSize};
+ data.size = FrameSizeNotCountedBytes + frameSize;
+
+ *reinterpret_cast(data.data()) = Header{
+ .deviceAddress = deviceAddress,
+ .frameSize = static_cast(frameSize),
+ .type = type,
+ };
+ data[data.size - 1] = CrsfCrc.Calculate(data.data() + FrameSizeNotCountedBytes, FrameTypeSize + payloadSize);
+
+ return data;
+ }
+
+ virtual size_t WritePayload(std::span payload) const {
+ throw Exception("WritePayload not implemented for frame type: 0x{:X}", static_cast(type));
+ }
+};
+
+struct BatterySensorFrame : public Frame {
+ static constexpr FrameType Type{FrameType::BatterySensor};
+
+ BatterySensorData battery;
+
+ constexpr BatterySensorFrame(BatterySensorData battery, Address deviceAddress = DefaultDeviceAddress)
+ : Frame(Type, deviceAddress)
+ , battery{battery} {}
+
+ inline BatterySensorFrame(std::span data)
+ : Frame(data)
+ , battery{*(reinterpret_cast(data.data() + HeaderSize))} {}
+
+ virtual size_t WritePayload(std::span payload) const override {
+ *reinterpret_cast(payload.data()) = battery;
+ return sizeof(BatterySensorData);
+ }
+};
+
+struct LinkStatisticsFrame : public Frame {
+ static constexpr FrameType Type{FrameType::LinkStatistics};
+
+ LinkStatisticsData statistics;
+
+ constexpr LinkStatisticsFrame(LinkStatisticsData statistics, Address deviceAddress = DefaultDeviceAddress)
+ : Frame(Type, deviceAddress)
+ , statistics{statistics} {}
+
+ inline LinkStatisticsFrame(std::span data)
+ : Frame(data)
+ , statistics{*(reinterpret_cast(data.data() + HeaderSize))} {}
+
+ virtual size_t WritePayload(std::span payload) const override {
+ *reinterpret_cast(payload.data()) = statistics;
+ return sizeof(LinkStatisticsData);
+ }
+};
+
+struct RcChannelsFrame : public Frame {
+ static constexpr FrameType Type{FrameType::RcChannelsPacked};
+
+ RcChannelsData channels;
+
+ constexpr RcChannelsFrame(RcChannelsData channels, Address deviceAddress = DefaultDeviceAddress)
+ : Frame(Type, deviceAddress)
+ , channels{channels} {}
+
+ RcChannelsFrame(std::span data)
+ : Frame(data)
+ , channels{*(reinterpret_cast(data.data() + HeaderSize))} {}
+
+ virtual size_t WritePayload(std::span payload) const override {
+ *reinterpret_cast(payload.data()) = channels;
+ return sizeof(RcChannelsData);
+ }
+};
+
+struct ExtFrame : public Frame {
+ Address destinationAddress;
+ Address originAddress;
+
+ constexpr ExtFrame(FrameType type, Address destinationAddress, Address originAddress = DefaultOriginAddress, Address deviceAddress = DefaultDeviceAddress)
+ : Frame(type, deviceAddress)
+ , destinationAddress{destinationAddress}
+ , originAddress{originAddress} {}
+
+ ExtFrame(std::span data)
+ : Frame(data)
+ , destinationAddress{data[3]}
+ , originAddress{data[4]} {}
+
+ virtual size_t WritePayload(std::span payload) const override {
+ auto address{reinterpret_cast(payload.data())};
+ *address = destinationAddress;
+ *(address + 1) = originAddress;
+ return sizeof(Address) * 2;
+ }
+};
+
+struct PingFrame : public ExtFrame {
+ static constexpr FrameType Type{FrameType::DevicePing};
+
+ constexpr PingFrame(Address destinationAddress, Address originAddress = DefaultOriginAddress, Address deviceAddress = DefaultDeviceAddress)
+ : ExtFrame(Type, destinationAddress, originAddress, deviceAddress) {}
+
+ PingFrame(std::span data)
+ : ExtFrame(data) {}
+};
+
+#pragma pack(push, 1)
+struct DeviceMetadata {
+ u32 serialNo;
+ u32 hardwareVersion;
+ u32 softwareVersion;
+ u8 fieldCount;
+ u8 parameterVersion;
+
+ constexpr bool operator==(const DeviceMetadata& other) const {
+ return serialNo == other.serialNo && hardwareVersion == other.hardwareVersion && softwareVersion == other.softwareVersion && fieldCount == other.fieldCount && parameterVersion == other.parameterVersion;
+ }
+};
+static_assert(sizeof(DeviceMetadata) == 14);
+#pragma pack(pop)
+
+struct DeviceInfoFrame : public ExtFrame {
+ static constexpr FrameType Type{FrameType::DeviceInfo};
+
+ std::string deviceName;
+ DeviceMetadata deviceMetadata;
+
+ constexpr DeviceInfoFrame(std::string deviceName, u32 serialNo, u32 hardwareVersion, u32 softwareVersion, u8 fieldCount, u8 parameterVersion, Address destinationAddress, Address originAddress = DefaultOriginAddress, Address deviceAddress = DefaultDeviceAddress)
+ : ExtFrame(Type, destinationAddress, originAddress, deviceAddress)
+ , deviceName{deviceName}
+ , deviceMetadata{serialNo, hardwareVersion, softwareVersion, fieldCount, parameterVersion} {}
+
+ DeviceInfoFrame(std::span data)
+ : ExtFrame(data)
+ , deviceName{reinterpret_cast(data.data() + ExtSize)}
+ , deviceMetadata{*(reinterpret_cast(data.data() + ExtSize + deviceName.size() + 1))} {}
+
+ virtual size_t WritePayload(std::span payload) const override {
+ size_t offset{ExtFrame::WritePayload(payload)};
+
+ std::copy(deviceName.begin(), deviceName.end(), payload.begin() + offset);
+ payload[deviceName.size()] = '\0';
+ offset += deviceName.size() + 1;
+
+ std::memcpy(payload.data() + offset, &deviceMetadata, sizeof(DeviceMetadata));
+ offset += sizeof(DeviceMetadata);
+
+ return offset;
+ }
+};
+
+struct ParameterSettingsEntryFrame : public ExtFrame {
+ static constexpr FrameType Type{FrameType::ParameterSettingsEntry};
+
+ static constexpr size_t FieldDataSizeMax{PayloadSizeMax - (HeaderSize + ExtSize + 2)};
+
+ u8 fieldIndex;
+ u8 chunksRemaining;
+ StaticVector data;
+
+ ParameterSettingsEntryFrame(std::span data)
+ : ExtFrame(data)
+ , fieldIndex{data[ExtSize]}
+ , chunksRemaining{data[ExtSize + 1]}
+ , data{data.begin() + ExtSize + 2, data.end() - FrameCrcSize} {}
+};
+
+struct ParameterReadFrame : public ExtFrame {
+ static constexpr FrameType Type{FrameType::ParameterRead};
+
+ u8 fieldIndex;
+ u8 chunkIndex;
+
+ constexpr ParameterReadFrame(u8 fieldIndex, u8 chunkIndex, Address destinationAddress, Address originAddress = DefaultOriginAddress, Address deviceAddress = DefaultDeviceAddress)
+ : ExtFrame(Type, destinationAddress, originAddress, deviceAddress)
+ , fieldIndex{fieldIndex}
+ , chunkIndex{chunkIndex} {}
+
+ ParameterReadFrame(std::span data)
+ : ExtFrame(data)
+ , fieldIndex{data[ExtSize]}
+ , chunkIndex{data[ExtSize + 1]} {}
+
+ virtual size_t WritePayload(std::span payload) const override {
+ size_t offset{ExtFrame::WritePayload(payload)};
+
+ payload[offset] = fieldIndex;
+ payload[offset + 1] = chunkIndex;
+
+ return offset + 2;
+ }
+};
+
+struct ParameterWriteFrame : public ExtFrame {
+ static constexpr FrameType Type{FrameType::ParameterWrite};
+ using WriteValue = u8;
+
+ u8 fieldIndex;
+ u8 value;
+
+ constexpr ParameterWriteFrame(u8 fieldIndex, u8 value, Address destinationAddress, Address originAddress = DefaultOriginAddress, Address deviceAddress = DefaultDeviceAddress)
+ : ExtFrame(Type, destinationAddress, originAddress, deviceAddress)
+ , fieldIndex{fieldIndex}
+ , value{value} {}
+
+ ParameterWriteFrame(std::span data)
+ : ExtFrame(data)
+ , fieldIndex{data[ExtSize]}
+ , value{data[ExtSize + 1]} {}
+
+ virtual size_t WritePayload(std::span payload) const override {
+ size_t offset{ExtFrame::WritePayload(payload)};
+
+ payload[offset] = fieldIndex;
+ payload[offset + 1] = value;
+
+ return offset + 2;
+ }
+};
+
+struct OpenTxSyncData {
+ i32 packetRate;
+ i32 packetOffset;
+};
+
+struct RadioIdFrame : public ExtFrame {
+ static constexpr FrameType Type{FrameType::RadioId};
+
+ OpenTxSyncData sync;
+
+ constexpr RadioIdFrame(OpenTxSyncData sync, Address destinationAddress, Address originAddress = DefaultOriginAddress, Address deviceAddress = DefaultDeviceAddress)
+ : ExtFrame(Type, destinationAddress, originAddress, deviceAddress)
+ , sync{sync} {}
+
+ RadioIdFrame(std::span data)
+ : ExtFrame(data) {
+ FrameType extendedType{data[ExtSize]};
+ if (extendedType != FrameType::OpenTxSync)
+ throw Exception("Unknown extended type: 0x{:X}", static_cast(extendedType));
+
+ auto syncData{reinterpret_cast(data.data() + ExtSize + 1)};
+ sync = {
+ .packetRate = std::byteswap(syncData->packetRate),
+ .packetOffset = std::byteswap(syncData->packetOffset),
+ };
+ }
+
+ virtual size_t WritePayload(std::span payload) const override {
+ size_t offset{ExtFrame::WritePayload(payload)};
+
+ payload[offset] = static_cast(FrameType::OpenTxSync);
+ *reinterpret_cast(payload.data() + offset + 1) = {
+ .packetRate = std::byteswap(sync.packetRate),
+ .packetOffset = std::byteswap(sync.packetOffset),
+ };
+
+ return offset + 1 + sizeof(OpenTxSyncData);
+ }
+};
+
+using FrameV = std::variant;
+
+constexpr FrameV GetFrame(std::span data, FrameType type) {
+ return [&](std::index_sequence) -> FrameV {
+ std::optional result{};
+ auto TryGetFrame{[&](auto index) -> bool {
+ using T = std::variant_alternative_t;
+ if (T::Type == type) {
+ result = T(data);
+ return true;
+ }
+ return false;
+ }};
+ if (!(TryGetFrame(std::integral_constant{}) || ...))
+ throw Exception("Unknown frame type: 0x{:X}", static_cast(type));
+ return *result;
+ }(std::make_index_sequence>{});
+}
+} // namespace crsf
\ No newline at end of file
diff --git a/src/crsf/parameter.h b/src/crsf/parameter.h
new file mode 100644
index 0000000..c342141
--- /dev/null
+++ b/src/crsf/parameter.h
@@ -0,0 +1,238 @@
+/* SPDX-License-Identifier: MPL-2.0
+ * Copyright © Mark Collins
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+
+#include
+
+#include "protocol.h"
+
+namespace crsf {
+template
+struct IntegerParameter {
+ T value;
+ T min;
+ T max;
+ std::string units;
+
+ constexpr IntegerParameter(std::span data) {
+ auto ptr{data.data()};
+
+ value = *reinterpret_cast(ptr);
+ ptr += sizeof(T);
+ min = *reinterpret_cast(ptr);
+ ptr += sizeof(T);
+ max = *reinterpret_cast(ptr);
+ ptr += sizeof(T);
+
+ units = std::string(reinterpret_cast(ptr));
+ }
+};
+
+struct FloatParameter {
+ float value;
+ float min;
+ float max;
+ u8 precision;
+ u32 step;
+ std::string units;
+
+ FloatParameter(std::span data) {
+ auto ptr{data.data()};
+
+ value = *reinterpret_cast(ptr);
+ ptr += sizeof(float);
+ min = *reinterpret_cast(ptr);
+ ptr += sizeof(float);
+ max = *reinterpret_cast(ptr);
+ ptr += sizeof(float);
+
+ precision = *ptr++;
+ step = *reinterpret_cast(ptr);
+ ptr += sizeof(u32);
+
+ units = std::string(reinterpret_cast(ptr));
+ }
+};
+
+struct TextSelectionParameter {
+ u8 selectedIndex;
+ u8 minIndex;
+ u8 maxIndex;
+ u8 defaultIndex;
+ std::vector options;
+ std::string units;
+
+ TextSelectionParameter(std::span data) {
+ auto ptr{data.data()};
+ std::string_view optionsString{reinterpret_cast(ptr)};
+ for (size_t start{}, end{}; end != std::string_view::npos; start = end + 1) {
+ end = optionsString.find(';', start);
+ options.emplace_back(optionsString.substr(start, end - start));
+ }
+ ptr += optionsString.size() + 1;
+
+ constexpr char LuaSymbolArrowUp{'\xc0'};
+ constexpr char LuaSymbolArrowDown{'\xc1'};
+
+ for (std::string& option : options) {
+ for (size_t i{}; i < option.size(); i++) {
+ if (option[i] == LuaSymbolArrowUp) {
+ option.replace(i, 1, "↑");
+ i++;
+ } else if (option[i] == LuaSymbolArrowDown) {
+ option.replace(i, 1, "↓");
+ i++;
+ }
+ }
+ }
+
+ selectedIndex = *ptr++;
+ minIndex = *ptr++;
+ maxIndex = *ptr++;
+ defaultIndex = *ptr++;
+
+ units = std::string(reinterpret_cast(ptr));
+ }
+};
+
+struct FolderParameter {
+ std::string displayName;
+
+ constexpr FolderParameter(std::span data) {
+ if (!data.empty())
+ displayName = std::string(reinterpret_cast(data.data()));
+ }
+};
+
+struct InfoParameter {
+ std::string display;
+
+ constexpr InfoParameter(std::span data) {
+ display = std::string(reinterpret_cast(data.data()));
+ }
+};
+
+struct CommandParameter {
+ CommandStep step;
+ std::string status;
+
+ constexpr CommandParameter(std::span data) {
+ step = static_cast(data[0]);
+ status = std::string(reinterpret_cast(data.data() + 1));
+ }
+};
+
+using ParameterValue = std::variant, IntegerParameter, IntegerParameter, IntegerParameter, IntegerParameter, IntegerParameter, FloatParameter, TextSelectionParameter, FolderParameter, InfoParameter, CommandParameter>;
+
+constexpr ParameterValue GetParameterValue(std::span data, ParameterType type) {
+ switch (type) {
+ case ParameterType::Uint8:
+ return IntegerParameter(data);
+ case ParameterType::Int8:
+ return IntegerParameter(data);
+ case ParameterType::Uint16:
+ return IntegerParameter(data);
+ case ParameterType::Int16:
+ return IntegerParameter(data);
+ case ParameterType::Uint32:
+ return IntegerParameter(data);
+ case ParameterType::Int32:
+ return IntegerParameter(data);
+ case ParameterType::Float:
+ return FloatParameter(data);
+ case ParameterType::TextSelection:
+ return TextSelectionParameter(data);
+ case ParameterType::Folder:
+ return FolderParameter(data);
+ case ParameterType::Info:
+ return InfoParameter(data);
+ case ParameterType::Command:
+ return CommandParameter(data);
+ default:
+ throw Exception("Unknown parameter type: {}", static_cast(type));
+ }
+}
+
+/**
+ * @brief An abstraction over a CRSF parameter, processing every chunk of data until the parameter is complete.
+ */
+struct Parameter {
+ u8 fieldIndex{};
+ u8 parentIndex{};
+ u8 chunkIndex{};
+ i16 lastChunksRemaining{-1};
+ bool complete{};
+ bool requestedChunk{};
+ bool activeCommand{};
+ std::chrono::time_point requestTime{};
+ std::chrono::time_point updateTime{};
+
+ std::string name{};
+ ParameterType type{};
+ std::vector rawData;
+ ParameterValue value{};
+
+#pragma pack(push, 1)
+ struct FirstChunkData {
+ u8 parentIndex;
+ ParameterType type;
+ };
+ static_assert(sizeof(FirstChunkData) == 2);
+#pragma pack(pop)
+
+ constexpr Parameter(u8 fieldIndex)
+ : fieldIndex{fieldIndex} {}
+
+ constexpr void ProcessChunk(std::span chunk, u8 chunksRemaining) {
+ if (lastChunksRemaining > 0 && chunksRemaining != lastChunksRemaining - 1) {
+ fmt::print("Chunk order mismatch: expected {}, got {}\n", lastChunksRemaining - 1, chunksRemaining);
+ return;
+ }
+ lastChunksRemaining = chunksRemaining;
+
+ rawData.insert(rawData.end(), chunk.begin(), chunk.end());
+ chunkIndex++;
+ requestedChunk = false;
+
+ if (chunksRemaining == 0) {
+ auto ptr{rawData.data()};
+
+ FirstChunkData* firstChunkData{reinterpret_cast(ptr)};
+ parentIndex = firstChunkData->parentIndex;
+ type = firstChunkData->type;
+ ptr += sizeof(FirstChunkData);
+
+ name = std::string(reinterpret_cast(ptr));
+ ptr += name.size() + 1;
+ value = GetParameterValue(std::span(ptr, rawData.size() - (ptr - rawData.data())), type);
+
+ complete = true;
+ rawData.clear();
+ updateTime = std::chrono::steady_clock::now();
+
+ if (activeCommand) {
+ CommandParameter& command{std::get(value)};
+ if (command.step == CommandStep::Idle)
+ activeCommand = false;
+ }
+ }
+ }
+
+ constexpr void Reset() {
+ chunkIndex = 0;
+ lastChunksRemaining = -1;
+ requestedChunk = false;
+ rawData.clear();
+ complete = false;
+ if (!activeCommand)
+ value = std::monostate{};
+ }
+};
+}
\ No newline at end of file
diff --git a/src/crsf/protocol.h b/src/crsf/protocol.h
new file mode 100644
index 0000000..6ab8124
--- /dev/null
+++ b/src/crsf/protocol.h
@@ -0,0 +1,469 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Copyright © ExpressLRS Developers
+ * Copyright © Mark Collins
+ * Heavily derivative of ExpressLRS, see https://github.com/ExpressLRS/ExpressLRS/tree/f3cc5e66796c93b5eaa90a3d1d519f0d0fa0e4ea/src/lib/CrsfProtocol
+ */
+
+#pragma once
+
+#include "crc.h"
+#include
+
+namespace crsf {
+constexpr u8 CrcPolynomial{0xd5};
+constexpr PolynomialCrc CrsfCrc{CrcPolynomial};
+
+constexpr u8 SyncByte{0xC8};
+
+constexpr size_t FrameSizeNotCountedBytes{2};
+constexpr size_t PayloadSizeMax{62};
+constexpr size_t FrameTypeSize{1}, FrameCrcSize{1};
+constexpr size_t FrameSizeMax{FrameSizeNotCountedBytes + PayloadSizeMax + FrameCrcSize};
+
+enum class FrameType : u8 {
+ Gps = 0x02,
+ Vario = 0x07,
+ BatterySensor = 0x08,
+ BaroAltitude = 0x09,
+ LinkStatistics = 0x14,
+ OpenTxSync = 0x10,
+ RadioId = 0x3A,
+ RcChannelsPacked = 0x16,
+ Attitude = 0x1E,
+ FlightMode = 0x21,
+ // Extended Header Frames, range: 0x28 to 0x96
+ DevicePing = 0x28,
+ DeviceInfo = 0x29,
+ ParameterSettingsEntry = 0x2B,
+ ParameterRead = 0x2C,
+ ParameterWrite = 0x2D,
+ ElrsStatus = 0x2E, // ELRS good/bad packet count and status flags
+ Command = 0x32,
+ // KISS frames
+ KissRequest = 0x78,
+ KissResponse = 0x79,
+ // MSP commands
+ MspRequest = 0x7A, // Response request using msp sequence as command
+ MspResponse = 0x7B, // Reply with 58 byte chunked binary
+ MspWrite = 0x7C, // Write with 8 byte chunked binary (OpenTX outbound telemetry buffer limit)
+ // Ardupilot frames
+ ArdupilotResp = 0x80,
+};
+
+enum class CommandType : u8 {
+ Rx = 0x10
+};
+
+enum class SubCommandType : u8 {
+ RxBind = 0x01,
+ ModelSelectId = 0x05
+};
+
+enum class Address : u8 {
+ Broadcast = 0x00,
+ Usb = 0x10,
+ TbsCorePnpPro = 0x80,
+ Reserved1 = 0x8A,
+ CurrentSensor = 0xC0,
+ Gps = 0xC2,
+ TbsBlackbox = 0xC4,
+ FlightController = 0xC8,
+ Reserved2 = 0xCA,
+ RaceTag = 0xCC,
+ RadioTransmitter = 0xEA,
+ CrsfReceiver = 0xEC,
+ CrsfTransmitter = 0xEE,
+ ElrsLua = 0xEF
+};
+
+#pragma pack(push, 1)
+struct Header {
+ Address deviceAddress;
+ u8 frameSize; //!< Size of the frame, for all bytes after the frameSize byte, including the CRC.
+ FrameType type;
+};
+
+constexpr size_t HeaderSize{sizeof(Header)};
+
+struct ExtHeader {
+ Address deviceAddr;
+ u8 frameSize;
+ FrameType type;
+ Address destinationAddress;
+ Address originAddress;
+};
+
+constexpr size_t ExtSize{sizeof(ExtHeader)};
+
+enum class ParameterType : u8 {
+ Uint8 = 0,
+ Int8 = 1,
+ Uint16 = 2,
+ Int16 = 3,
+ Uint32 = 4,
+ Int32 = 5,
+ Uint64 = 6,
+ Int64 = 7,
+ Float = 8,
+ TextSelection = 9,
+ String = 10,
+ Folder = 11,
+ Info = 12,
+ Command = 13,
+ Vtx = 15,
+ OutOfRange = 127,
+};
+
+constexpr u8 ParameterHidden{0x80};
+constexpr u8 ParameterElrsHidden{0x40};
+constexpr u8 ParameterTypeMask{static_cast(~(ParameterHidden | ParameterElrsHidden))};
+
+enum class CommandStep : u8 {
+ Idle = 0,
+ Click = 1,
+ Executing = 2,
+ AskConfirm = 3,
+ Confirmed = 4,
+ Cancel = 5,
+ Query = 6,
+};
+
+constexpr const char* CommandStepToString(CommandStep step) {
+ switch (step) {
+ case CommandStep::Idle:
+ return "Idle";
+ case CommandStep::Click:
+ return "Clicked";
+ case CommandStep::Executing:
+ return "Executing";
+ case CommandStep::AskConfirm:
+ return "Needs Confirmation";
+ case CommandStep::Confirmed:
+ return "Confirmed";
+ case CommandStep::Cancel:
+ return "Cancel";
+ case CommandStep::Query:
+ return "Query";
+ default:
+ return "Unknown";
+ }
+}
+
+struct RcChannelsData {
+ static constexpr size_t ChannelCount{16};
+ static constexpr size_t BitsPerChannel{11};
+ static constexpr size_t PackedSize{((BitsPerChannel * ChannelCount) + 7) / 8};
+ static constexpr u16 BitMask{(1 << BitsPerChannel) - 1};
+
+ std::array data;
+
+ constexpr bool operator==(const RcChannelsData& other) const {
+ return data == other.data;
+ }
+
+ constexpr bool operator!=(const RcChannelsData& other) const {
+ return data != other.data;
+ }
+
+ constexpr u16 get(u8 i) const {
+ size_t byteIndex{(i * BitsPerChannel) / 8};
+ size_t bitOffset{(i * BitsPerChannel) % 8};
+ u16 value{static_cast((data[byteIndex] >> bitOffset) | (data[byteIndex + 1] << (8 - bitOffset)))};
+ if (bitOffset > 5)
+ value |= (data[byteIndex + 2] << (16 - bitOffset));
+ return value & BitMask;
+ }
+
+ constexpr void set(u8 i, u16 val) {
+ size_t byteIndex{(i * BitsPerChannel) / 8};
+ size_t bitOffset{(i * BitsPerChannel) % 8};
+ data[byteIndex] = (data[byteIndex] & ~(BitMask << bitOffset)) | ((val << bitOffset) & 0xFF);
+ data[byteIndex + 1] = (data[byteIndex + 1] & ~(BitMask >> (8 - bitOffset))) | ((val >> (8 - bitOffset)) & 0xFF);
+ if (bitOffset > 5)
+ data[byteIndex + 2] = (data[byteIndex + 2] & (0xFF << (16 - bitOffset))) | ((val >> (16 - bitOffset)) & 0xFF);
+ }
+};
+
+struct DeviceInformationData {
+ u32 serialNo;
+ u32 hardwareVersion;
+ u32 softwareVersion;
+ u8 ParametersCount; //!< Number of parameters in the device, these can be queried using ParameterRead frames.
+ u8 ParametersVersion;
+ // A null-terminated string containing the device name follows.
+};
+
+namespace msp {
+ constexpr size_t RequestPayloadSize{8};
+ constexpr size_t ResponsePayloadSize{58};
+ constexpr size_t MaxPayloadSize{(RequestPayloadSize > ResponsePayloadSize ? RequestPayloadSize : ResponsePayloadSize)};
+
+ struct VtxConfigPacket {
+ u8 vtxType;
+ u8 band;
+ u8 channel;
+ u8 power;
+ u8 pitmode;
+ u16 freq;
+ u8 deviceIsReady;
+ u8 lowPowerDisarm;
+ u16 pitModeFreq;
+ u8 vtxTableAvailable;
+ u8 bands;
+ u8 channels;
+ u8 powerLevels;
+ };
+
+ struct VtxPowerLevelPacket {
+ u8 powerLevel;
+ u16 powerValue;
+ u8 powerLabelLength;
+ u8 label[3];
+ };
+
+ struct VtxBandPacket {
+ u8 band;
+ u8 bandNameLength;
+ u8 bandName[8];
+ u8 bandLetter;
+ u8 isFactoryBand;
+ u8 channels;
+ u16 channel[8];
+ };
+}
+
+struct BatterySensorData {
+ u16 voltage; // mv * 100, big endian.
+ u16 current; // ma * 100, big endian.
+ u32 capacityRemainingPacked; // First 24 bits capacity in mah, last 8 bits remaining capacity in %, little endian.
+
+ /*
+ * @return Battery voltage in volts.
+ */
+ constexpr float Voltage() const {
+ return std::byteswap(voltage) / 10.0f;
+ }
+
+ /*
+ * @return Current draw in amps.
+ */
+ constexpr float Current() const {
+ return std::byteswap(current) / 100.0f;
+ }
+
+ /*
+ * @return Battery capacity in mAh.
+ */
+ constexpr float Capacity() const {
+ return (capacityRemainingPacked & 0xFFFFFF) / 1000.0f;
+ }
+
+ /*
+ * @return Remaining battery capacity in %.
+ */
+ constexpr u8 RemainingCapacity() const {
+ return capacityRemainingPacked >> 24;
+ }
+};
+
+struct BaroVarioData {
+ u16 altitude; //!< Altitude in decimeters + 10000dm, or Altitude in meters if high bit is set, big endian.
+ i16 verticalSpeed; //!< Vertical speed in cm/s, big endian.
+
+ /*
+ * @return Altitude in meters.
+ */
+ constexpr float Altitude() const {
+ u16 alt{std::byteswap(altitude)};
+ if (alt & 0x8000)
+ return static_cast(alt & 0x7FFF);
+ return static_cast(alt - 10000) / 10.0f;
+ }
+
+ /*
+ * @return Vertical speed in m/s.
+ */
+ constexpr i16 VerticalSpeed() const {
+ return std::byteswap(verticalSpeed);
+ }
+};
+
+struct VarioData {
+ i16 verticalSpeed; //!< Vertical speed in cm/s, big endian.
+
+ /*
+ * @return Vertical speed in m/s.
+ */
+ constexpr float VerticalSpeed() const {
+ return std::byteswap(verticalSpeed) / 100.0f;
+ }
+};
+
+struct GpsData {
+ i32 latitude; //!< Degree / 10`000`000.
+ i32 longitude; //!< Degree / 10`000`000.
+ u16 groundSpeed; //!< km/h / 10.
+ u16 gpsHeading; //!< Degree / 100.
+ u16 altitude; //!< Meters, 1000m offset.
+ u8 satellitesInUse;
+
+ /*
+ * @return Latitude in degrees.
+ */
+ constexpr double Latitude() const {
+ return static_cast(latitude) / 10000000.0f;
+ }
+
+ /*
+ * @return Longitude in degrees.
+ */
+ constexpr double Longitude() const {
+ return static_cast(longitude) / 10000000.0f;
+ }
+
+ /*
+ * @return Ground speed in km/h.
+ */
+ constexpr float GroundSpeed() const {
+ return static_cast(groundSpeed) / 10.0f;
+ }
+
+ /*
+ * @return GPS heading in degrees.
+ */
+ constexpr float GpsHeading() const {
+ return static_cast(gpsHeading) / 100.0f;
+ }
+
+ /*
+ * @return Altitude in meters, relative to the ground.
+ */
+ constexpr float Altitude() const {
+ return static_cast(altitude) + 1000.0f;
+ }
+};
+
+struct AttitudeData {
+ i16 pitch; //!< Radians * 10000.
+ i16 roll; //!< Radians * 10000.
+ i16 yaw; //!< Radians * 10000.
+
+ /*
+ * @return Pitch in radians.
+ */
+ constexpr float Pitch() const {
+ return std::byteswap(pitch) / 10000.0f;
+ }
+
+ /*
+ * @return Roll in radians.
+ */
+ constexpr float Roll() const {
+ return std::byteswap(roll) / 10000.0f;
+ }
+
+ /*
+ * @return Yaw in radians.
+ */
+ constexpr float Yaw() const {
+ return std::byteswap(yaw) / 10000.0f;
+ }
+};
+
+struct FlightModeData {
+ std::array flightMode;
+};
+
+struct LinkStatisticsData {
+ static constexpr float MaxRssi{300.f}; //!< An arbitrary maximum RSSI value, this is inverted.
+ static constexpr float MaxSnrDb{100.f}; //!< Maximum SNR in dB, this value is centered around 0 going in positive and negative directions.
+
+ u8 uplinkRssi1Inverse;
+ u8 uplinkRssi2Inverse;
+ u8 uplinkLinkQuality; //!< The link quality in %.
+ i8 uplinkSnr;
+ u8 activeAntenna; //!< 0 = Antenna 1, 1 = Antenna 2.
+ u8 rfModeIndex;
+ u8 uplinkTxPowerIndex;
+ u8 downlinkRssiInverse;
+ u8 downlinkLinkQuality;
+ i8 downlinkSnr;
+
+ constexpr float UplinkRssi1() {
+ return static_cast(uplinkRssi1Inverse) * -1.0f;
+ }
+
+ constexpr float UplinkRssi1Norm() {
+ return (MaxRssi + UplinkRssi1()) / MaxRssi;
+ }
+
+ constexpr float UplinkRssi2() {
+ return static_cast(uplinkRssi2Inverse) * -1.0f;
+ }
+
+ constexpr float UplinkRssi2Norm() {
+ return (MaxRssi + UplinkRssi2()) / MaxRssi;
+ }
+
+ constexpr float UplinkLinkQualityNorm() {
+ return static_cast(uplinkLinkQuality) / 100.0f;
+ }
+
+ constexpr float UplinkSnrNorm() {
+ return (static_cast(uplinkSnr) + MaxSnrDb) / (MaxSnrDb * 2);
+ }
+
+ constexpr float DownlinkRssi() {
+ return static_cast(downlinkRssiInverse) * -1.0f;
+ }
+
+ constexpr float DownlinkRssiNorm() {
+ return (MaxRssi + DownlinkRssi()) / MaxRssi;
+ }
+
+ constexpr float DownlinkLinkQualityNorm() {
+ return static_cast(downlinkLinkQuality) / 100.0f;
+ }
+
+ constexpr float DownlinkSnrNorm() {
+ return (static_cast(downlinkSnr) + MaxSnrDb) / (MaxSnrDb * 2);
+ }
+
+ constexpr const char* RfMode() {
+ constexpr std::array ExpressLrsRfModes{
+ "LORA 4Hz",
+ "LORA 25Hz",
+ "LORA 50Hz",
+ "LORA 100Hz",
+ "LORA 100Hz 8CH",
+ "LORA 150Hz",
+ "LORA 200Hz",
+ "LORA 250Hz",
+ "LORA 333Hz 8CH",
+ "LORA 500Hz",
+ "DVDA 250Hz (FLRC)",
+ "DVDA 500Hz (FLRC)",
+ "FLRC 500Hz",
+ "FLRC 1000Hz",
+ "DVDA 50Hz",
+ "LORA 200Hz 8CH",
+ "FSK 2G4 DVDA 500Hz",
+ "FSK 2G4 1000Hz",
+ "FSK 900 1000Hz",
+ "FSK 900 1000Hz 8CH"};
+ if (rfModeIndex > ExpressLrsRfModes.size())
+ return "Unknown";
+ return ExpressLrsRfModes[rfModeIndex];
+ }
+
+ constexpr int UplinkTxPower() {
+ constexpr std::array TxPowers{0, 10, 25, 100, 500, 1000, 2000, 250, 50};
+ if (uplinkTxPowerIndex > TxPowers.size())
+ return -1;
+ return TxPowers[uplinkTxPowerIndex];
+ }
+};
+
+#pragma pack(pop)
+
+} // namespace crsf::protocol
diff --git a/src/main.cpp b/src/main.cpp
new file mode 100644
index 0000000..0d8de67
--- /dev/null
+++ b/src/main.cpp
@@ -0,0 +1,605 @@
+/* SPDX-License-Identifier: MPL-2.0
+ * Copyright © Mark Collins
+ */
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "common/scope.h"
+#include "common/thread_name.h"
+
+#include "crsf/crsf.h"
+#include "crsf/parameter.h"
+#include "serial/serial.h"
+
+class ElrsManager {
+ private:
+ crsf::Interface crsfInterface;
+
+ std::mutex stateMutex;
+ std::condition_variable stateCV;
+
+ std::vector devices;
+ std::jthread rxThread, txThread;
+ bool earlyPing{}; //!< Send a ping frame early, this is used when a packet with an unrecognized device is found.
+ size_t pingsSinceLastRx{}; //!< Number of pings sent since the last received packet.
+
+ std::optional linkStatistics{};
+ std::optional channelFrame{};
+ std::optional batteryData{};
+
+ SDL_Joystick* joystick{};
+ struct ButtonState {
+ bool pressed{}; //!< Whether the button is currently pressed, this is necessary to track releases for toggling.
+ bool toggled{}; //!< Turns true when the button is pressed and false when it is pressed again.
+ };
+ std::vector buttonStates;
+ bool showJoystickData{}; //!< Whether to show the joystick input data.
+
+ crsf::Device* FindDevice(crsf::Address address) {
+ auto it{std::find_if(devices.begin(), devices.end(), [&](const crsf::Device& device) { return device.address == address; })};
+ if (it == devices.end())
+ return nullptr;
+ return &*it;
+ }
+
+ void RxThread(std::stop_token stopToken) {
+ SetThreadName("ELRS RX");
+ while (!stopToken.stop_requested()) {
+ try {
+ std::optional frameV{crsfInterface.ReceiveFrame(std::chrono::steady_clock::now() + std::chrono::seconds{1})};
+ // Note: Timeouts are important so that stop tokens are checked frequently.
+ if (!frameV)
+ continue;
+
+ std::scoped_lock lock{stateMutex};
+ std::visit([&](auto&& frame) {
+ using T = std::decay_t;
+
+ if constexpr (std::is_same_v) {
+ batteryData = frame.battery;
+ } else if constexpr (std::is_same_v) {
+ linkStatistics = frame.statistics;
+ } else if constexpr (std::is_same_v) {
+ fmt::print("Ping frame\n");
+ } else if constexpr (std::is_same_v) {
+ crsf::Device* device{FindDevice(frame.originAddress)};
+ if (device) {
+ device->Update(frame.deviceName, frame.deviceMetadata);
+ fmt::print("Updated device: {}\n", device->name);
+ } else {
+ device = &devices.emplace_back(frame.originAddress, frame.deviceName, frame.deviceMetadata);
+ fmt::print("Added device: {}\n", device->name);
+ }
+ } else if constexpr (std::is_same_v) {
+ auto device{FindDevice(frame.originAddress)};
+ if (!device) {
+ earlyPing = true;
+ fmt::print("Device not found: 0x{:X}\n", static_cast(frame.originAddress));
+ return;
+ }
+
+ crsf::Parameter* parameter{device->FindParameter(frame.fieldIndex)};
+ if (parameter) {
+ if (parameter->complete)
+ return;
+ parameter->ProcessChunk(frame.data, frame.chunksRemaining);
+ } else {
+ fmt::print("Parameter not found: {}\n", frame.fieldIndex);
+ return;
+ }
+ } else if constexpr (std::is_same_v) {
+ auto device{FindDevice(frame.originAddress)};
+ if (!device) {
+ earlyPing = true;
+ fmt::print("Device not found: 0x{:X}\n", static_cast(frame.originAddress));
+ return;
+ }
+
+ device->syncData = frame.sync;
+ } else {
+ throw Exception("Unknown frame type: 0x{:X}", static_cast(frame.type));
+ }
+ },
+ *frameV);
+
+ pingsSinceLastRx = 0;
+ stateCV.notify_all();
+ } catch (std::exception& e) {
+ fmt::print("RX Error: {}\n", e.what());
+ if (!crsfInterface.IsActive()) {
+ fmt::print("Serial port is inactive, stopping RX thread\n");
+ requestStop = true;
+ return;
+ }
+ }
+ }
+ }
+
+ void TxThread(std::stop_token stopToken) {
+ SetThreadName("ELRS TX");
+
+ std::chrono::time_point wakeTime{std::chrono::steady_clock::now()}, pingTime{wakeTime};
+ constexpr std::chrono::milliseconds WakeInterval{100}, PingInterval{5000};
+
+ bool recurringException{};
+ while (!stopToken.stop_requested()) {
+ std::unique_lock lock{stateMutex};
+ stateCV.wait_until(lock, wakeTime > pingTime ? wakeTime : pingTime);
+
+ try {
+ if (pingsSinceLastRx >= 2) {
+ fmt::print("No packets received after two pings, resetting device\n");
+ crsfInterface.ResetDevice();
+ pingsSinceLastRx = 0;
+ earlyPing = true;
+ }
+
+ if (channelFrame) {
+ crsfInterface.SendFrame(*channelFrame);
+ channelFrame.reset();
+ }
+
+ bool sentFrame{};
+ for (crsf::Device& device : devices) {
+ auto frame{device.TryGetTxFrame()};
+
+ if (frame) {
+ crsfInterface.SendFrame(*frame);
+ sentFrame = true;
+ }
+ }
+
+ if (earlyPing || std::chrono::steady_clock::now() >= pingTime) {
+ crsf::PingFrame ping{crsf::Address::Broadcast, crsf::Address::ElrsLua};
+ crsfInterface.SendFrame(ping);
+ fmt::print("Sent ping frame\n");
+
+ earlyPing = false;
+ pingsSinceLastRx++;
+ pingTime = std::chrono::steady_clock::now() + PingInterval;
+ }
+
+ wakeTime = std::chrono::steady_clock::now() + WakeInterval;
+ } catch (std::exception& e) {
+ fmt::print("TX Error: {}\n", e.what());
+ if (!crsfInterface.IsActive()) {
+ fmt::print("Serial port is inactive, stopping TX thread\n");
+ requestStop = true;
+ return;
+ }
+ if (recurringException) {
+ fmt::print("Recurring exception, trying to reset the device\n");
+ crsfInterface.ResetDevice();
+ }
+ recurringException = true;
+ }
+ }
+ }
+
+ public:
+ bool requestStop{}; //!< If any of the threads have requested a stop, this happens when they can no longer continue due to an error or the serial port being closed.
+
+ ElrsManager(std::string portName, size_t baudRate)
+ : crsfInterface{portName, baudRate}
+ , rxThread{std::bind_front(&ElrsManager::RxThread, this)}
+ , txThread{std::bind_front(&ElrsManager::TxThread, this)} {}
+
+ bool HasJoystick() {
+ if (joystick) {
+ if (SDL_JoystickConnected(joystick))
+ return true;
+ SDL_CloseJoystick(joystick);
+ joystick = nullptr;
+ }
+
+ if (SDL_HasJoystick()) {
+ int joystickCount{};
+ auto joysticks{SDL_GetJoysticks(&joystickCount)};
+ if (joystickCount > 0) {
+ joystick = SDL_OpenJoystick(joysticks[0]);
+ if (joystick != nullptr) {
+ fmt::print("Opened joystick: {}\n", SDL_GetJoystickName(joystick));
+ buttonStates.resize(SDL_GetNumJoystickButtons(joystick));
+ return true;
+ } else {
+ fmt::print("Failed to open joystick: {}\n", SDL_GetError());
+ }
+ }
+ }
+
+ return false;
+ }
+
+ void Draw() {
+ std::scoped_lock lock{stateMutex};
+
+ try {
+ bool wrotePackets{};
+
+ if (linkStatistics) {
+ ImGui::Text("Link Statistics:");
+ ImGui::Indent();
+
+ ImGui::Text("RF Mode: %s", linkStatistics->RfMode());
+ ImGui::Text("Diversity active antenna: %d", linkStatistics->activeAntenna);
+
+ // Uplink
+ ImGui::Text("Uplink TX Power: %d mW", linkStatistics->UplinkTxPower());
+ ImGui::ProgressBar(linkStatistics->UplinkRssi1Norm(), ImVec2(0.0f, 0.0f), fmt::format("Uplink RSSI Ant. 1: {} dBm", linkStatistics->UplinkRssi1()).c_str());
+ ImGui::ProgressBar(linkStatistics->UplinkRssi2Norm(), ImVec2(0.0f, 0.0f), fmt::format("Uplink RSSI Ant. 1: {} dBm", linkStatistics->UplinkRssi2()).c_str());
+ ImGui::ProgressBar(linkStatistics->UplinkLinkQualityNorm(), ImVec2(0.0f, 0.0f), fmt::format("Uplink Package success rate: {}%", linkStatistics->uplinkLinkQuality).c_str());
+ ImGui::ProgressBar(linkStatistics->UplinkSnrNorm(), ImVec2(0.0f, 0.0f), fmt::format("Uplink SNR: {} dB", linkStatistics->uplinkSnr).c_str());
+
+ // Downlink
+ ImGui::ProgressBar(linkStatistics->DownlinkRssiNorm(), ImVec2(0.0f, 0.0f), fmt::format("Downlink RSSI: {} dBm", linkStatistics->DownlinkRssi()).c_str());
+ ImGui::ProgressBar(linkStatistics->DownlinkLinkQualityNorm(), ImVec2(0.0f, 0.0f), fmt::format("Downlink package success rate: {}%", linkStatistics->downlinkLinkQuality).c_str());
+ ImGui::ProgressBar(linkStatistics->DownlinkSnrNorm(), ImVec2(0.0f, 0.0f), fmt::format("Downlink SNR: {} dB", linkStatistics->downlinkSnr).c_str());
+
+ ImGui::Unindent();
+
+ for (crsf::Device& device : devices) {
+ if (device.syncData) {
+ ImGui::Text("Device: %s (Address: 0x%02hhX)", device.name.c_str(), static_cast(device.address));
+ ImGui::Indent();
+ ImGui::Text("Packet Rate: %d", device.syncData->packetRate);
+ ImGui::Text("Packet Offset: %d", device.syncData->packetOffset);
+ ImGui::Unindent();
+ }
+ }
+
+ ImGui::Separator();
+ }
+
+ {
+ ImGui::Text("RC Channels:");
+ ImGui::Indent();
+
+ if (HasJoystick()) {
+ SDL_LockJoysticks();
+
+ for (int i{}; i < SDL_GetNumJoystickButtons(joystick); i++) {
+ bool pressed{static_cast(SDL_GetJoystickButton(joystick, i))};
+ ButtonState& buttonState{buttonStates[i]};
+ if (pressed && !buttonState.pressed) {
+ buttonState.pressed = true;
+ buttonState.toggled = !buttonState.toggled;
+ } else if (!pressed && buttonState.pressed) {
+ buttonState.pressed = false;
+ }
+ }
+
+ constexpr u16 CrsfChannelMin{172 + 5}, CrsfChannelMid{992}, CrsfChannelMax{1811 - 5}, CrsfChannelDiff{CrsfChannelMax - CrsfChannelMin};
+ constexpr u16 JoystickDeadzone{2000};
+
+ auto getAxisValue{[&](int axis, bool invert = false) -> u16 {
+ i16 inputValue{SDL_GetJoystickAxis(joystick, axis)};
+ if (invert) {
+ if (inputValue == INT16_MIN)
+ inputValue = INT16_MAX;
+ else
+ inputValue *= -1;
+ }
+ if (abs(inputValue) < JoystickDeadzone)
+ return CrsfChannelMid;
+
+ // Shift the input value from -32768 to 32767 (signed 16-bit) to 0 to 65535 (unsigned 16-bit)
+ u32 unsignedValue{static_cast(inputValue) + (INT16_MAX + 1)};
+
+ // Scale the shifted value to the CRSF range
+ u32 crsfValue{((unsignedValue * CrsfChannelDiff) / UINT16_MAX) + CrsfChannelMin};
+
+ return static_cast(crsfValue);
+ }};
+
+ /* getCombinedTriggerValue, combines anegative axis and the positive axis them into a single axis which is:
+ * * Centered when both are at their minimum.
+ * * At the maximum value, if the positive axis is at its max.
+ * * At the minimum value, if the negative axis is at its max.
+ */
+ auto getCombinedTriggerValue{[&](int negativeAxis, int positiveAxis, bool invert = false) -> u16 {
+ i16 negativeInputValue{SDL_GetJoystickAxis(joystick, negativeAxis)};
+ if (abs(negativeInputValue) < JoystickDeadzone)
+ negativeInputValue = 0;
+ u32 negativeUnsignedValue{static_cast(negativeInputValue) + (INT16_MAX + 1)};
+
+ i16 positiveInputValue{SDL_GetJoystickAxis(joystick, positiveAxis)};
+ if (abs(positiveInputValue) < JoystickDeadzone)
+ positiveInputValue = 0;
+ u32 positiveUnsignedValue{static_cast(positiveInputValue) + (INT16_MAX + 1)};
+
+ // Shift the input value from -32768 to 32767 (signed 16-bit) to 0 to 65535 (unsigned 16-bit)
+ u32 unsignedValue{INT16_MAX};
+ unsignedValue += positiveUnsignedValue / 2;
+ unsignedValue -= negativeUnsignedValue / 2;
+
+ // Scale the shifted value to the CRSF range
+ u32 crsfValue{((unsignedValue * CrsfChannelDiff) / UINT16_MAX) + CrsfChannelMin};
+
+ return static_cast(crsfValue);
+ }};
+
+ auto getButtonToggle{[&](int button) -> u16 {
+ return buttonStates[button].toggled ? CrsfChannelMid : CrsfChannelMin;
+ }};
+
+ crsf::RcChannelsData crsfChannels{};
+ crsfChannels.set(0, getAxisValue(SDL_GAMEPAD_AXIS_RIGHTX));
+ crsfChannels.set(1, getAxisValue(SDL_GAMEPAD_AXIS_RIGHTY, true));
+ crsfChannels.set(2, getCombinedTriggerValue(SDL_GAMEPAD_AXIS_LEFT_TRIGGER, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER));
+ crsfChannels.set(3, getAxisValue(SDL_GAMEPAD_AXIS_LEFTX));
+ // CRSF Aux 1 value is ignored for some reason.
+ crsfChannels.set(5, getButtonToggle(SDL_GAMEPAD_BUTTON_START));
+ crsfChannels.set(6, getButtonToggle(SDL_GAMEPAD_BUTTON_LEFT_STICK));
+
+ constexpr std::array channelLabels{"Roll", "Pitch", "Throttle", "Yaw", "Aux 1", "Aux 2", "Aux 3"};
+ for (int i{}; i < channelLabels.size(); i++) {
+ float scaledValue{static_cast(crsfChannels.get(i) - CrsfChannelMin) / CrsfChannelDiff};
+ ImGui::ProgressBar(scaledValue, ImVec2(0.0f, 0.0f), channelLabels[i]);
+ }
+
+ if (!channelFrame || channelFrame->channels != crsfChannels) {
+ channelFrame = crsf::RcChannelsFrame(crsfChannels, crsf::Address::FlightController);
+ wrotePackets = true;
+ }
+
+ ImGui::Checkbox("Show Joystick Input", &showJoystickData);
+ if (showJoystickData) {
+ ImGui::Text("Name: %s", SDL_GetJoystickName(joystick));
+ for (int i{}; i < SDL_GetNumJoystickAxes(joystick); i++) {
+ ImGui::Text("Axis %d:", i);
+ ImGui::Indent();
+ i16 signedValue{SDL_GetJoystickAxis(joystick, i)};
+ u32 unsignedValue{static_cast(i32{signedValue} - (std::numeric_limits::min)())};
+ float value{static_cast(unsignedValue) / (std::numeric_limits::max)()};
+ ImGui::ProgressBar(value, ImVec2(-100, 0), fmt::format("Axis {}", i).c_str());
+ ImGui::Unindent();
+ }
+
+ for (int i{}; i < SDL_GetNumJoystickButtons(joystick); i++) {
+ ButtonState& buttonState{buttonStates[i]};
+ ImGui::Text("Button %d:", i);
+ ImGui::Indent();
+ ImGui::Checkbox("Pressed", &buttonState.pressed);
+ ImGui::Checkbox("Toggled", &buttonState.toggled);
+ ImGui::Unindent();
+ }
+ }
+
+ SDL_UnlockJoysticks();
+ } else {
+ ImGui::Text("No joystick connected");
+ }
+
+ ImGui::Unindent();
+ ImGui::Separator();
+ }
+
+ if (batteryData) {
+ ImGui::Text("Battery:");
+ ImGui::Indent();
+ ImGui::Text("Voltage: %.2f V", batteryData->Voltage());
+ ImGui::Text("Current: %.2f A", batteryData->Current());
+ ImGui::Text("Capacity: %.2f Ah", batteryData->Capacity());
+ ImGui::Text("Remaining Capacity: %d%%", batteryData->RemainingCapacity());
+ ImGui::Unindent();
+ ImGui::Separator();
+ }
+
+ for (crsf::Device& device : devices) {
+ ImGui::Text("Device: %s (Address: 0x%02hhX, Serial No: 0x%08X)", device.name.c_str(), static_cast(device.address), device.metadata.serialNo);
+ ImGui::Indent();
+ ImGui::Text("HW Version: 0x%02X, SW Version: 0x%02X", device.metadata.hardwareVersion, device.metadata.softwareVersion);
+ ImGui::Text("Parameters: (v0x%02X - %d)", device.metadata.parameterVersion, device.metadata.fieldCount);
+
+ ImGui::Indent();
+ for (crsf::Parameter& parameter : device.parameters) {
+ if (parameter.complete || parameter.activeCommand) {
+ std::visit([&](auto value) {
+ if constexpr (std::is_same_v> || std::is_same_v> || std::is_same_v> || std::is_same_v>) {
+ i64 integerValue{static_cast(value.value)};
+ i64 step{1};
+ if (ImGui::InputScalar(parameter.name.data(), ImGuiDataType_U64, &integerValue, &step)) {
+ if (integerValue < value.min)
+ integerValue = value.min;
+ else if (integerValue > value.max)
+ integerValue = value.max;
+ value.value = static_cast(integerValue);
+ fmt::print("Set '{}' to {}\n", parameter.name, value.value);
+ device.WriteParameter(parameter.fieldIndex, value.value);
+ wrotePackets = true;
+ }
+ } else if constexpr (std::is_same_v) {
+ std::string format{"%." + std::to_string(value.precision) + "f"};
+ if (ImGui::InputFloat(parameter.name.data(), &value.value, value.step, value.step * 10, format.c_str())) {
+ if (value.value < value.min)
+ value.value = value.min;
+ else if (value.value > value.max)
+ value.value = value.max;
+ fmt::print("Set '{}' to {}\n", parameter.name, value.value);
+ device.WriteParameter(parameter.fieldIndex, value.value);
+ wrotePackets = true;
+ }
+ } else if constexpr (std::is_same_v) {
+ ImGui::Text("%s", parameter.name.data());
+ if (ImGui::BeginCombo(fmt::format("##PARAM{}-{}", parameter.fieldIndex, device.name).c_str(), std::string{value.options[value.selectedIndex]}.c_str())) {
+ for (u8 i{0}; i < value.options.size(); ++i) {
+ bool selected{i == value.selectedIndex};
+ if (ImGui::Selectable(fmt::format("{}{}", value.options[i], i == value.defaultIndex ? " (Default)" : "").c_str(), selected)) {
+ value.selectedIndex = i;
+ fmt::print("Selected '{}' ({}) in field #{} ({})\n", value.options[i], i, parameter.fieldIndex, parameter.name);
+ device.WriteParameter(parameter.fieldIndex, static_cast(i));
+ wrotePackets = true;
+ }
+ if (selected)
+ ImGui::SetItemDefaultFocus();
+ }
+ ImGui::EndCombo();
+ }
+ } else if constexpr (std::is_same_v) {
+ ImGui::Unindent();
+ ImGui::Text("%s", value.displayName.empty() ? parameter.name.data() : value.displayName.data());
+ ImGui::Indent();
+ } else if constexpr (std::is_same_v) {
+ ImGui::Text("%s: %s", parameter.name.data(), value.display.data());
+ } else if constexpr (std::is_same_v) {
+ if (ImGui::Button(parameter.name.data())) {
+ device.WriteParameter(parameter.fieldIndex, static_cast(crsf::CommandStep::Click));
+ wrotePackets = true;
+ } else if (parameter.complete && parameter.activeCommand && parameter.updateTime + std::chrono::seconds{1} < std::chrono::steady_clock::now()) {
+ device.WriteParameter(parameter.fieldIndex, static_cast(crsf::CommandStep::Query));
+ wrotePackets = true;
+ }
+ if (value.step != crsf::CommandStep::Idle) {
+ ImGui::SameLine();
+ ImGui::Text("%s", crsf::CommandStepToString(value.step));
+ }
+ } else {
+ ImGui::Text("Unhandled '%s' type: %d", parameter.name.data(), static_cast(parameter.type));
+ }
+ },
+ parameter.value);
+ } else {
+ ImGui::Text("Parameter #%d", parameter.fieldIndex);
+ }
+ }
+ ImGui::Unindent();
+
+ ImGui::Unindent();
+ ImGui::Separator();
+ }
+
+ if (wrotePackets)
+ stateCV.notify_all();
+ } catch (std::exception& e) {
+ fmt::print("Error: {}\n", e.what());
+ ImGui::Text("Error: %s", e.what());
+ }
+ }
+};
+
+int main(int argv, char** args) {
+ /* SDL */
+ SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
+
+ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD) != 0)
+ throw Exception("SDL initialization failed: {}", SDL_GetError());
+
+ SDL_Window* window{SDL_CreateWindow("DeckTX", 1920, 1080, SDL_WINDOW_VULKAN | SDL_WINDOW_HIGH_PIXEL_DENSITY)};
+ if (window == nullptr)
+ throw Exception("SDL window creation failed: {}", SDL_GetError());
+
+ /* SDL Renderer */
+ SDL_Renderer* renderer{SDL_CreateRenderer(window, nullptr)};
+ if (renderer == nullptr)
+ throw Exception("SDL renderer creation failed: {}", SDL_GetError());
+ SDL_SetRenderVSync(renderer, 1);
+
+ SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
+ SDL_SetWindowResizable(window, SDL_TRUE);
+ SDL_ShowWindow(window);
+
+ /* IMGUI */
+ IMGUI_CHECKVERSION();
+ ImGui::CreateContext();
+ ImGuiIO& io{ImGui::GetIO()};
+ io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
+ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
+ io.IniFilename = nullptr;
+
+ ImGui::StyleColorsDark();
+
+ ImGui_ImplSDL3_InitForSDLRenderer(window, renderer);
+ ImGui_ImplSDLRenderer3_Init(renderer);
+
+ /* Main Loop */
+ std::optional selectedPort{};
+ u32 baudRate{1200000};
+ std::string error{};
+ std::optional manager;
+
+ bool running{true};
+ while (running) {
+ SDL_Event event;
+ while (SDL_PollEvent(&event)) {
+ ImGui_ImplSDL3_ProcessEvent(&event);
+
+ if (event.type == SDL_EVENT_QUIT)
+ running = false;
+ }
+
+ ImGui_ImplSDLRenderer3_NewFrame();
+ ImGui_ImplSDL3_NewFrame();
+ ImGui::NewFrame();
+
+ const ImGuiViewport* viewport{ImGui::GetMainViewport()};
+ ImGui::SetNextWindowPos(viewport->WorkPos);
+ ImGui::SetNextWindowSize(viewport->WorkSize);
+
+ {
+ ImGui::Begin("DeckTX", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse);
+ SCOPE_EXIT(ImGui::End());
+
+ if (manager) {
+ manager->Draw();
+ if (ImGui::Button("Disconnect") || manager->requestStop)
+ manager.reset();
+ } else {
+ std::vector ports{ListSerialPorts()};
+ if (!selectedPort && !ports.empty())
+ selectedPort = ports.front();
+
+ if (ImGui::BeginCombo("Serial Port", selectedPort ? selectedPort->friendlyName.c_str() : "")) {
+ for (const SerialPortInfo& it : ports) {
+ bool selected{selectedPort->devicePath == it.devicePath};
+ if (ImGui::Selectable(it.friendlyName.c_str(), selected))
+ selectedPort = it;
+ if (selected)
+ ImGui::SetItemDefaultFocus();
+ }
+ ImGui::EndCombo();
+ }
+
+ ImGui::InputScalar("Baud Rate", ImGuiDataType_U32, &baudRate);
+
+ if (ImGui::Button("Connect")) {
+ if (selectedPort) {
+ ImGui::Text("Connecting to port: %s", selectedPort->friendlyName.c_str());
+ fmt::print("Connecting to port: {}\n", selectedPort->friendlyName);
+
+ try {
+ manager.emplace(selectedPort->devicePath, baudRate);
+ } catch (std::exception& e) {
+ error = e.what();
+ manager.reset();
+ }
+ }
+ }
+
+ if (!error.empty())
+ ImGui::Text("Error: %s", error.c_str());
+ }
+ }
+
+ ImGui::Render();
+ SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
+ SDL_RenderClear(renderer);
+ ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), renderer);
+
+ SDL_RenderPresent(renderer);
+ }
+
+ SDL_DestroyWindow(window);
+
+ SDL_Quit();
+
+ return 0;
+}
\ No newline at end of file
diff --git a/src/serial/serial.cpp b/src/serial/serial.cpp
new file mode 100644
index 0000000..4ed0203
--- /dev/null
+++ b/src/serial/serial.cpp
@@ -0,0 +1,443 @@
+/* SPDX-License-Identifier: MIT
+ * Copyright © Craig Lilley
+ * Copyright © Yan Naing Aye
+ * Copyright © Mark Collins
+ * Heavily derivative of wjwwood/serial, see https://github.com/wjwwood/serial/tree/69e0372cf0d3796e84ce9a09aff1d74496f68720/src/impl/list_ports
+ * Heavily derivative of yan9a/serial, see https://github.com/yan9a/serial/blob/7346457660b192a38660f53e0ea11565719682f4/ceSerial.h
+ */
+
+#include "serial.h"
+
+#if SERIAL_WIN
+ #include
+ #include
+
+ #include
+ #include
+#elif SERIAL_LINUX
+ #include
+ #include
+ #include
+
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+#else
+ #error "Unsupported platform"
+#endif
+
+#include