initial commit

This commit is contained in:
2025-08-26 19:58:07 -04:00
commit 7367171767
27 changed files with 4618 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
/build/**/*
/external/**/*
+69
View File
@@ -0,0 +1,69 @@
set(PROJECT aw410k_rgb)
cmake_minimum_required(VERSION 3.13)
set(PICO_SDK_PATH /home/kenji/programming/pico/c/pico-sdk)
set(PICO_PIO_USB_PATH /home/kenji/programming/pico/c/Pico-PIO-USB)
set(PICO_BOARD pico2)
set(TUSB_NETWORKING_PATH ${PICO_SDK_PATH}/lib/tinyusb/lib/networking)
include (${PICO_SDK_PATH}/external/pico_sdk_import.cmake)
project(${PROJECT} C CXX ASM)
set(MAKE_FS_DATA_SCRIPT ${CMAKE_CURRENT_LIST_DIR}/external/makefsdata)
set(HTML_DIR ${CMAKE_CURRENT_LIST_DIR}/html)
if (NOT EXISTS ${MAKE_FS_DATA_SCRIPT})
file(DOWNLOAD
https://raw.githubusercontent.com/lwip-tcpip/lwip/e799c266facc3c70190676eccad49d6c2db2caac/src/apps/http/makefsdata/makefsdata
${MAKE_FS_DATA_SCRIPT}
)
endif()
message("Running makefsdata script")
execute_process(COMMAND
perl ${MAKE_FS_DATA_SCRIPT}
WORKING_DIRECTORY ${HTML_DIR}
ECHO_OUTPUT_VARIABLE
ECHO_ERROR_VARIABLE
)
file(RENAME ${HTML_DIR}/fsdata.c ${CMAKE_CURRENT_LIST_DIR}/my_fsdata.c)
pico_sdk_init()
add_subdirectory(${PICO_PIO_USB_PATH} pico_pio_usb)
add_executable(${PROJECT})
target_sources(${PROJECT} PRIVATE
aw410k.c
main.c
usb_device.c
usb_host.c
usb_server.c
websocket.c
${TUSB_NETWORKING_PATH}/dhserver.c
${TUSB_NETWORKING_PATH}/dnserver.c
)
# print memory usage, enable all warnings
target_link_options(${PROJECT} PRIVATE -Xlinker --print-memory-usage)
target_compile_options(${PROJECT} PRIVATE ) #-Wall -Wextra
# use tinyusb implementation
target_compile_definitions(${PROJECT} PRIVATE PIO_USB_USE_TINYUSB)
# needed so tinyusb can find tusb_config.h
target_include_directories(${PROJECT} PRIVATE ${CMAKE_CURRENT_LIST_DIR} ${TUSB_NETWORKING_PATH})
target_link_libraries(${PROJECT} PRIVATE
pico_lwip
pico_lwip_arch
pico_lwip_http
pico_mbedtls
pico_stdlib
pico_pio_usb
tinyusb_board
tinyusb_device
tinyusb_host
tinyusb_pico_pio_usb
hardware_adc
)
pico_add_extra_outputs(${PROJECT})
+16
View File
@@ -0,0 +1,16 @@
Alienware AW410K RGB controller - configure individual keyboard LEDs and
adjust brightness using a light dependent resistor
Copyright (C) 2025 Kenji Kozai
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 <https://www.gnu.org/licenses/>.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+99
View File
@@ -0,0 +1,99 @@
# Alienware AW410K RGB Controller
This project provides control to the RGB lighting on an Alienware AW410K
keyboard based on ADC readings from an attached light dependent resistor using
a webpage served by a Raspberry Pi Pico 2. Each key on the keyboard is
individually configurable from the webpage and can be set to automatically
adjust brightness based off the ambient lighting.
![Keyboard lighting changing with light on a LDR](ambient.gif)
## Setup
### Hardware
You will need the following hardware to make the device:
- Raspberry Pi Pico 2
- USB extension cable
- light dependent resistor such as GL5528 (specific part number may vary)
- 10k ohm resistor (resistance value may vary)
You will need to cut the USB extension in half and connect the wires from the
female end to the Raspberry Pi Pico 2. The default configuration is to attach
the USB's green wire to pin 1/GP0 and USB's white wire to pin 2/GP1. You will
also need to connect the red to 5V VBUS/VSYS (since you'll be powering from the
USB host device, VBUS should be fine) and the black to any ground pin. Pin 38
is the closest and most convenient. While you can connect the Raspberry Pi Pico
to the host device using the micro USB port and a micro USB cable, since
you have already sacrificed half of the USB extension cable, you might as well
use the male half to create a standard USB-A connection. If you wish to do so,
then simply connect the red and black wires of the male connector end to
VBUS (5V) and GND, respectively. For the data wires, you can solder them to the
two test points TP2 and TP3 on the back of the Raspberry Pi Pico 2. The white
cable goes to TP2 and the green cable to TP3.
![Back of Raspberry Pi Pico with USB connections to TP2 and TP3](back.jpg)
The LDR should then be connected to the ADC2 pin (pin 34/GP28) and 3.3V (pin 36)
or alternatively to the ADC_VREF (pin 35) and the regular resistor between ADC2
and any ground, including ADC_GND (pin 33). The results look something like
the following.
![Back of Raspberry Pi Pico with USB and LDR connected](front.jpg)
The individual wires on the USB can be fragile, so hot glue or other strain
relief is a good idea. There is also a [model for a 3D printed
enclosure](pico-usb-ldr.stl) that you can use to place the Pico inside with a
hole for the LDR to detect ambient light.
![3D printed enclosure with finished device](enclosure.jpg)
## Software
Flash the aw410k_rgb.uf2 file found from the latest
[release](https://git.kkozai.com/kenji/aw410k_rgb/releases) to the Raspberry Pi
Pico 2, and connect the keyboard to the female USB port and insert the male USB
connector of the device into your host device such as PC.
To load the UI for configuring the RGB lighting, open a browser to the page
at http://aw410k.usb, or if that doesn't load, to http://192.168.40.1. From the
webpage, you can click on any individual key that you want to configure and
change the color using the color selector or by manually inputting the RGB
color value into the text boxes. To finalize setting the color for the
selected key(s), click on the "Set Color" button.
![Interface for setting the color of individual keys](ui.jpg)
To save the lighting configuration to the Pico 2 so that it loads the next time
it is powered on, click on the "Save" button under the "Flash Memory" section.
If you make unsaved changes and want to reload the configuration from memory,
you can also click the "Load" button to reset to the last saved setting.
If the checkbox next to "Adaptive" is selected when setting the color, the key's
brightness will automatically adjust with the ambient lighting, as determined by
the ADC reading of the LDR. Leaving it unchecked will set the RGB color to be
constant regardless of the ambient light level.
The mute button has special behavior when set to adaptive mode. It will toggle
between the user-configured color and red each time that it is pressed as a
way to indicate whether system sounds are muted or not. The keyboard will
always boot in the "unmuted" setting, so if your system starts off muted,
the LED color on the keyboard and your system may not match.
## Licensing
This software is distributed under the [GNU General Public License version
3](LICENSE), with the exception of the libraries in the following section.
## Credits
The project uses code from the following sources:
- [OpenRGB](https://gitlab.com/CalcProgrammer1/OpenRGB/) for code related to
Alienware's [RGB lighting protocol](https://gitlab.com/CalcProgrammer1/OpenRGB/-/tree/master/Controllers/AlienwareKeyboardController/AlienwareAW410KController)
on the AW410K keyboard licensed under GNU-GPLv2
- [Pico-PIO-USB](https://github.com/sekigon-gonnoc/Pico-PIO-USB/) for templates
used from the [host_hid_to_device_cdc](https://github.com/sekigon-gonnoc/Pico-PIO-USB/tree/control-keyboard-led/examples/host_hid_to_device_cdc)
example released under the MIT license
- [TinyUSB](https://github.com/hathach/tinyusb) for templates used from the
[net_lwip_webserver](https://github.com/hathach/tinyusb/tree/master/examples/device/net_lwip_webserver)
example distributed under the MIT license
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

+449
View File
@@ -0,0 +1,449 @@
#include <stdlib.h>
#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "hardware/adc.h"
#include "hardware/flash.h"
#include "tusb.h"
#include "usb_device.h"
#include "websocket.h"
#include "aw410k.h"
static absolute_time_t lastSend;
static absolute_time_t lastRead;
static uint16_t adc_value = 0;
static bool mute = false;
static unsigned char buf[BUF_SIZE];
static uint8_t buf_idx=0;
static uint8_t key_idx=0;
static uint8_t packets_sent=0;
static int64_t delay=0;
static uint8_t report_type=HID_REPORT_TYPE_INVALID;
static uint8_t ws_buf[12];
static uint16_t ws_len;
static void send_color(uint8_t dev_addr);
static void send_initial(uint8_t dev_addr);
static struct key * find_key(char * name);
static void set_color(char * name, uint8_t red, uint8_t green, uint8_t blue, uint8_t mode);
static void set_color_all(uint8_t red, uint8_t green, uint8_t blue, uint8_t mode);
static struct key key_list[NUM_KEYS] =
{
INIT_KEY("KeyA", KEY_A),
INIT_KEY("KeyB", KEY_B),
INIT_KEY("KeyC", KEY_C),
INIT_KEY("KeyD", KEY_D),
INIT_KEY("KeyE", KEY_E),
INIT_KEY("KeyF", KEY_F),
INIT_KEY("KeyG", KEY_G),
INIT_KEY("KeyH", KEY_H),
INIT_KEY("KeyI", KEY_I),
INIT_KEY("KeyJ", KEY_J),
INIT_KEY("KeyK", KEY_K),
INIT_KEY("KeyL", KEY_L),
INIT_KEY("KeyM", KEY_M),
INIT_KEY("KeyN", KEY_N),
INIT_KEY("KeyO", KEY_O),
INIT_KEY("KeyP", KEY_P),
INIT_KEY("KeyQ", KEY_Q),
INIT_KEY("KeyR", KEY_R),
INIT_KEY("KeyS", KEY_S),
INIT_KEY("KeyT", KEY_T),
INIT_KEY("KeyU", KEY_U),
INIT_KEY("KeyV", KEY_V),
INIT_KEY("KeyW", KEY_W),
INIT_KEY("KeyX", KEY_X),
INIT_KEY("KeyY", KEY_Y),
INIT_KEY("KeyZ", KEY_Z),
INIT_KEY("Digit1", KEY_1),
INIT_KEY("Digit2", KEY_2),
INIT_KEY("Digit3", KEY_3),
INIT_KEY("Digit4", KEY_4),
INIT_KEY("Digit5", KEY_5),
INIT_KEY("Digit6", KEY_6),
INIT_KEY("Digit7", KEY_7),
INIT_KEY("Digit8", KEY_8),
INIT_KEY("Digit9", KEY_9),
INIT_KEY("Digit0", KEY_0),
INIT_KEY("Enter", KEY_ENTER),
INIT_KEY("Escape", KEY_ESC),
INIT_KEY("Backspace", KEY_BACKSPACE),
INIT_KEY("Tab", KEY_TAB),
INIT_KEY("Space", KEY_SPACE),
INIT_KEY("Minus", KEY_MINUS),
INIT_KEY("Equal", KEY_EQUAL),
INIT_KEY("BracketLeft", KEY_LEFTBRACE),
INIT_KEY("BracketRight", KEY_RIGHTBRACE),
INIT_KEY("Backslash", KEY_BACKSLASH),
INIT_KEY("Semicolon", KEY_SEMICOLON),
INIT_KEY("Quote", KEY_APOSTROPHE),
INIT_KEY("Backquote", KEY_GRAVE),
INIT_KEY("Comma", KEY_COMMA),
INIT_KEY("Period", KEY_DOT),
INIT_KEY("Slash", KEY_SLASH),
INIT_KEY("CapsLock", KEY_CAPSLOCK),
INIT_KEY("F1", KEY_F1),
INIT_KEY("F2", KEY_F2),
INIT_KEY("F3", KEY_F3),
INIT_KEY("F4", KEY_F4),
INIT_KEY("F5", KEY_F5),
INIT_KEY("F6", KEY_F6),
INIT_KEY("F7", KEY_F7),
INIT_KEY("F8", KEY_F8),
INIT_KEY("F9", KEY_F9),
INIT_KEY("F10", KEY_F10),
INIT_KEY("F11", KEY_F11),
INIT_KEY("F12", KEY_F12),
INIT_KEY("PrintScreen", KEY_SYSRQ),
INIT_KEY("ScrollLock", KEY_SCROLLLOCK),
INIT_KEY("Pause", KEY_PAUSE),
INIT_KEY("Insert", KEY_INSERT),
INIT_KEY("Home", KEY_HOME),
INIT_KEY("PageUp", KEY_PAGEUP),
INIT_KEY("Delete", KEY_DELETE),
INIT_KEY("End", KEY_END),
INIT_KEY("PageDown", KEY_PAGEDOWN),
INIT_KEY("ArrowRight", KEY_RIGHT),
INIT_KEY("ArrowLeft", KEY_LEFT),
INIT_KEY("ArrowDown", KEY_DOWN),
INIT_KEY("ArrowUp", KEY_UP),
INIT_KEY("NumLock", KEY_NUMLOCK),
INIT_KEY("NumpadDivide", KEY_KPSLASH),
INIT_KEY("NumpadMultiply", KEY_KPASTERISK),
INIT_KEY("NumpadSubtract", KEY_KPMINUS),
INIT_KEY("NumpadAdd", KEY_KPPLUS),
INIT_KEY("NumpadEnter", KEY_KPENTER),
INIT_KEY("Numpad1", KEY_KP1),
INIT_KEY("Numpad2", KEY_KP2),
INIT_KEY("Numpad3", KEY_KP3),
INIT_KEY("Numpad4", KEY_KP4),
INIT_KEY("Numpad5", KEY_KP5),
INIT_KEY("Numpad6", KEY_KP6),
INIT_KEY("Numpad7", KEY_KP7),
INIT_KEY("Numpad8", KEY_KP8),
INIT_KEY("Numpad9", KEY_KP9),
INIT_KEY("Numpad0", KEY_KP0),
INIT_KEY("NumpadDecimal", KEY_KPDOT),
INIT_KEY("ControlLeft", KEY_LEFTCTRL),
INIT_KEY("ShiftLeft", KEY_LEFTSHIFT),
INIT_KEY("AltLeft", KEY_LEFTALT),
INIT_KEY("MetaLeft", KEY_LEFTMETA),
INIT_KEY("ControlRight", KEY_RIGHTCTRL),
INIT_KEY("ShiftRight", KEY_RIGHTSHIFT),
INIT_KEY("AltRight", KEY_RIGHTALT),
INIT_KEY("MetaRight", KEY_RIGHTMETA),
INIT_KEY("ContextMenu", KEY_MENU),
INIT_KEY_MUTE("Mute", KEY_MUTE),
INIT_KEY("VolumeDown", KEY_VOLUMEDOWN),
INIT_KEY("VolumeUp", KEY_VOLUMEUP)
};
void get_light() {
// get ADC reading from LDR every 500ms
// if above threshold, set backlight to off
if ( absolute_time_diff_us(lastRead, get_absolute_time()) >= 500000) {
adc_value = adc_read();
}
}
void rgb_task(uint8_t dev_addr) {
// the RGB protocol used by Alienware sends individual RGB data in
// multiple packets after a series of initialization packets
// the code here will determine if we are in the middle of sending
// updated color into (packets_sent>0) and continue to send the next
// packet at designated intervals
// if sending is complete, it will wait before sending again
if ( absolute_time_diff_us(lastSend, get_absolute_time()) >= delay) {
if ( packets_sent < 4) {
// first packets are initialization packets
send_initial(dev_addr);
} else {
// remaining packets are color packets
send_color(dev_addr);
}
lastSend = get_absolute_time();
}
}
// send color packet - 64 byte packet contains RGB values for 4 keys
static void send_color(uint8_t dev_addr) {
memset(buf, 0x00, BUF_SIZE);
// set header info
buf[0] = 0x0E;
buf[1] = 0x01;
buf[3] = packets_sent-3;
buf_idx = 4;
// send colors, data is in sets of 15 bytes
while (key_idx < NUM_KEYS && buf_idx < BUF_SIZE) {
buf[buf_idx] = key_list[key_idx].val;
buf[buf_idx+1] = 0x81;
buf[buf_idx+3] = 0xA5;
buf[buf_idx+5] = 0x0A;
switch (key_list[key_idx].mode) {
case RGB_MODE_ADAPTIVE: // adjust brightness based on LDR ADC reading
buf[buf_idx+6] = (ADC_MAX-adc_value)*key_list[key_idx].red/ADC_MAX;
buf[buf_idx+7] = (ADC_MAX-adc_value)*key_list[key_idx].green/ADC_MAX;
buf[buf_idx+8] = (ADC_MAX-adc_value)*key_list[key_idx].blue/ADC_MAX;
break;
case RGB_MODE_MUTE:
if (mute) {
buf[buf_idx+6] = 0xFF; // red
buf[buf_idx+7] = 0x00;
buf[buf_idx+8] = 0x00;
} else {
buf[buf_idx+6] = key_list[key_idx].red;
buf[buf_idx+7] = key_list[key_idx].green;
buf[buf_idx+8] = key_list[key_idx].blue;
}
break;
default:
buf[buf_idx+6] = key_list[key_idx].red;
buf[buf_idx+7] = key_list[key_idx].green;
buf[buf_idx+8] = key_list[key_idx].blue;
break;
}
buf[buf_idx+13] = 0x01;
key_idx++;
buf_idx += 15;
}
// send color packets until done
if (tuh_hid_send_report(dev_addr, RGB_ITF, RGB_REPORT_ID, buf, BUF_SIZE)) {
packets_sent++;
delay=5000;
}
// completed all color packets, wait before starting next cycle
if (key_idx >= NUM_KEYS) {
key_idx = 0;
packets_sent = 0;
delay = 1000000;
}
}
// send initialization packets to keyboard to put into direct lighting mode
static void send_initial(uint8_t dev_addr) {
memset(buf, 0x00, BUF_SIZE);
report_type = HID_REPORT_TYPE_INVALID;
switch ( packets_sent ) {
case 0:
buf[0] = 0x0E;
buf[1] = 0x01;
buf[3] = 0x01;
buf[4] = 0xAD;
buf[5] = 0x80;
buf[6] = 0x10;
buf[7] = 0xA5;
buf[9] = 0x0A;
buf[17] = 0x01;
report_type = HID_REPORT_TYPE_OUTPUT;
delay = 5000;
break;
case 1:
buf[0] = 0x05;
buf[1] = 0x01;
buf[2] = 0x51;
report_type = HID_REPORT_TYPE_FEATURE;
delay = 10000;
break;
case 2:
buf[0] = 0x05;
buf[1] = 0x01;
buf[9] = 0x10;
buf[10] = 0x0A;
buf[11] = 0x01;
buf[12] = 0x02;
buf[13] = 0x01;
report_type = HID_REPORT_TYPE_OUTPUT;
delay = 20000;
break;
case 3:
buf[0] = 0x0E;
buf[1] = NUM_KEYS;
buf[3] = 0x01;
report_type = HID_REPORT_TYPE_FEATURE;
delay = 10000;
break;
default:
break;
}
if ( report_type == HID_REPORT_TYPE_FEATURE ) {
if (tuh_hid_set_report(dev_addr, RGB_ITF, RGB_REPORT_ID, report_type, buf, BUF_SIZE)) {
packets_sent++;
}
} else {
if (tuh_hid_send_report(dev_addr, RGB_ITF, RGB_REPORT_ID, buf, BUF_SIZE)) {
packets_sent++;
}
}
}
// find key by name
static struct key * find_key(char * name) {
for (uint8_t i=0; i<NUM_KEYS; i++) {
if ( strcmp(key_list[i].name, name) == 0 ) {
return &(key_list[i]);
}
}
return NULL;
}
// set RGB color for key by name
static void set_color(char * name, uint8_t red, uint8_t green, uint8_t blue, uint8_t mode) {
struct key * set_key;
set_key = find_key(name);
if (set_key != NULL) {
set_key->red = red;
set_key->green = green;
set_key->blue = blue;
if ( set_key->val == KEY_MUTE && mode == RGB_MODE_ADAPTIVE ) {
mode = RGB_MODE_MUTE;
}
set_key->mode = mode;
cdc_count = sprintf(cdc_buf, "key: %02X color: (%u,%u,%u) mode: %u\n", set_key->val, set_key->red, set_key->green, set_key->blue, set_key->mode);
tud_cdc_write(cdc_buf, cdc_count);
}
}
// set RGB color for all keys
static void set_color_all(uint8_t red, uint8_t green, uint8_t blue, uint8_t mode) {
for (uint8_t i=0; i<NUM_KEYS; i++) {
key_list[i].red = red;
key_list[i].green = green;
key_list[i].blue = blue;
// don't change modes on MUTE only to preserve toggling behavior
// user can set manually from GUI if desired
if (key_list[i].val != KEY_MUTE) {
key_list[i].mode = mode;
}
}
}
// parse color request from webpage and update keyboard colors
void parse_colors(char * data, uint16_t len) {
(void) len;
// Javascript sends the list of keys in a comma delimited format with the
// first entry being the color code, so split at commas
char * token = strtok(data, ",");
if (token != NULL) {
// first string is the RGB color code
uint8_t red, green, blue;
sscanf(token, "%02x%02x%02x", &red, &green, &blue);
token = strtok(NULL, ",");
if (token != NULL) {
// second string is mode flag
uint8_t mode = RGB_MODE_SOLID;
if ( strcmp(token, "1") == 0 ) {
mode = RGB_MODE_ADAPTIVE;
}
// extract the keys from the rest of the string and set to the preceding color
token = strtok(NULL, ",");
while (token != NULL) {
set_color(token, red, green, blue, mode);
token = strtok(NULL, ",");
}
}
}
}
// parse send color request and return color of first selected key
void get_color(char * data, uint16_t len) {
(void) len;
// split at commas and get just the first key
char * token = strtok(data, ",");
if (token != NULL){
struct key * getkey;
getkey = find_key(token);
if (getkey != NULL) {
ws_len=sprintf(ws_buf, "#%02x%02X%02X,%u", getkey->red, getkey->green, getkey->blue, getkey->mode);
ws_send_all(ws_buf, ws_len);
}
}
}
// initialize the ADC for reading the LDR
void startADC() {
stdio_init_all();
adc_init();
adc_gpio_init(LDR_PIN);
adc_select_input(LDR_ADC);
}
// forward HID report after processing
bool forward_report(uint8_t instance, uint8_t const* report, uint16_t len) {
// toggle mute button color if mute button is pressed
if ( instance == 0x02 && report[0] == 0x02 && (report[2] & 0x01) ) {
mute = !mute;
}
return tud_hid_n_report(instance, 0, report, len);
}
// save RGB configuration to flash
void save_rgb_config(void) {
// set save signature and number of bytes to be written into config
uint16_t signature = CFG_SIGNATURE;
uint16_t key_list_size=sizeof(key_list);
uint8_t pages = (key_list_size+sizeof(signature)+sizeof(key_list_size) + FLASH_PAGE_SIZE - 1) / FLASH_PAGE_SIZE;
uint8_t flash_buf[pages*FLASH_PAGE_SIZE];
memset(flash_buf, 0x00, pages*FLASH_PAGE_SIZE);
// stage data for copying to flash
memcpy(flash_buf, &signature, sizeof(signature));
memcpy(flash_buf+sizeof(signature), &key_list_size, sizeof(key_list_size));
memcpy(flash_buf+sizeof(signature)+sizeof(key_list_size), key_list, key_list_size);
// turn off web server and USB interrupts to allow flash writes
uint32_t interrupts = save_and_disable_interrupts();
// host core must have its TinyUSB interrupts disabled to allow flash writes
multicore_lockout_start_blocking();
// erase sector where save will go in flash
flash_range_erase(FLASH_TARGET_OFFSET, FLASH_SECTOR_SIZE);
// write config to flash
flash_range_program(FLASH_TARGET_OFFSET, flash_buf, pages*FLASH_PAGE_SIZE);
// restore interrupts on both core 1 and core 0
multicore_lockout_end_blocking();
restore_interrupts(interrupts);
cdc_count = sprintf(cdc_buf, "Configuration saved to flash (%u:%u)\n", key_list_size, pages);
tud_cdc_write(cdc_buf, cdc_count);
}
// load RGB configuration from flash - return true if valid config, false otherwise
bool load_rgb_config(void) {
uint16_t signature;
uint16_t key_list_size;
const uint8_t *data = (const uint8_t *) (XIP_BASE+FLASH_TARGET_OFFSET);
memcpy(&signature, data, sizeof(signature));
memcpy(&key_list_size, data+sizeof(signature), sizeof(key_list_size));
if (signature == CFG_SIGNATURE && key_list_size == sizeof(key_list) ) {
memcpy(&key_list, data+sizeof(signature)+sizeof(key_list_size), key_list_size);
cdc_count = sprintf(cdc_buf, "Configuration loaded from flash %u (%04x)\n", key_list_size, signature);
tud_cdc_write(cdc_buf, cdc_count);
return true;
}
tud_cdc_write_str("Configuration failed to load\n");
return false;
}
+155
View File
@@ -0,0 +1,155 @@
#ifndef AW410K_H_
#define AW410K_H_
#define LDR_PIN 28
#define LDR_ADC 2
#define AW410K_VID 0x04F2
#define AW410K_PID 0x1968
#define RGB_ITF 1
#define RGB_REPORT_ID 0
#define NUM_KEYS 107
#define BUF_SIZE 64
#define ADC_MAX 4096
enum {
RGG_MODE_INVALID=0,
RGB_MODE_SOLID,
RGB_MODE_ADAPTIVE,
RGB_MODE_MUTE,
};
struct key {
unsigned char name[15];
uint8_t val;
uint8_t red;
uint8_t green;
uint8_t blue;
uint8_t mode;
};
void get_light();
void rgb_task(uint8_t dev_addr);
void startADC();
bool forward_report(uint8_t instance, uint8_t const* report, uint16_t len);
void parse_colors(char * data, uint16_t len);
void get_color(char * data, uint16_t len);
void save_rgb_config(void);
bool load_rgb_config(void);
#define KEY_ESC 0xB0
#define KEY_F1 0x98
#define KEY_F2 0x90
#define KEY_F3 0x88
#define KEY_F4 0x80
#define KEY_F5 0x70
#define KEY_F6 0x68
#define KEY_F7 0x60
#define KEY_F8 0x58
#define KEY_F9 0x50
#define KEY_F10 0x48
#define KEY_F11 0x40
#define KEY_F12 0x38
#define KEY_SYSRQ 0x30 // printscreen
#define KEY_SCROLLLOCK 0x28
#define KEY_PAUSE 0x20
#define KEY_MUTE 0x18
#define KEY_VOLUMEDOWN 0x10
#define KEY_VOLUMEUP 0x08
#define KEY_GRAVE 0xB1 // ` and ~
#define KEY_1 0xA1
#define KEY_2 0x99
#define KEY_3 0x91
#define KEY_4 0x89
#define KEY_5 0x81
#define KEY_6 0x79
#define KEY_7 0x71
#define KEY_8 0x69
#define KEY_9 0x61
#define KEY_0 0x59
#define KEY_MINUS 0x51
#define KEY_EQUAL 0x49
#define KEY_BACKSPACE 0x39
#define KEY_INSERT 0x31
#define KEY_HOME 0x29
#define KEY_PAGEUP 0x21
#define KEY_NUMLOCK 0x19
#define KEY_KPSLASH 0x11
#define KEY_KPASTERISK 0x09
#define KEY_KPMINUS 0x01
#define KEY_TAB 0xB2
#define KEY_Q 0xA2
#define KEY_W 0x9A
#define KEY_E 0x92
#define KEY_R 0x8A
#define KEY_T 0x82
#define KEY_Y 0x7A
#define KEY_U 0x72
#define KEY_I 0x6A
#define KEY_O 0x62
#define KEY_P 0x5A
#define KEY_LEFTBRACE 0x52
#define KEY_RIGHTBRACE 0x4A
#define KEY_BACKSLASH 0x42
#define KEY_DELETE 0x32
#define KEY_END 0x2A
#define KEY_PAGEDOWN 0x22
#define KEY_KP7 0x1A
#define KEY_KP8 0x12
#define KEY_KP9 0x0A
#define KEY_KPPLUS 0x03
#define KEY_CAPSLOCK 0xB3
#define KEY_A 0xA3
#define KEY_S 0x9B
#define KEY_D 0x93
#define KEY_F 0x8B
#define KEY_G 0x83
#define KEY_H 0x7B
#define KEY_J 0x73
#define KEY_K 0x6B
#define KEY_L 0x63
#define KEY_SEMICOLON 0x5B
#define KEY_APOSTROPHE 0x53
#define KEY_ENTER 0x43
#define KEY_KP4 0x1B
#define KEY_KP5 0x13
#define KEY_KP6 0x0B
#define KEY_LEFTSHIFT 0xB4
#define KEY_Z 0xA4
#define KEY_X 0x9C
#define KEY_C 0x94
#define KEY_V 0x8C
#define KEY_B 0x84
#define KEY_N 0x7C
#define KEY_M 0x74
#define KEY_COMMA 0x6C
#define KEY_DOT 0x64
#define KEY_SLASH 0x5C
#define KEY_RIGHTSHIFT 0x4C
#define KEY_UP 0x2C
#define KEY_KP1 0x1C
#define KEY_KP2 0x14
#define KEY_KP3 0x0C
#define KEY_KPENTER 0x05
#define KEY_LEFTCTRL 0xB5
#define KEY_LEFTMETA 0xAD
#define KEY_LEFTALT 0xA5
#define KEY_SPACE 0x85
#define KEY_RIGHTALT 0x65
#define KEY_RIGHTMETA 0x5D // FN
#define KEY_MENU 0x55
#define KEY_RIGHTCTRL 0x4D
#define KEY_LEFT 0x35
#define KEY_DOWN 0x2D
#define KEY_RIGHT 0x25
#define KEY_KP0 0x1D
#define KEY_KPDOT 0x0D
#define INIT_KEY(name, code) {name, code, 0x80, 0x80, 0x80, RGB_MODE_ADAPTIVE}
#define INIT_KEY_MUTE(name, code) {name, code, 0x80, 0x80, 0x80, RGB_MODE_MUTE}
#define CFG_SIGNATURE 0xa22e
#define FLASH_TARGET_OFFSET (PICO_FLASH_SIZE_BYTES - FLASH_BLOCK_SIZE - FLASH_SECTOR_SIZE)
#endif
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

+381
View File
@@ -0,0 +1,381 @@
<!DOCTYPE html>
<html>
<head>
<title>AW410K RGB Configuration</title>
<style>
div.container > div {
display: block;
}
div.output {
width: 40em;
word-break: break-all;
}
div#configuration {
display: inline-block;
text-align: right;
}
div.config {
display: inline-block;
vertical-align: middle;
}
div#keyboard {
display: inline-block;
background-color: #000000;
}
div#keys {
display: inline-block;
}
div.label {
width: 10em;
text-align: center;
text-decoration: underline;
font-weight: bold;
}
div.key {
text-align:center;
vertical-align: top;
display: inline-block;
background-color: #dddddd;
margin: 1px;
width: 2.5em;
height: 3em;
font-size: 0.8em;
border-style: double;
border-color: #dddddd
}
div.selected {
border-style: double;
border-color: blue;
border-width: 2px;
}
div.blank {
opacity: 0;
}
input.byte {
width: 2em;
}
</style>
<script>
var selected = [];
const keyboard_list = [
[
{id: "Escape", label: "ESC", width: 2},
{id: "", label: ""},
{id: "F1", label: "F1"},
{id: "F2", label: "F2"},
{id: "F3", label: "F3"},
{id: "F4", label: "F4"},
{id: "F5", label: "F5"},
{id: "F6", label: "F6"},
{id: "F7", label: "F7"},
{id: "F8", label: "F8"},
{id: "F9", label: "F9"},
{id: "F10", label: "F10"},
{id: "F11", label: "F11"},
{id: "F12", label: "F12"},
{id: "PrintScreen", label: "Print<br>Screen"},
{id: "ScrollLock", label: "Scroll<br>Lock"},
{id: "Pause", label: "Pause"},
{id: "", label: ""},
{id: "Mute", label: "Mute"},
{id: "VolumeDown", label: "Vol<br>Down"},
{id: "VolumeUp", label: "Vol<br>Up"}
],
[
{id: "Backquote", label: "~<br>`"},
{id: "Digit1", label: "!<br>1"},
{id: "Digit2", label: "@<br>2"},
{id: "Digit3", label: "#<br>3"},
{id: "Digit4", label: "$<br>4"},
{id: "Digit5", label: "%<br>5"},
{id: "Digit6", label: "^<br>6"},
{id: "Digit7", label: "&<br>7"},
{id: "Digit8", label: "*<br>8"},
{id: "Digit9", label: "(<br>9"},
{id: "Digit0", label: ")<br>0"},
{id: "Minus", label: "_<br>-"},
{id: "Equal", label: "+<br>="},
{id: "Backspace", label: "Backspace", width: 2},
{id: "Insert", label: "Insert" },
{id: "Home", label: "Home" },
{id: "PageUp", label: "Page<br>Up"},
{id: "NumLock", label: "Num"},
{id: "NumpadDivide", label: "/"},
{id: "NumpadMultiply", label: "*"},
{id: "NumpadSubtract", label: "-"}
],
[
{id: "Tab", label: "Tab", width: 1.5},
{id: "KeyQ", label: "Q"},
{id: "KeyW", label: "W"},
{id: "KeyE", label: "E"},
{id: "KeyR", label: "R"},
{id: "KeyT", label: "T"},
{id: "KeyY", label: "Y"},
{id: "KeyU", label: "U"},
{id: "KeyI", label: "I"},
{id: "KeyO", label: "O"},
{id: "KeyP", label: "P"},
{id: "BracketLeft", label: "{<br>["},
{id: "BracketRight", label: "}<br>]"},
{id: "Backslash", label: "|<br>\\", width: 1.5},
{id: "Delete", label: "Delete"},
{id: "End", label: "End"},
{id: "PageDown", label: "Page<br>Down"},
{id: "Numpad7", label: "Home<br>7"},
{id: "Numpad8", label: "Up<br>8"},
{id: "Numpad9", label: "PgUp<br>9"},
{id: "NumpadAdd", label: "+", height: 2}
],
[
{id: "CapsLock", label: "Caps<br>Lock", width: 2},
{id: "KeyA", label: "A"},
{id: "KeyS", label: "S"},
{id: "KeyD", label: "D"},
{id: "KeyF", label: "F"},
{id: "KeyG", label: "G"},
{id: "KeyH", label: "H"},
{id: "KeyJ", label: "J"},
{id: "KeyK", label: "K"},
{id: "KeyL", label: "L"},
{id: "Semicolon", label: ":<br>;"},
{id: "Quote", label: "\"<br>\'"},
{id: "Enter", label: "Enter", width: 2.3},
{id: "", label: "", width: 3.4},
{id: "Numpad4", label: "Left<br>4"},
{id: "Numpad5", label: "5"},
{id: "Numpad6", label: "Right<br>6"}
],
[
{id: "ShiftLeft", label: "Shift", width: 2.5},
{id: "KeyZ", label: "Z"},
{id: "KeyX", label: "X"},
{id: "KeyC", label: "C"},
{id: "KeyV", label: "V"},
{id: "KeyB", label: "B"},
{id: "KeyN", label: "N"},
{id: "KeyM", label: "M"},
{id: "Comma", label: "\<<br>,"},
{id: "Period", label: "\><br>."},
{id: "Slash", label: "?<br>/"},
{id: "ShiftRight", label: "Shift", width: 3},
{id: "", label: ""},
{id: "ArrowUp", label: "Up"},
{id: "", label: ""},
{id: "Numpad1", label: "End<br>1"},
{id: "Numpad2", label: "Down<br>2"},
{id: "Numpad3", label: "PgDn<br>3"},
{id: "NumpadEnter", label: "Enter", height: 2}
],
[
{id: "ControlLeft", label: "Control", width: 2},
{id: "MetaLeft", label: "Meta"},
{id: "AltLeft", label: "Alt", width: 1.5},
{id: "Space", label: "Space", width: 6.4},
{id: "AltRight", label: "Alt", width: 2},
{id: "MetaRight", label: "FN"},
{id: "ContextMenu", label:"Menu"},
{id: "ControlRight", label: "Control", width: 1.7},
{id: "ArrowLeft", label: "Left"},
{id: "ArrowDown", label: "Down"},
{id: "ArrowRight", label: "Right"},
{id: "Numpad0", label: "Ins<br>0", width: 2},
{id: "NumpadDecimal", label: "Del<br>."}
],
];
// initialize page and websocket connection on load
window.onload = (event) => {
createKeys("keyboard", keyboard_list);
socket = new WebSocket("ws://" + window.location.hostname + ":8080/");
socket.onmessage = function (event) { setColor(event.data); };
}
// macro for sending over websocket and reopening connection if closed
function sendreload(msg, func) {
if (socket.readyState == WebSocket.OPEN) {
socket.send(msg);
} else if (socket.readyState == WebSocket.CLOSED) {
socket = new WebSocket("ws://" + window.location.hostname + ":8080/");
socket.onmessage = function (event) { setColor(event.data); };
setTimeout( func, 10);
} else {
setTimeout( func, 10);
}
}
// toggle selection of pressed key
function pressKey(code) {
if (selected.includes(code)) {
selected.splice(selected.indexOf(code),1);
} else {
selected.push(code);
}
updateKeys(selected);
}
// update GUI with currently selected keys
function updateKeys(selected_keys) {
// update highlighting of selected keys
prev_keys = document.getElementsByClassName("selected");
for (let key of selected_keys) {
keyDiv = document.getElementById(key);
keyDiv.classList.add("selected");
}
for (let key of prev_keys) {
if (!selected_keys.includes(key.id)) {
key.classList.remove("selected");
}
}
// show updated list of selected keys
document.getElementById("keys").innerHTML = selected_keys;
// request color of selected key
getColor(selected_keys);
}
// create keyboard layout from array of keys
function createKeys(div_id, key_list) {
let keyboardDiv = document.getElementById(div_id);
for (let row of key_list) {
let newRow = document.createElement("div");
keyboardDiv.appendChild(newRow);
for (let key of row) {
let newDiv = document.createElement("div");
if (key.id) {
newDiv.id = key.id;
newDiv.innerHTML = key.label;
newDiv.className = "key";
newDiv.addEventListener("click", function () {
pressKey(key.id); });
} else {
newDiv.className = "key blank";
}
newRow.appendChild(newDiv);
if (key.width) {
newDiv.style = "width:" + (key.width*newDiv.clientWidth ) + "px;";
}
if (key.height) {
newDiv.style = "height:" + (key.height*newDiv.clientHeight ) + "px; float: right;";
}
}
}
}
// send new RGB data to host
function sendKeys(keys) {
if (selected.length > 0) {
let color = document.getElementById("rgb").value;
let adapt = document.getElementById("adaptive").checked ? 1:0;
sendreload("S," + color.substr(1,6) + "," + adapt + "," + keys, function () { sendKeys(keys); } );
}
}
// send save request to host
function save() {
sendreload("F,", function (event) { save(); } );
}
// send load request to host
function load() {
sendreload("L,", function (event) { load(); } );
}
// update RGB color of the color selector
function setColor(new_color) {
document.getElementById("rgb").value = new_color.substring(0,7);
let adapt = document.getElementById("adaptive");
if (new_color.substring(8,9) == "1") {
adapt.checked = false;
} else {
adapt.checked = true;
}
updateRGB();
}
// send request to retrieve color of first selected key
function getColor(keys) {
if (selected.length > 0) {
sendreload("G," + keys, function () { getColor(keys); } );
}
}
// update the individual R, G, B values when color is change from the palette
function updateRGB() {
let color = document.getElementById("rgb").value;
document.getElementById("red").value = parseInt(color.substring(1,3), 16);
document.getElementById("green").value = parseInt(color.substring(3,5), 16);
document.getElementById("blue").value = parseInt(color.substring(5,7), 16);
}
// update the color palette when individual R, G, B value is changed
function updateColor() {
// first make sure that individual channel values are between 0-255;
let red = document.getElementById("red");
let green = document.getElementById("green");
let blue = document.getElementById("blue");
for (let channel of [red, green, blue]) {
if (parseInt(channel.value) > 255) {
channel.value = 255;
} else if (parseInt(channel.value) < 0) {
channel.value = 0;
}
}
document.getElementById("rgb").value = "#" + parseInt(red.value).toString(16).padStart(2,"0") +
parseInt(green.value).toString(16).padStart(2,"0") + parseInt(blue.value).toString(16).padStart(2,"0");
}
</script>
</head>
<body>
<div class="container">
<div id="keyboard"></div>
<div id="menu">
<div class="label">LED Settings</div>
<div class="output">Key(s): <div id="keys"></div></div>
<div id="configuration">
<div class="config">
Color: <input type="color" id="rgb" name="rgb" onchange="updateRGB()"><br>
Red: <input type="text" id="red" name="red" class="byte" pattern="[0-9]{1,2}" onchange="updateColor()"><br>
Green: <input type="text" id="green" name="green" class="byte" pattern="[0-9]{1,2}" onchange="updateColor()"><br>
Blue: <input type="text" id="blue" name="blue" class="byte" pattern="[0-9]{1,2}" onchange="updateColor()"><br>
Adaptive: <input type="checkbox" id="adaptive" name="adaptive"><br><br>
<button type="button" onclick="sendKeys(selected)">Set Color</button> <button type="button" onclick="getColor(selected)">Reset</button>
</div>
<div class="config">
<div class="label">Flash memory</div>
<div>
<button type="button" onclick="save()">Save</button>
<button type="button" onclick="load()">Load</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
+68
View File
@@ -0,0 +1,68 @@
#ifndef __LWIPOPTS_H__
#define __LWIPOPTS_H__
#define NO_SYS 1
#define MEM_ALIGNMENT 4
#define LWIP_RAW 0
#define LWIP_NETCONN 0
#define LWIP_SOCKET 0
#define LWIP_DHCP 0
#define LWIP_ICMP 1
#define LWIP_UDP 1
#define LWIP_TCP 1
#define LWIP_IPV4 1
#define LWIP_IPV6 0
#define ETH_PAD_SIZE 0
#define LWIP_IP_ACCEPT_UDP_PORT(p) ((p) == PP_NTOHS(67))
#define TCP_MSS (1500 /*mtu*/ - 20 /*iphdr*/ - 20 /*tcphhr*/)
#define TCP_SND_BUF (4 * TCP_MSS)
#define TCP_WND (4 * TCP_MSS)
#define ETHARP_SUPPORT_STATIC_ENTRIES 1
#define LWIP_SINGLE_NETIF 1
#define LWIP_NETIF_LINK_CALLBACK 1
#define PBUF_POOL_SIZE 4
#define ETHARP_DEBUG LWIP_DBG_OFF
#define NETIF_DEBUG LWIP_DBG_OFF
#define PBUF_DEBUG LWIP_DBG_OFF
#define API_LIB_DEBUG LWIP_DBG_OFF
#define API_MSG_DEBUG LWIP_DBG_OFF
#define SOCKETS_DEBUG LWIP_DBG_OFF
#define ICMP_DEBUG LWIP_DBG_OFF
#define INET_DEBUG LWIP_DBG_OFF
#define IP_DEBUG LWIP_DBG_OFF
#define IP_REASS_DEBUG LWIP_DBG_OFF
#define RAW_DEBUG LWIP_DBG_OFF
#define MEM_DEBUG LWIP_DBG_OFF
#define MEMP_DEBUG LWIP_DBG_OFF
#define SYS_DEBUG LWIP_DBG_OFF
#define TCP_DEBUG LWIP_DBG_OFF
#define TCP_INPUT_DEBUG LWIP_DBG_OFF
#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF
#define TCP_RTO_DEBUG LWIP_DBG_OFF
#define TCP_CWND_DEBUG LWIP_DBG_OFF
#define TCP_WND_DEBUG LWIP_DBG_OFF
#define TCP_FR_DEBUG LWIP_DBG_OFF
#define TCP_QLEN_DEBUG LWIP_DBG_OFF
#define TCP_RST_DEBUG LWIP_DBG_OFF
#define UDP_DEBUG LWIP_DBG_OFF
#define TCPIP_DEBUG LWIP_DBG_OFF
#define PPP_DEBUG LWIP_DBG_OFF
#define SLIP_DEBUG LWIP_DBG_OFF
#define DHCP_DEBUG LWIP_DBG_OFF
// HTTPD stuff
#define LWIP_HTTPD 1
#define LWIP_HTTPD_CGI 0
#define LWIP_HTTPD_SSI 0
#define LWIP_HTTPD_SSI_INCLUDE_TAG 0
#define LWIP_HTTPD_SUPPORT_POST 0
#define HTTPD_FSDATA_FILE "my_fsdata.c"
#endif /* __LWIPOPTS_H__ */
+24
View File
@@ -0,0 +1,24 @@
#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "pico/bootrom.h"
#include "hardware/clocks.h"
#include "usb_device.h"
#include "usb_host.h"
// main loop
int main(void) {
// default 150MHz is not apropriate. Clock should be multiple of 12MHz
set_sys_clock_khz(144000, true);
sleep_ms(10);
// run usb host on core 1
multicore_reset_core1();
multicore_launch_core1(usb_host_main);
// run usb device on core 0
usb_device_main();
return 0;
}
+75
View File
@@ -0,0 +1,75 @@
#ifndef MBEDTLS_CONFIG_H
#define MBEDTLS_CONFIG_H
/* Workaround for some mbedtls source files using INT_MAX without including limits.h */
#include <limits.h>
#define MBEDTLS_NO_PLATFORM_ENTROPY
#define MBEDTLS_ENTROPY_HARDWARE_ALT
#define MBEDTLS_SSL_OUT_CONTENT_LEN 2048
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#define MBEDTLS_HAVE_TIME
#define MBEDTLS_PLATFORM_MS_TIME_ALT
#define MBEDTLS_CIPHER_MODE_CBC
#define MBEDTLS_ECP_DP_SECP192R1_ENABLED
#define MBEDTLS_ECP_DP_SECP224R1_ENABLED
#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
#define MBEDTLS_ECP_DP_SECP384R1_ENABLED
#define MBEDTLS_ECP_DP_SECP521R1_ENABLED
#define MBEDTLS_ECP_DP_SECP192K1_ENABLED
#define MBEDTLS_ECP_DP_SECP224K1_ENABLED
#define MBEDTLS_ECP_DP_SECP256K1_ENABLED
#define MBEDTLS_ECP_DP_BP256R1_ENABLED
#define MBEDTLS_ECP_DP_BP384R1_ENABLED
#define MBEDTLS_ECP_DP_BP512R1_ENABLED
#define MBEDTLS_ECP_DP_CURVE25519_ENABLED
#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
#define MBEDTLS_PKCS1_V15
#define MBEDTLS_SHA256_SMALLER
#define MBEDTLS_SSL_SERVER_NAME_INDICATION
#define MBEDTLS_AES_C
#define MBEDTLS_ASN1_PARSE_C
#define MBEDTLS_BIGNUM_C
#define MBEDTLS_CIPHER_C
#define MBEDTLS_CTR_DRBG_C
#define MBEDTLS_ENTROPY_C
#define MBEDTLS_ERROR_C
#define MBEDTLS_MD_C
#define MBEDTLS_MD5_C
#define MBEDTLS_OID_C
#define MBEDTLS_PKCS5_C
#define MBEDTLS_PK_C
#define MBEDTLS_PK_PARSE_C
#define MBEDTLS_PLATFORM_C
#define MBEDTLS_RSA_C
#define MBEDTLS_SHA1_C
#define MBEDTLS_SHA224_C
#define MBEDTLS_SHA256_C
#define MBEDTLS_SHA512_C
#define MBEDTLS_SSL_CLI_C
#define MBEDTLS_SSL_SRV_C
#define MBEDTLS_SSL_TLS_C
#define MBEDTLS_X509_CRT_PARSE_C
#define MBEDTLS_X509_USE_C
#define MBEDTLS_AES_FEWER_TABLES
/* TLS 1.2 */
#define MBEDTLS_SSL_PROTO_TLS1_2
#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#define MBEDTLS_GCM_C
#define MBEDTLS_ECDH_C
#define MBEDTLS_ECP_C
#define MBEDTLS_ECDSA_C
#define MBEDTLS_ASN1_WRITE_C
// The following is needed to parse a certificate
#define MBEDTLS_PEM_PARSE_C
#define MBEDTLS_BASE64_C
// The following significantly speeds up mbedtls due to NIST optimizations.
#define MBEDTLS_ECP_NIST_OPTIM
#endif
+1071
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
+136
View File
@@ -0,0 +1,136 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* 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.
*
*/
#ifndef _TUSB_CONFIG_H_
#define _TUSB_CONFIG_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------
// COMMON CONFIGURATION
//--------------------------------------------------------------------
#define CFG_TUSB_OS OPT_OS_PICO
// Enable device stack
#define CFG_TUD_ENABLED 1
// Enable host stack with pio-usb if Pico-PIO-USB library is available
#define CFG_TUH_ENABLED 1
#define CFG_TUH_RPI_PIO_USB 1
// CFG_TUSB_DEBUG is defined by compiler in DEBUG build
// #define CFG_TUSB_DEBUG 0
/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment.
* Tinyusb use follows macros to declare transferring memory so that they can be put
* into those specific section.
* e.g
* - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") ))
* - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4)))
*/
#ifndef CFG_TUSB_MEM_SECTION
#define CFG_TUSB_MEM_SECTION
#endif
#ifndef CFG_TUSB_MEM_ALIGN
#define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4)))
#endif
//--------------------------------------------------------------------
// DEVICE CONFIGURATION
//--------------------------------------------------------------------
//------------------------- Board Specific --------------------------
// RHPort number used for device can be defined by board.mk, default to port 0
#ifndef BOARD_TUD_RHPORT
#define BOARD_TUD_RHPORT 0
#endif
// RHPort max operational speed can defined by board.mk
#ifndef BOARD_TUD_MAX_SPEED
#define BOARD_TUD_MAX_SPEED OPT_MODE_DEFAULT_SPEED
#endif
#ifndef CFG_TUD_ENDPOINT0_SIZE
#define CFG_TUD_ENDPOINT0_SIZE 64
#endif
//-----------------------Driver configuration-------------------------
#define CFG_TUD_CDC 1
#define CFG_TUD_HID 4
#define CFG_TUD_NCM 1
// CDC FIFO size of TX and RX
#define CFG_TUD_CDC_RX_BUFSIZE 128
#define CFG_TUD_CDC_TX_BUFSIZE 128
// CDC Endpoint transfer buffer size, more is faster
#define CFG_TUD_CDC_EP_BUFSIZE 64
#define CFG_TUD_HID_EP_BUFSIZE 64
// NCM settings
//#define CFG_TUD_NCM_OUT_MAX_DATAGRAMS_PER_NTB 1
//#define CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB 1
//--------------------------------------------------------------------
// HOST CONFIGURATION
//--------------------------------------------------------------------
//------------------------- Board Specific --------------------------
// RHPort number used for host can be defined by board.mk, default to port 0
#ifndef BOARD_TUH_RHPORT
#define BOARD_TUH_RHPORT 1
#endif
// RHPort max operational speed can defined by board.mk
#ifndef BOARD_TUH_MAX_SPEED
#define BOARD_TUH_MAX_SPEED OPT_MODE_DEFAULT_SPEED
#endif
//-----------------------Driver configuration-------------------------
// Size of buffer to hold descriptors and other data used for enumeration
#define CFG_TUH_ENUMERATION_BUFSIZE 256
#define CFG_TUH_HUB 1
// max device support (excluding hub device)
#define CFG_TUH_DEVICE_MAX (CFG_TUH_HUB ? 4 : 1) // hub typically has 4 ports
#define CFG_TUH_HID 4
#define CFG_TUH_HID_EPIN_BUFSIZE 128
#define CFG_TUH_HID_EPOUT_BUFSIZE 128
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CONFIG_H_ */
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

+259
View File
@@ -0,0 +1,259 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pico/stdlib.h"
#include "bsp/board_api.h"
#include "tusb.h"
#include "aw410k.h"
#include "usb_host.h"
#include "usb_server.h"
#include "usb_device.h"
// reserve space for CDC messages
char cdc_buf[64];
uint16_t cdc_len;
size_t cdc_count;
device_state_t device_state;
// reserve space for HID descriptor
static uint8_t desc_configuration[DESC_CFG_MAX];
static uint16_t _desc_str[32+1];
// device descriptor
static tusb_desc_device_t const desc_device =
{
.bLength = sizeof(tusb_desc_device_t),
.bDescriptorType = TUSB_DESC_DEVICE,
.bcdUSB = USB_BCD,
// Use Interface Association Descriptor (IAD) for CDC
// As required by USB Specs IAD's subclass must be common class (2) and protocol must be IAD (1)
.bDeviceClass = TUSB_CLASS_MISC,
.bDeviceSubClass = MISC_SUBCLASS_COMMON,
.bDeviceProtocol = MISC_PROTOCOL_IAD,
.bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
.idVendor = USB_VID,
.idProduct = USB_PID,
.bcdDevice = 0x0100,
.iManufacturer = 0x01,
.iProduct = 0x02,
.iSerialNumber = 0x03,
.bNumConfigurations = 0x01
};
// string labels for device
static char const* string_desc_arr [] =
{
(const char[]) { 0x09, 0x04 }, // 0: is supported language is English (0x0409)
"Raspberry Pi", // 1: Manufacturer
"Pico AW410K RGB Controller", // 2: Product
NULL, // 3: Serials, should use chip ID
"Pico AW410K CDC", // 4: CDC
"Pico AWK410K NCM", // 5: NCM
NULL, // 6: MAC address for NCM
"Pico AW410K HID", // 7: HID
};
static void usb_device_init(void);
// main task for USB device
void usb_device_main(void) {
// start ADC for reading LDR
startADC();
// initialize the TinyUSB device
device_state = DEVICE_INACTIVE;
usb_device_init();
usb_server_init();
while (true) {
switch ( device_state ) {
case DEVICE_ACTIVE:
break;
case DEVICE_INACTIVE:
break;
case DEVICE_RESTART:
if (tud_disconnect()) {
sleep_ms(10);
if (tud_connect()) {
if ( host_state == HOST_INACTIVE ) {
device_state = DEVICE_INACTIVE;
} else {
device_state = DEVICE_ACTIVE;
}
}
}
break;
default:
break;
}
get_light(); // get the ADC LDR reading
tud_task();
tud_cdc_write_flush();
}
}
// initialize the TinyUSB device
static void usb_device_init(void) {
// run TinyUSB device
tusb_rhport_init_t dev_init = {
.role = TUSB_ROLE_DEVICE,
.speed = TUSB_SPEED_AUTO,
};
tusb_init(BOARD_TUH_RHPORT, &dev_init);
}
// Invoked when received GET DEVICE DESCRIPTOR
// Application return pointer to descriptor
uint8_t const * tud_descriptor_device_cb(void)
{
return (uint8_t const *) &desc_device;
}
// Invoked when received GET CONFIGURATION DESCRIPTOR
// Application return pointer to descriptor
// Descriptor contents must exist long enough for transfer to complete
uint8_t const * tud_descriptor_configuration_cb(uint8_t index)
{
(void) index; // for multiple configurations
// set configuration descriptor and CDC descriptor
memset(desc_configuration, 0, sizeof(desc_configuration));
uint8_t desc_initial[TUD_CONFIG_DESC_LEN+TUD_CDC_DESC_LEN+TUD_CDC_NCM_DESC_LEN+1] = {
TUD_CONFIG_DESCRIPTOR(1, 4+num_mounted, 0, TUD_CONFIG_DESC_LEN+TUD_CDC_DESC_LEN+TUD_CDC_NCM_DESC_LEN+num_mounted*TUD_HID_DESC_LEN, 0x00, 100),
TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 8, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64),
TUD_CDC_NCM_DESCRIPTOR(ITF_NUM_NCM, 5, 6, EPNUM_NCM_NOTIF, 64, EPNUM_NCM_OUT, EPNUM_NCM_IN, CFG_TUD_NET_ENDPOINT_SIZE, CFG_TUD_NET_MTU)
};
memcpy(desc_configuration, desc_initial, TUD_CONFIG_DESC_LEN+TUD_CDC_DESC_LEN+TUD_CDC_NCM_DESC_LEN);
// add a HID descriptor for each interface mounted on host
if ( descriptors != NULL) {
struct report_desc *descriptor;
for (uint8_t i=0; i<num_mounted; i++) {
descriptor = report_desc_find(descriptors->dev_addr, i);
uint8_t hid_desc[TUD_HID_DESC_LEN+1] = {
TUD_HID_DESCRIPTOR(ITF_NUM_HID+i, 7, HID_ITF_PROTOCOL_NONE, descriptor->desc_len, EPNUM_HID+i, CFG_TUD_HID_EP_BUFSIZE, 1)
};
memcpy(&desc_configuration[TUD_CONFIG_DESC_LEN+TUD_CDC_DESC_LEN+TUD_CDC_NCM_DESC_LEN+i*TUD_HID_DESC_LEN], hid_desc, TUD_HID_DESC_LEN);
}
}
return desc_configuration;
}
// Invoked when received GET STRING DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid)
{
(void) langid;
uint8_t chr_count;
switch (index) {
case 0: // langid
memcpy(&_desc_str[1], string_desc_arr[0], 2);
chr_count = 1;
break;
case 3: // serial
chr_count = board_usb_get_serial(_desc_str+1, 32);
break;
case 6: // MAC address: link-local prefix of 02 and last 10 digits from board serial
chr_count = board_usb_get_serial(_desc_str+1, 32);
if (chr_count > 12) {
_desc_str[1] = '0';
_desc_str[2] = '2';
for (uint8_t i=0; i<10; i++) {
_desc_str[3+i] = _desc_str[chr_count-9+i];
}
chr_count=12;
}
break;
default:
// Note: the 0xEE index string is a Microsoft OS 1.0 Descriptors.
// https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors
if ( !(index < sizeof(string_desc_arr)/sizeof(string_desc_arr[0])) ) return NULL;
char* str = string_desc_arr[index];
// Cap at max char
chr_count = (uint8_t) strlen(str);
if ( chr_count > 31 ) chr_count = 31;
// Convert ASCII string into UTF-16
for(uint8_t i=0; i<chr_count; i++) {
_desc_str[1+i] = str[i];
}
break;
}
// first byte is length (including header), second byte is string type
_desc_str[0] = (TUSB_DESC_STRING << 8 ) | (2*chr_count + 2);
return _desc_str;
}
// Invoked when received GET HID REPORT DESCRIPTOR
// Application return pointer to descriptor
// Descriptor contents must exist long enough for transfer to complete
uint8_t const * tud_hid_descriptor_report_cb(uint8_t itf)
{
// find HID report descriptor for indicated interface on the host and forward to device
if ( descriptors != NULL) {
struct report_desc * descriptor = report_desc_find(descriptors->dev_addr, itf);
if ( descriptor != NULL ) {
return descriptor->descriptor;
}
}
return NULL;
}
// Invoked when received SET_REPORT control request or
// received data on OUT endpoint ( Report ID = 0, Type = 0 )
void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) {
// forward to device connected to host
if (descriptors != NULL) {
tuh_hid_set_report(descriptors->dev_addr, instance, report_id, report_type, buffer, bufsize);
}
}
// Invoked when received GET_REPORT control request
// Application must fill buffer report's content and return its length.
// Return zero will cause the stack to STALL request
uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen)
{
(void) instance;
(void) report_id;
(void) report_type;
(void) buffer;
(void) reqlen;
return 0;
}
// print message to CDC in raw hex
void cdc_print_hex(uint8_t const* msg, uint16_t msg_len) {
(void) msg;
(void) msg_len;
for (int i=0; i<msg_len; i++) {
cdc_count=sprintf(cdc_buf, "%02X ", msg[i]);
tud_cdc_write(cdc_buf, cdc_count);
}
tud_cdc_write_str("\n");
}
// print message to CDC
void cdc_print(uint8_t const* msg, uint16_t msg_len) {
tud_cdc_write(msg, msg_len);
}
+43
View File
@@ -0,0 +1,43 @@
#ifndef USB_DEVICE_H_
#define USB_DEVICE_H_
#define DESC_CFG_MAX TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN + TUD_CDC_NCM_DESC_LEN + CFG_TUD_HID*TUD_HID_DESC_LEN
#define USB_PID 0xA410
#define USB_VID 0xCEC0
#define USB_BCD 0x0200
#define EPNUM_CDC_NOTIF 0x81
#define EPNUM_CDC_OUT 0x02
#define EPNUM_CDC_IN 0x82
#define EPNUM_NCM_NOTIF 0x83
#define EPNUM_NCM_OUT 0x03
#define EPNUM_NCM_IN 0x84
#define EPNUM_HID 0x85
enum
{
ITF_NUM_CDC=0,
ITF_NUM_CDC_DATA,
ITF_NUM_NCM,
ITF_NUM_NCM_DATA,
ITF_NUM_HID
};
typedef enum {
DEVICE_INACTIVE=0,
DEVICE_ACTIVE,
DEVICE_RESTART,
} device_state_t;
extern char cdc_buf[64];
extern uint16_t cdc_len;
extern size_t cdc_count;
extern device_state_t device_state;
void usb_device_main(void);
void cdc_print_hex(uint8_t const* msg, uint16_t msg_len);
void cdc_print(uint8_t const* msg, uint16_t msg_len);
#endif
+309
View File
@@ -0,0 +1,309 @@
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "pico/stdlib.h"
#include "pico/multicore.h"
#include "pio_usb.h"
#include "tusb.h"
#include "aw410k.h"
#include "usb_device.h"
#include "usb_host.h"
host_state_t host_state;
struct report_desc *descriptors;
uint8_t num_mounted=0;
static absolute_time_t request_time;
static bool enabled=false;
static uint8_t kb_addr=0;
static void usb_host_init(void);
static void host_ready(void);
static bool request_hid_report(uint8_t dev_addr, uint8_t instance);
static bool stop_hid_report(uint8_t dev_addr, uint8_t instance);
static bool request_hid_reports_all(void);
static bool stop_hid_reports_all(void);
static struct report_desc* report_desc_alloc(void);
static void report_desc_init(struct report_desc *descriptor);
static void report_desc_free(struct report_desc *descriptor);
static bool add_descriptor(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len);
static void remove_instance(uint8_t dev_addr, uint8_t instance);
// initialize usb host
static void usb_host_init(void) {
// configure PIO USB for TinyUSB host
pio_usb_configuration_t pio_cfg = PIO_USB_DEFAULT_CONFIG;
pio_cfg.alarm_pool = (void*) alarm_pool_create(2,1);
tuh_configure(1, TUH_CFGID_RPI_PIO_USB_CONFIGURATION, &pio_cfg);
// run TinyUSB host
tusb_rhport_init_t host_init = {
.role = TUSB_ROLE_HOST,
.speed = TUSB_SPEED_AUTO,
};
tuh_hid_set_default_protocol(HID_PROTOCOL_REPORT);
tusb_init(BOARD_TUH_RHPORT, &host_init);
host_state=HOST_INACTIVE;
}
void usb_host_main(void) {
// allow other core to pause host process - required for saving to flash
multicore_lockout_victim_init();
usb_host_init();
if (load_rgb_config()) {
tud_cdc_write_str("found previous RGB configuration\n");
}
while (true) {
switch ( host_state ) {
case HOST_MOUNTED:
device_state = DEVICE_RESTART;
host_ready();
break;
case HOST_UNMOUNTED:
host_state = HOST_MOUNTED;
break;
case HOST_START_LISTEN:
request_hid_reports_all();
break;
case HOST_STOP_LISTEN:
stop_hid_reports_all();
break;
case HOST_LISTENING:
if (enabled) {
rgb_task(kb_addr);
}
break;
default:
break;
}
tuh_task();
}
}
// Invoked when device with hid interface is mounted
void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len)
{
uint16_t vid, pid;
tuh_vid_pid_get(dev_addr, &vid, &pid);
uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance);
/// send device vid:pid information to CDC for debugging
cdc_count = sprintf(cdc_buf, "Mount: [%04x:%04x][%u:%u] Protocol = %u\n", vid, pid, dev_addr, instance, itf_protocol);
tud_cdc_write(cdc_buf, cdc_count);
// enable RGB control if AW410K is mounted
if (vid == AW410K_VID && pid == AW410K_PID) {
kb_addr = dev_addr;
enabled = true;
}
// add to HID report descriptor
if ( add_descriptor(dev_addr, instance, desc_report, desc_len)) {
num_mounted++;
host_state=HOST_MOUNTED;
request_time=get_absolute_time();
}
}
// Invoked when device with hid interface is un-mounted
void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance)
{
// send device address:instance to CDC for debugging
cdc_count = sprintf(cdc_buf, "Unmount: [%u:%u]\n", dev_addr, instance);
tud_cdc_write(cdc_buf, cdc_count);
if (stop_hid_report(dev_addr, instance)) {
tud_cdc_write_str("Successfully stopped receiving reports\n");
}
// remove record of interface and disable RGB control if AW410K is unmounted
remove_instance(dev_addr, instance);
if (dev_addr == kb_addr) {
enabled = false;
kb_addr=0;
}
num_mounted--;
host_state=HOST_UNMOUNTED;
request_time=get_absolute_time();
}
// Invoked when received report from device via interrupt endpoint
void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len)
{
if (len > 0 ) {
cdc_count = sprintf(cdc_buf, "[%u:%u](%u) ", dev_addr, instance, len);
tud_cdc_write(cdc_buf,cdc_count);
cdc_print_hex(report, len);
}
forward_report(instance, report, len);
// continue to request to receive report
if ( !tuh_hid_receive_report(dev_addr, instance) )
{
tud_cdc_write_str("Error: cannot request report\r\n");
}
}
// start listening on host for HID events
static void host_ready(void) {
if (absolute_time_diff_us(request_time, get_absolute_time()) >= 500000){
if( descriptors != NULL ) {
host_state = HOST_START_LISTEN;
} else {
host_state = HOST_INACTIVE;
}
}
}
// request HID input reports on specified device address and instance
static bool request_hid_report(uint8_t dev_addr, uint8_t instance) {
// request to receive reports HID devices
if ( !tuh_hid_receive_report(dev_addr, instance) ) {
cdc_count = sprintf(cdc_buf, "Error: cannot request report on [%u:%u]\n", dev_addr, instance);
tud_cdc_write(cdc_buf, cdc_count);
return false;
}
return true;
}
// stop receiving HID input reports on specified device address and instance
static bool stop_hid_report(uint8_t dev_addr, uint8_t instance) {
if (!tuh_hid_receive_abort(dev_addr, instance)) {
tud_cdc_write_str("Error: could not stop receiving reports\n");
return false;
}
return true;
}
// start listening to HID input reports on all mounted devices
static bool request_hid_reports_all(void) {
// send request to receive reports on all mounted devices
struct report_desc * current;
for (current=descriptors; current != NULL; current=current->next) {
if (! current->listening) {
if(request_hid_report(current->dev_addr, current->instance)) {
cdc_count = sprintf(cdc_buf, "Listening to input reports on [%u:%u]\n", current->dev_addr, current->instance);
tud_cdc_write(cdc_buf, cdc_count);
current->listening = true;
} else {
tud_cdc_write_str("Error listening to input report(s)\n");
stop_hid_reports_all();
return false;
}
}
}
host_state = HOST_LISTENING;
return true;
}
// stop listening to HID input reports on all mounted devices
static bool stop_hid_reports_all(void) {
// send request to stop reports on all mounted devices
struct report_desc * current;
for (current=descriptors; current != NULL; current=current->next) {
if (current->listening) {
if(stop_hid_report(current->dev_addr, current->instance)) {
cdc_count = sprintf(cdc_buf, "Stopping input reports on [%u:%u]\n", current->dev_addr, current->instance);
tud_cdc_write(cdc_buf, cdc_count);
current->listening = false;
} else {
tud_cdc_write_str("Error stopping input report(s)\n");
return false;
}
}
}
host_state = HOST_INACTIVE;
return true;
}
// allocate memory for USB interface report descriptor
static struct report_desc * report_desc_alloc(void) {
struct report_desc *ret = REPORT_DESC_ALLOC();
if (ret != NULL) {
report_desc_init(ret);
if (descriptors == NULL) {
descriptors = ret;
} else {
struct report_desc *last;
for (last = descriptors; last->next != NULL; last=last->next);
last->next = ret;
}
}
return ret;
}
// initialize report descriptor struct
static void report_desc_init(struct report_desc *descriptor) {
memset(descriptor, 0, sizeof(struct report_desc));
descriptor->next = NULL;
}
// free memory and teardown usb->bt report ID mappings for report descriptor struct
static void report_desc_free(struct report_desc *descriptor) {
if (descriptor != NULL) {
if (descriptors == descriptor) {
descriptors = descriptor->next;
} else {
struct report_desc *last;
for (last = descriptors; last->next != NULL; last = last->next) {
if ((last->next) == descriptor) {
last->next = descriptor->next;
break;
}
}
}
free(descriptor);
}
}
// add report descriptor for new HID interface
static bool add_descriptor(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) {
struct report_desc * descriptor = report_desc_alloc();
if (descriptor == NULL) {
return false;
}
memcpy(descriptor->descriptor, desc_report, desc_len);
descriptor->desc_len = desc_len;
descriptor->dev_addr = dev_addr;
descriptor->instance = instance;
descriptor->listening = false;
return true;
}
// remove report descriptor for HID interface
static void remove_instance(uint8_t dev_addr, uint8_t instance) {
struct report_desc *descriptor = report_desc_find(dev_addr, instance);
if (descriptor != NULL) {
report_desc_free(descriptor);
}
}
// find report descriptor by device address and instance
struct report_desc * report_desc_find(uint8_t dev_addr, uint8_t instance) {
struct report_desc *descriptor;
for (descriptor = descriptors; descriptor != NULL; descriptor = descriptor->next) {
if (descriptor->dev_addr==dev_addr && descriptor->instance==instance) {
break;
}
}
return descriptor;
}
+36
View File
@@ -0,0 +1,36 @@
#ifndef USB_HOST_H_
#define USB_HOST_H_
#define REPORT_MAX_SIZE 64
#define REPORT_BUF_SIZE 256
#define DESCRIPTOR_MAX_SIZE 256
typedef enum {
HOST_INACTIVE=0,
HOST_MOUNTED,
HOST_UNMOUNTED,
HOST_START_LISTEN,
HOST_LISTENING,
HOST_STOP_LISTEN,
} host_state_t;
struct report_desc {
uint8_t dev_addr;
uint8_t instance;
uint8_t descriptor[DESCRIPTOR_MAX_SIZE];
uint16_t desc_len;
struct report_desc *next;
bool listening;
};
#define REPORT_DESC_ALLOC() (struct report_desc *)malloc(sizeof(struct report_desc))
extern host_state_t host_state;
extern struct report_desc *descriptors;
extern uint8_t num_mounted;
void usb_host_main(void);
struct report_desc * report_desc_find(uint8_t dev_addr, uint8_t instance);
#endif
+234
View File
@@ -0,0 +1,234 @@
#include "bsp/board_api.h"
#include "tusb.h"
#include "dhserver.h"
#include "dnserver.h"
#include "lwip/apps/httpd.h"
#include "lwip/init.h"
#include "lwip/timeouts.h"
#include "websocket.h"
#include "usb_device.h"
#include "aw410k.h"
#include "usb_server.h"
// ip address of the USB server and dhcp address(es) it will give out
static const ip4_addr_t usb_ip = INIT_IP4(192, 168, 40, 1);
static const ip4_addr_t usb_netmask = INIT_IP4(255, 255, 255, 0);
static const ip4_addr_t usb_gateway = INIT_IP4(0, 0, 0, 0);
static dhcp_entry_t dhcp_clients[] = {
{ {0}, INIT_IP4(192, 168, 40, 2), 4*3600 },
};
static const dhcp_config_t dhcp_config = {
.router = INIT_IP4(0,0,0,0),
.port = 67,
.dns = usb_ip,
"usb",
TU_ARRAY_SIZE(dhcp_clients),
dhcp_clients
};
static struct netif netif_data;
static err_t netif_init_cb(struct netif *netif);
static err_t ip4_output_fn(struct netif *netif, struct pbuf *p, const ip4_addr_t *addr);
static err_t linkoutput_fn(struct netif *netif, struct pbuf *p);
static void usb_server_netif_link_cb(struct netif *netif);
static bool dns_request(const char *name, ip4_addr_t *addr);
// called to initialize the USB network and HTTP server
void usb_server_init(void) {
struct netif *netif = &netif_data;
lwip_init();
// use 02 followed by last 10 digits from board serial as MAC address
uint8_t board_serial[16];
size_t count = board_get_unique_id(board_serial, sizeof(board_serial));
netif->hwaddr_len = 6;
memcpy(netif->hwaddr, &board_serial[count-6], 6);
netif->hwaddr[0]=0x02;
// lwip virtual MAC address msut differ from the host MAC - toggle last bit
netif->hwaddr[5] ^= 0x01;
netif = netif_add(netif, &usb_ip, &usb_netmask, &usb_gateway, NULL, netif_init_cb, ethernet_input);
netif_set_default(netif);
#if LWIP_NETIF_LINK_CALLBACK
netif_set_link_callback(netif, usb_server_netif_link_cb);
netif_set_link_up(netif);
#else
//tud_network_link_state(BOARD_TUD_RHPORT, true);
// unsupported in current version - add when Pico SDK updates TinyUSB version
#endif
while (!netif_is_up(&netif_data));
while (dhserv_init(&dhcp_config) != ERR_OK);
while (dnserv_init(IP_ADDR_ANY, 53, dns_request) != ERR_OK);
httpd_init();
// start the websocket server
ws_server_init();
ws_set_open_handler(ws_open_handler);
ws_set_receive_handler(ws_receive_handler);
}
// callback when data is received on USB network
// return true if the packet buffer was accepted
bool tud_network_recv_cb(const uint8_t *src, uint16_t size) {
struct netif *netif = &netif_data;
if (size) {
struct pbuf *p = pbuf_alloc(PBUF_RAW, size, PBUF_POOL);
if (p == NULL) {
printf("ERROR: Failed to allocate pbuf of size %d\n", size);
return false;
}
/* Copy buf to pbuf */
pbuf_take(p, src, size);
// Surrender ownership of our pbuf unless there was an error
// Only call pbuf_free if not Ok else it will panic with "pbuf_free: p->ref > 0"
// or steal it from whatever took ownership of it with undefined consequences.
// See: https://savannah.nongnu.org/patch/index.php?10121
if (netif->input(p, netif) != ERR_OK) {
printf("ERROR: netif input failed\n");
pbuf_free(p);
}
// Signal tinyusb that the current frame has been processed.
tud_network_recv_renew();
}
return true;
}
// callback when network interface is initialized
// save the network configuration
static err_t netif_init_cb(struct netif *netif) {
LWIP_ASSERT("netif != NULL", (netif != NULL));
netif->mtu = CFG_TUD_NET_MTU;
netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP | NETIF_FLAG_UP;
netif->state = NULL;
netif->name[0] = 'E';
netif->name[1] = 'X';
netif->linkoutput = linkoutput_fn;
netif->output = ip4_output_fn;
return ERR_OK;
}
// callback for sending data over USB network interface
// copy from network stack packet pointer to dst
uint16_t tud_network_xmit_cb(uint8_t *dst, void *ref, uint16_t arg) {
struct pbuf *p = (struct pbuf *) ref;
(void) arg; /* unused for this example */
return pbuf_copy_partial(p, dst, p->tot_len, 0);
}
static err_t ip4_output_fn(struct netif *netif, struct pbuf *p, const ip4_addr_t *addr) {
return etharp_output(netif, p, addr);
}
static err_t linkoutput_fn(struct netif *netif, struct pbuf *p) {
(void) netif;
for (;;) {
// if TinyUSB isn't ready, we must signal back to lwip that there is nothing we can do
if (!tud_ready())
return ERR_USE;
// if the network driver can accept another packet, we make it happen
if (tud_network_can_xmit(p->tot_len)) {
tud_network_xmit(p, 0 /* unused for this example */);
return ERR_OK;
}
// transfer execution to TinyUSB in the hopes that it will finish transmitting the prior packet
tud_task();
}
}
// notify USB host about link state changes
static void usb_server_netif_link_cb(struct netif *netif) {
bool link_up = netif_is_link_up(netif);
//tud_network_link_state(BOARD_TUD_RHPORT, link_up);
// unsupported in current version - add when Pico SDK updates TinyUSB version
}
// handle DNS requests and serve on designed domain
static bool dns_request(const char *name, ip4_addr_t *addr) {
if (0 == strcmp(name, "aw410k.usb")) {
*addr = usb_ip;
return true;
}
return false;
}
// handler called when websocket connection is opened
const void ws_open_handler(struct ws_state * wss) {
(void) wss;
// nothing to do
}
// handler for data received on websocket connection
const void ws_receive_handler(uint8_t *data, uint16_t len) {
if (strncmp(data, "S,", 2) == 0) {
// set color command
parse_colors(&data[2], len-2);
} else if ( strncmp(data, "G,", 2) == 0) {
// get color comand
get_color(&data[2], len-2);
} else if ( strncmp(data, "F,", 2) == 0) {
// save to flash memory
save_rgb_config();
} else if ( strncmp(data, "L,", 2) == 0) {
// load from flash memory
load_rgb_config();
}
}
// Pico specific routines needed by lwip
auto_init_mutex(lwip_mutex);
static int lwip_mutex_count = 0;
sys_prot_t sys_arch_protect(void)
{
uint32_t owner;
if (!mutex_try_enter(&lwip_mutex, &owner))
{
if (owner != get_core_num())
{
// Wait until other core releases mutex
mutex_enter_blocking(&lwip_mutex);
}
}
lwip_mutex_count++;
return 0;
}
void sys_arch_unprotect(sys_prot_t pval)
{
(void)pval;
if (lwip_mutex_count)
{
lwip_mutex_count--;
if (!lwip_mutex_count)
{
mutex_exit(&lwip_mutex);
}
}
}
uint32_t sys_now(void)
{
return to_ms_since_boot( get_absolute_time() );
}
+12
View File
@@ -0,0 +1,12 @@
#ifndef USB_SERVER_H_
#define USB_SERVER_H_
#define INIT_IP4(a, b, c, d) \
{ PP_HTONL(LWIP_MAKEU32(a, b, c, d)) }
void usb_server_init(void);
const void ws_receive_handler(uint8_t *data, uint16_t len);
const void ws_open_handler(struct ws_state * wss);
#endif
+470
View File
@@ -0,0 +1,470 @@
#include <string.h>
#include "lwip/altcp.h"
#include "lwip/debug.h"
#include "mbedtls/base64.h"
#include "mbedtls/sha1.h"
#include "websocket.h"
static const char WS_GUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static const char WS_RESPONSE[] = "HTTP/1.1 101 Switching Protocols\r\n" \
"Upgrade: websocket\r\n" \
"Connection: Upgrade\r\n" \
"Sec-WebSocket-Accept: ";
static uint8_t buf[WS_BUFFER_SIZE];
static uint16_t buf_len=0;
static tWSHandler ws_receive_cb = NULL;
static tWSOpenHandler ws_open_cb = NULL;
static struct ws_state * ws_connections;
static uint8_t ws_num_conns = 0;
static struct ws_state* ws_state_alloc(void);
static void ws_state_init(struct ws_state *wss);
static void ws_state_free(struct ws_state *wss);
static void ws_server_init_pcb( struct altcp_pcb *pcb, uint16_t port);
static err_t ws_accept(void *arg, struct altcp_pcb *pcb, err_t err);
static err_t ws_recv(void *arg, struct altcp_pcb *pcb, struct pbuf *p, err_t err);
static err_t ws_sent(void *arg, struct altcp_pcb *pcb, uint16_t len);
static void ws_err (void *arg, err_t err);
static err_t ws_close_conn(struct altcp_pcb *pcb, struct ws_state *wss);
static err_t ws_close_or_abort_conn(struct altcp_pcb *pcb, struct ws_state *wss, uint8_t abort_conn);
static err_t ws_poll(void *arg, struct altcp_pcb *pcb);
static err_t ws_handshake(struct altcp_pcb *pcb, struct ws_state *wss, struct pbuf *p);
static err_t ws_read(struct altcp_pcb *pcb, struct ws_state *wss, struct pbuf *p);
static err_t ws_send(struct ws_state *wss, uint8_t *data, uint16_t len);
// allocate memory for ws_state instance
static struct ws_state * ws_state_alloc(void) {
struct ws_state *ret = WS_ALLOC_WS_STATE();
if ( ret != NULL) {
ws_state_init(ret);
if (ws_connections == NULL) {
ws_connections = ret;
} else {
struct ws_state *last;
for (last=ws_connections; last->next != NULL; last=last->next);
LWIP_ASSERT("last != NULL", last != NULL);
last->next = ret;
}
}
return ret;
}
// initiate ws_state instance
static void ws_state_init(struct ws_state *wss) {
memset(wss, 0, sizeof(struct ws_state));
wss->active = false;
}
// free memory from ws_state instance
static void ws_state_free(struct ws_state *wss) {
if (wss != NULL) {
if (ws_connections == wss) {
ws_connections = wss->next;
} else {
struct ws_state * last;
for (last = ws_connections; last->next != NULL; last = last->next) {
if (last->next == wss) {
last->next = wss->next;
break;
}
}
}
mem_free(wss);
}
}
// initiate websocket server on specified pcb
static void ws_server_init_pcb( struct altcp_pcb *pcb, uint16_t port) {
err_t err;
if (pcb) {
altcp_setprio(pcb, TCP_PRIO_MIN);
err = altcp_bind(pcb, IP_ANY_TYPE, port);
LWIP_UNUSED_ARG(err);
LWIP_ASSERT("ws_server_init: tcp_bind failed", err == ERR_OK);
pcb = altcp_listen(pcb);
LWIP_ASSERT("ws_server_init: tcp_listen failed", pcb != NULL);
altcp_accept(pcb, ws_accept);
}
}
// initiate a websocket server
void ws_server_init(void) {
struct altcp_pcb *pcb = altcp_tcp_new_ip_type(IPADDR_TYPE_ANY);
LWIP_ASSERT("ws_server_init: tcp_new failed", pcb != NULL);
ws_server_init_pcb(pcb, WS_PORT);
}
// set ws_receive_handler
void ws_set_receive_handler( tWSHandler ws_handler)
{
ws_receive_cb = ws_handler;
}
// set ws_open_handler
void ws_set_open_handler( tWSOpenHandler ws_handler)
{
ws_open_cb = ws_handler;
}
// callback for accepted websocket connection
static err_t ws_accept(void *arg, struct altcp_pcb *pcb, err_t err) {
struct ws_state *wss;
LWIP_UNUSED_ARG(err);
LWIP_UNUSED_ARG(arg);
LWIP_DEBUGF(WS_DEBUG, ("ws_accept %p / %p\n", (void *)pcb, arg));
if ((err != ERR_OK) || (pcb == NULL)) {
return ERR_VAL;
}
// create new ws_state object
wss = ws_state_alloc();
if (wss == NULL) {
LWIP_DEBUGF(WS_DEBUG, ("ws_accept: Out of memory, RST\n"));
return ERR_MEM;
}
wss->pcb = pcb;
// make ws_state object the argument of callbacks
altcp_arg(pcb, wss);
// register callbacks for tcp events
altcp_recv(pcb, ws_recv);
altcp_sent(pcb, ws_sent);
altcp_poll(pcb, ws_poll, WS_POLL_INTERVAL);
altcp_err(pcb, ws_err);
return ERR_OK;
}
// call when data is received
static err_t ws_recv(void *arg, struct altcp_pcb *pcb, struct pbuf *p, err_t err) {
struct ws_state *wss = (struct ws_state *) arg;
if ((err != ERR_OK) || (p == NULL) || (wss == NULL)) {
// error or closed by client
if (p != NULL) {
// inform TCP that we have taken the data
altcp_recved(pcb, p->tot_len);
pbuf_free(p);
}
if (wss == NULL) {
// should not occur
LWIP_DEBUGF(WS_DEBUG, ("Error, ws_recv: wss is NULL, close\n"));
}
ws_close_conn(pcb, wss);
return ERR_OK;
}
if (wss->active) {
// process websocket message
err = ws_read(pcb, wss, p);
} else {
// init websocket connection
LWIP_DEBUGF(WS_DEBUG, ("ws_recv: websocket inactive, checking for handshake\n"));
err = ws_handshake(pcb, wss, p);
}
// inform TCP that we have taken the data.
altcp_recved(pcb, p->tot_len);
pbuf_free(p);
if (err == ERR_CLSD) {
ws_close_conn(pcb, wss);
}
return ERR_OK;
}
// called when data has been sent over the websocket
static err_t ws_sent(void *arg, struct altcp_pcb *pcb, uint16_t len) {
(void) pcb;
struct ws_state *wss = (struct ws_state *)arg;
LWIP_DEBUGF(WS_DEBUG | LWIP_DBG_TRACE, ("ws_sent %p\n", (void*) pcb));
LWIP_UNUSED_ARG(len);
if (wss == NULL) {
return ERR_OK;
}
wss->retries = 0;
return ERR_OK;
}
// called when there is a websocket error
static void ws_err (void *arg, err_t err) {
struct ws_state *wss = (struct ws_state *) arg;
LWIP_UNUSED_ARG(err);
LWIP_DEBUGF(WS_DEBUG, ("ws_err: %s", lwip_strerr(err)));
if (wss != NULL) {
ws_state_free(wss);
}
}
// initiate close of connection
static err_t ws_close_conn(struct altcp_pcb *pcb, struct ws_state *wss) {
return ws_close_or_abort_conn(pcb, wss, 0);
}
// call when closing connection or connection was aborted
static err_t ws_close_or_abort_conn(struct altcp_pcb *pcb, struct ws_state *wss,
uint8_t abort_conn) {
err_t err;
LWIP_DEBUGF(WS_DEBUG, ("Closing connection %p\n", (void *)pcb));
// clear callbacks
altcp_arg(pcb, NULL);
altcp_recv(pcb, NULL);
altcp_sent(pcb, NULL);
altcp_poll(pcb, NULL, 0);
altcp_err(pcb, NULL);
// remove and free memory from ws_state object
if (wss != NULL) {
ws_state_free(wss);
}
if (abort_conn) {
altcp_abort(pcb);
return ERR_OK;
}
err = altcp_close(pcb);
if (err != ERR_OK) {
LWIP_DEBUGF(WS_DEBUG, ("Error %d closing %p\n", err, (void *)pcb));
// error closing, try again later in poll
altcp_poll(pcb, ws_poll, WS_POLL_INTERVAL);
}
return err;
}
// callback for polling process
static err_t ws_poll(void *arg, struct altcp_pcb *pcb) {
struct ws_state *wss = (struct ws_state *) arg;
if (wss == NULL) {
err_t closed;
LWIP_DEBUGF(WS_DEBUG, ("ws_poll: arg is NULL, close\n"));
closed = ws_close_conn(pcb, NULL);
LWIP_UNUSED_ARG(closed);
if (closed == ERR_MEM) {
altcp_abort(pcb);
return ERR_ABRT;
}
return ERR_OK;
} else {
wss->retries++;
if (wss->retries == WS_MAX_RETRIES) {
LWIP_DEBUGF(WS_DEBUG, ("ws_poll: too may retries, close\n"));
ws_close_conn(pcb, wss);
return ERR_OK;
}
}
return ERR_OK;
}
// check for and complete handshake with client
static err_t ws_handshake(struct altcp_pcb *pcb, struct ws_state *wss, struct pbuf *p){
uint8_t *data = (uint8_t *) p->payload;
uint16_t len = p->len;
// check if client is initiating a websocket connecttion
if (strstr(data, "Upgrade: websocket")) {
LWIP_DEBUGF(WS_DEBUG, ("ws_handshake: received websocket upgrade request\n"));
// search for websocket security key
char *key_start = strstr(data, "Sec-WebSocket-Key: ");
if (key_start) {
key_start += 19;
const char *key_end = strstr(key_start, "\r\n");
if (key_end) {
char key[64];
uint16_t key_len = key_end-key_start;
if ( (key_len>0) && (key_len + sizeof(WS_GUID) < sizeof(key)) ) {
// create response key by concatenating with websocket GUID,
// taking SHA1 hash, then encoding in base 64
strncpy(key, key_start, key_len);
strlcpy(&key[key_len], WS_GUID, sizeof(key)-key_len);
key_len += sizeof(WS_GUID)-1;
unsigned char key_sha1[20];
unsigned char key_base64[29];
size_t encoded_len;
mbedtls_sha1( (unsigned char *) key, key_len, key_sha1);
mbedtls_base64_encode( key_base64, 29, &encoded_len, key_sha1, 20);
// create response packet with encoded response key
unsigned char response[sizeof(WS_RESPONSE) + sizeof(key_base64)+3];
size_t count = sprintf(response, "%s%s\r\n\r\n", WS_RESPONSE, key_base64);
// send completed data packet
LWIP_DEBUGF(WS_DEBUG, ("ws_handshake: sending response\n"));
if(altcp_write(pcb, response, count, TCP_WRITE_FLAG_COPY) == ERR_OK) {
wss->active = true;
}
if (ws_open_cb != NULL) {
ws_open_cb(wss);
}
return ERR_OK;
}
}
LWIP_DEBUGF(WS_DEBUG, ("ws_handshake: key overflow\n"));
return ERR_MEM;
} else {
LWIP_DEBUGF(WS_DEBUG, ("ws_handshake: key not received\n"));
return ERR_ARG;
}
}
LWIP_DEBUGF(WS_DEBUG, ("ws_handshake: not a websocket request\n"));
return ERR_ARG;
}
// handle reading of websocket data and pass to ws_receive_cb
static err_t ws_read(struct altcp_pcb *pcb, struct ws_state *wss, struct pbuf *p) {
(void) pcb;
uint8_t *data = (uint8_t *) p->payload;
uint16_t len = p->len;
if (data != NULL && len > 1) {
// successful read, reset timeout
wss->retries = 0;
uint8_t fin = data[0] & 0x80;
uint8_t opcode = data[0] & 0x0F;
uint8_t masked = data[1] & 0x80;
uint16_t msg_len = data[1] & 0x7F;
uint8_t *msg;
switch (msg_len) {
case 126: // next two bytes are length
memcpy(&msg_len, &data[2], 2);
if (len >= 8) {
msg = &data[8];
}
break;
case 127: // next four bytes are length
// lwIP's pbuf only handles 16-bit lengths, so error
LWIP_DEBUGF(WS_DEBUG, ("ws_read: received 64-bit length %u\n", msg_len));
return ERR_MEM;
default:
if (len >= 6) {
msg = &data[6];
}
break;
}
switch (opcode) {
case OP_CONT:
LWIP_DEBUGF(WS_DEBUG, ("ws_read: received continuation frame\n"));
case OP_TEXT:
LWIP_DEBUGF(WS_DEBUG, ("ws_read: received text data\n"));
case OP_BINARY:
LWIP_DEBUGF(WS_DEBUG, ("ws_read: decoding data, len=%u\n", msg_len));
if (msg && ws_receive_cb != NULL) {
// unmask the data if mask bit is received
if (masked) {
uint8_t *mask = &data[2];
for (int i=0; i<msg_len; i++) {
msg[i] ^= mask[i % 4];
}
} else {
// messages from client must be masked - disconnect
LWIP_DEBUGF(WS_DEBUG, ("ws_read: received unmasked message"));
return ERR_CLSD;
}
msg[msg_len]=0;
if (opcode != OP_CONT) { // not a continuation frame, reset buffer
buf_len=0;
memset(buf, 0x00, sizeof(buf));
}
if (buf_len + msg_len > WS_BUFFER_SIZE) {
LWIP_DEBUGF(WS_DEBUG, ("ws_read: message exceeds buffer size %u+%u\n", buf_len, msg_len));
return ERR_MEM;
}
memcpy(&buf[buf_len], msg, msg_len);
buf_len += msg_len;
if (fin) { // last packet in message, process completed message
ws_receive_cb(buf, buf_len);
}
}
break;
case OP_CLOSE:
LWIP_DEBUGF(WS_DEBUG, ("ws_read: close request"));
return ERR_CLSD;
case OP_PING:
// control frames cannot exceed 125 bytes in length
if (msg && msg_len <= 125) {
// send back a pong
uint8_t pong[2+msg_len];
pong[0]=0x8A;
pong[1]=msg_len;
memcpy(&pong[2], msg, msg_len);
return ws_send(wss, pong, msg_len+2);
}
return ERR_ARG;
case OP_PONG: // no response required for pong
return ERR_OK;
default:
LWIP_DEBUGF(WS_DEBUG, ("ws_read: invalid opcode %02X\n", opcode));
return ERR_ARG;
}
return ERR_OK;
}
LWIP_DEBUGF(WS_DEBUG, ("ws_read: received empty payload\n"));
return ERR_VAL;
}
static err_t ws_send(struct ws_state *wss, uint8_t *data, uint16_t len) {
uint8_t buf[128];
buf[0] = 0x81;
buf[1] = len & 0x7F;
memcpy(&buf[2], data, len);
err_t err;
err = altcp_write(wss->pcb, buf, len+2, TCP_WRITE_FLAG_COPY);
if (err == ERR_OK) {
altcp_output(wss->pcb);
}
return err;
}
void ws_send_all(uint8_t *data, uint16_t len) {
// send message to all connections
if (ws_connections != NULL) {
struct ws_state *wss;
err_t err;
for (wss=ws_connections; wss != NULL; wss=wss->next) {
err = ws_send(wss, data, len);
if (err != ERR_OK ) {
LWIP_DEBUGF(WS_DEBUG, ("ws_send_all: error sending to %p\n", wss));
}
}
}
}
+36
View File
@@ -0,0 +1,36 @@
#ifndef WEBSOCKET_H_
#define WEBSOCKET_H_
#define WS_PORT 8080
#define WS_TIMEOUT 10
#define WS_DEBUG LWIP_DBG_ON
#define WS_MAX_RETRIES 10
#define WS_POLL_INTERVAL 60 // WS_POLL_INTERVAL/2 seconds
#define WS_MAX_CONN 4
#define WS_BUFFER_SIZE 512
#define OP_CONT 0x00
#define OP_TEXT 0x01
#define OP_BINARY 0x02
#define OP_CLOSE 0x08
#define OP_PING 0x09
#define OP_PONG 0x0A
struct ws_state {
bool active;
uint8_t retries;
struct altcp_pcb *pcb;
struct ws_state *next;
};
#define WS_ALLOC_WS_STATE() (struct ws_state *)mem_malloc(sizeof(struct ws_state))
typedef void (* tWSHandler ) (uint8_t *data, uint16_t len);
typedef void (* tWSOpenHandler ) (struct ws_state * wss);
void ws_server_init(void);
void ws_send_all(uint8_t *data, uint16_t len);
void ws_set_receive_handler( tWSHandler ws_handler);
void ws_set_open_handler( tWSOpenHandler ws_handler);
#endif