├── .gitignore
├── 00install.bash
├── 1-run-backend
├── 2-run-frontend
├── LICENSE
├── README.md
├── experimental
├── go.mod
├── go.sum
├── gtktest
│ └── gtktest.go
└── jspython
│ └── jspython.py
├── nscontroller
├── autofire.go
├── backend_proxy.go
├── cmd
│ ├── nsbackend
│ │ ├── fifo.go
│ │ ├── nsbackend.go
│ │ └── subcommands.go
│ └── nsfrontend
│ │ └── nsfrontend.go
├── events.go
├── go.mod
├── go.sum
├── js
│ └── js_linux.go
├── jsinput.go
├── nscon.go
├── nsprojoystick.go
├── psjoystick.go
├── scripts
│ └── switch-controller-gadget
├── streaminput.go
├── utils
│ └── sync.go
└── xboxjoystick.go
└── presubmit.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # If you prefer the allow list template instead of the deny list, see community template:
2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
3 | #
4 | # Binaries for programs and plugins
5 | *.exe
6 | *.exe~
7 | *.dll
8 | *.so
9 | *.dylib
10 |
11 | # Test binary, built with `go test -c`
12 | *.test
13 |
14 | # Output of the go coverage tool, specifically when used with LiteIDE
15 | *.out
16 |
17 | # Dependency directories (remove the comment below to include it)
18 | # vendor/
19 |
20 | # Go workspace file
21 | go.work
22 | go.work.sum
23 |
24 | # env file
25 | .env
26 |
--------------------------------------------------------------------------------
/00install.bash:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 | SCRIPT_DIR="${0%/*}"
5 |
6 | cd "$SCRIPT_DIR"/nscontroller/cmd/
7 | go install ./...
8 |
--------------------------------------------------------------------------------
/1-run-backend:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | cd "${0%/*}"/nscontroller
6 |
7 | go run ./cmd/nsbackend "$@"
8 |
9 |
--------------------------------------------------------------------------------
/2-run-frontend:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | cd "${0%/*}"/nscontroller
6 |
7 | go run ./cmd/nsfrontend "$@"
8 |
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # raspberry-switch-control
2 |
3 | Emulate Nintendo Switch USB Controller with Raspberry Pi
4 |
5 | Credit: This project heavily relies on https://github.com/mzyy94/nscon.
6 |
7 | ## Hardware requirements
8 | * Raspberry Pi. Tested with Zero W and Pi 4. Not sure if Pi 5 works. (Saw an page saying 5 doesn't support the usb "gadget" mode?)
9 |
10 | ## Set up Raspberry Pi
11 |
12 | Tested on Ubuntu 24 (on Pi 4) and the latest Raspberry Pi OS (on Zero W 2) on 2024-12-31.
13 |
14 | 1. Install libcomposites for the USB gadget mode. (From )
15 |
16 | # Needed this on Raspberry Pi OS (?). Not needed on Ubuntu.
17 | echo "dtoverlay=dwc2" | sudo tee -a /boot/firmware/config.txt
18 |
19 |
20 | echo "dwc2" | sudo tee -a /etc/modules
21 | echo "libcomposite" | sudo tee -a /etc/modules
22 |
23 | reboot
24 |
25 | 1. Install binary on the Raspberry Pi.
26 |
27 | # Install commands
28 | apt install -y golang xxd git
29 |
30 | go install -v github.com/omakoto/raspberry-switch-control/nscontroller/cmd/...@latest
31 |
32 | 1. ~~Download source for the following script.~~
33 |
34 | This step is no longer needed. Now you can use the following sudo command to run the script.
35 |
36 | 1. Create the USB gadget by running the `switch-controller-gadget` script.
37 |
38 | The path to this script is not stable. Run `nsbackend usb-init-script-path` to get the path.
39 |
40 | sudo bash "$($HOME/go/bin/nsbackend usb-init-script-path)"
41 |
42 | Or, add the following entry to root's `crontabe` (i.e. `sudo crontab -e` and add it)
43 | Change `/home/pi/` as needed.
44 |
45 |
46 | @reboot bash -c ". $(/home/pi/go/bin/nsbackend usb-init-script-path)"
47 |
48 |
49 | 2. Connect the Raspberry Pi to the Nintendo Switch
50 |
51 | - If it's a Pi 4 or 5, use the USB-C port.
52 |
53 | My configuration: connect the Switch to a *powered* USB hub, then connect it to the Pi's C port. Make sure the Pi can draw enough power.
54 |
55 | - If it's a Zero, use the micro USB port.
56 |
57 |
58 | ## Control Nintendo Switch with Joystick on a PC (via Raspberry Pi)
59 |
60 | 1. Connect the Raspberry Pi to the Switch.
61 | - If using a Pi Zero, connect via the micro-USB port.
62 | - If using a Pi 4, connect to the USB C port. (aka the power port)
63 | - *Either way, to make sure the Pi keeps running even when not connected to the switch, use a powered USB hub.*
64 |
65 | (So, ideally, use a hub with a usb C output and connect it to the Pi, rather than using an A port.)
66 |
67 | 1. Connect a joystick to a host PC. (only the following ones are supported and tested)
68 | 1. Nintendo Pro controller
69 | 2. X-Box One controller
70 | 3. PS4 controller
71 |
72 | 1. On the host PC, install the software:
73 |
74 | apt install -y golang
75 | go install -v github.com/omakoto/raspberry-switch-control/nscontroller/cmd/...@latest
76 |
77 | 1. On the host PC, run it:
78 |
79 | nsfrontend -j /dev/input/js0 -o >(ssh pi@$PI_ADDRESS go/bin/nsbackend)
80 |
81 | 1. Press `[enter]` on the console to finish.
82 |
83 |
84 | ## Run backend as daemon (Advanced use)
85 |
86 | 1. Auto start `nsbackend` as a daemon. Add this to `root`'s crontab.
87 |
88 | $ sudo crontab -l
89 | # ...
90 | @reboot bash -c ". $(/home/pi/go/bin/nsbackend usb-init-script-path); /home/pi/go/bin/nsbackend -x"
91 |
92 |
93 | 1. Then write to `/tmp/nsbackend.fifo` from `nsfrontend` instead:
94 |
95 | nsfrontend -j /dev/input/js0 -o >(ssh pi@$PI_ADDRESS 'echo "SSH Connected."; cat > /tmp/nsbackend.fifo')
96 |
97 |
98 | ## TODOs
99 |
100 | - Autofire on/off
101 | - Macro
102 |
103 |
104 | ## References
105 | 1. Control switch from a smart phone
106 | 1. https://mzyy94.com/blog/2020/03/20/nintendo-switch-pro-controller-usb-gadget/
107 | 1. https://github.com/mzyy94/nscon
108 | 1. https://gist.github.com/mzyy94/60ae253a45e2759451789a117c59acf9#file-add_procon_gadget-sh
109 | 1. https://www.kernel.org/doc/html/v4.13/driver-api/usb/gadget.html
110 | 1. https://github.com/milador/RaspberryPi-Joystick
111 | 1. https://www.rmedgar.com/blog/using-rpi-zero-as-keyboard-setup-and-device-definition
112 | 1. https://github.com/wchill/SwitchInputEmulator
113 | 1. https://sourceforge.net/projects/linuxconsole/
114 | 1. https://github.com/progmem/Switch-Fightstick
115 | 1. https://sourceforge.net/p/linuxconsole/code/ci/master/tree/utils/jstest.c
116 | 1. http://www.fourwalledcubicle.com/files/LUFA/Doc/120219/html/group___group___std_descriptors.html
117 |
--------------------------------------------------------------------------------
/experimental/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/omakoto/raspberry-switch-control/experiment
2 |
3 | go 1.14
4 |
5 | require (
6 | github.com/BurntSushi/xgb v0.0.0-20200324125942-20f126ea2843
7 | github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046
8 | github.com/omakoto/go-common v0.0.0-20190929182938-7ec82e969da9
9 | )
10 |
--------------------------------------------------------------------------------
/experimental/go.sum:
--------------------------------------------------------------------------------
1 | github.com/BurntSushi/xgb v0.0.0-20200324125942-20f126ea2843 h1:3iF31c7rp7nGZVDv7YQ+VxOgpipVfPKotLXykjZmwM8=
2 | github.com/BurntSushi/xgb v0.0.0-20200324125942-20f126ea2843/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
3 | github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046 h1:O/r2Sj+8QcMF7V5IcmiE2sMFV2q3J47BEirxbXJAdzA=
4 | github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046/go.mod h1:uw9h2sd4WWHOPdJ13MQpwK5qYWKYDumDqxWWIknEQ+k=
5 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
7 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
8 | github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
9 | github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
10 | github.com/omakoto/go-common v0.0.0-20190929182938-7ec82e969da9 h1:PLuzwAS/CCOxCzg5c67yx0Uv4tSCscIffBvHhaG6hLg=
11 | github.com/omakoto/go-common v0.0.0-20190929182938-7ec82e969da9/go.mod h1:qZAhdjMaCqvLTLpircN5wqm3B0S7eUTd6flSszQF5gE=
12 | github.com/pborman/getopt v0.0.0-20190409184431-ee0cd42419d3/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
13 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
14 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
15 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
16 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
17 | golang.org/x/crypto v0.0.0-20190927123631-a832865fa7ad/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
18 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
19 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
20 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
21 | golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
22 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
23 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
24 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
25 |
--------------------------------------------------------------------------------
/experimental/gtktest/gtktest.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | // See: https://github.com/BurntSushi/xgbutil/blob/master/keybind/doc.go
4 | import (
5 | "fmt"
6 | _ "github.com/BurntSushi/xgb/xproto"
7 | "github.com/BurntSushi/xgbutil"
8 | "github.com/BurntSushi/xgbutil/keybind"
9 | "github.com/BurntSushi/xgbutil/xevent"
10 | "github.com/omakoto/go-common/src/common"
11 | )
12 |
13 | func main() {
14 | xu, err := xgbutil.NewConn()
15 | common.Checke(err)
16 |
17 | keybind.Initialize(xu)
18 |
19 | // This isn't quite "press/release" because key repeats trigger them.
20 | keybind.KeyPressFun(
21 | func(X *xgbutil.XUtil, ev xevent.KeyPressEvent) {
22 | fmt.Printf("Pressed: %v\n", ev)
23 | }).Connect(xu, xu.RootWin(), "a", true)
24 |
25 | keybind.KeyReleaseFun(func(xu *xgbutil.XUtil, ev xevent.KeyReleaseEvent) {
26 | fmt.Printf("Released: %v\n", ev)
27 | }).Connect(xu, xu.RootWin(), "a", true)
28 |
29 | //xevent.KeyPressFun(
30 | // func(X *xgbutil.XUtil, e xevent.KeyPressEvent) {
31 | // // keybind.LookupString does the magic of implementing parts of
32 | // // the X Keyboard Encoding to determine an english representation
33 | // // of the modifiers/keycode tuple.
34 | // // N.B. It's working for me, but probably isn't 100% correct in
35 | // // all environments yet.
36 | // modStr := keybind.ModifierString(e.State)
37 | // keyStr := keybind.LookupString(X, e.State, e.Detail)
38 | // if len(modStr) > 0 {
39 | // fmt.Printf("Key: %s-%s\n", modStr, keyStr)
40 | // } else {
41 | // fmt.Println("Key:", keyStr)
42 | // }
43 | //
44 | // if keybind.KeyMatch(X, "Escape", e.State, e.Detail) {
45 | // if e.State&xproto.ModMaskControl > 0 {
46 | // fmt.Println("Control-Escape detected. Quitting...")
47 | // xevent.Quit(X)
48 | // }
49 | // }
50 | // }).Connect(xu, xu.RootWin())
51 |
52 | xevent.Main(xu)
53 | }
54 |
--------------------------------------------------------------------------------
/experimental/jspython/jspython.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # Copied from https://gist.githubusercontent.com/rdb/8864666/raw/516178252bbe1cfe8067145b11223ee54c5d9698/js_linux.py
3 |
4 | import os, struct, array
5 | from fcntl import ioctl
6 |
7 | # Iterate over the joystick devices.
8 | print('Available devices:')
9 |
10 | for fn in os.listdir('/dev/input'):
11 | if fn.startswith('js'):
12 | print(' /dev/input/%s' % (fn))
13 |
14 | # We'll store the states here.
15 | axis_states = {}
16 | button_states = {}
17 |
18 | # These constants were borrowed from linux/input.h
19 | axis_names = {
20 | 0x00 : 'x', # switch L-stick
21 | 0x01 : 'y', # switch L-stick
22 | 0x02 : 'z',
23 | 0x03 : 'rx', # switch R-stick
24 | 0x04 : 'ry', # switch R-stick
25 | 0x05 : 'rz',
26 | 0x06 : 'trottle',
27 | 0x07 : 'rudder',
28 | 0x08 : 'wheel',
29 | 0x09 : 'gas',
30 | 0x0a : 'brake',
31 | 0x10 : 'hat0x', # switch D-pad
32 | 0x11 : 'hat0y', # switch D-pad
33 | 0x12 : 'hat1x',
34 | 0x13 : 'hat1y',
35 | 0x14 : 'hat2x',
36 | 0x15 : 'hat2y',
37 | 0x16 : 'hat3x',
38 | 0x17 : 'hat3y',
39 | 0x18 : 'pressure',
40 | 0x19 : 'distance',
41 | 0x1a : 'tilt_x',
42 | 0x1b : 'tilt_y',
43 | 0x1c : 'tool_width',
44 | 0x20 : 'volume',
45 | 0x28 : 'misc',
46 | }
47 |
48 | button_names = {
49 | 0x120 : 'trigger',
50 | 0x121 : 'thumb',
51 | 0x122 : 'thumb2',
52 | 0x123 : 'top',
53 | 0x124 : 'top2',
54 | 0x125 : 'pinkie',
55 | 0x126 : 'base',
56 | 0x127 : 'base2',
57 | 0x128 : 'base3',
58 | 0x129 : 'base4',
59 | 0x12a : 'base5',
60 | 0x12b : 'base6',
61 | 0x12f : 'dead',
62 | 0x130 : 'a', # switch B
63 | 0x131 : 'b', # switch A
64 | 0x132 : 'c',
65 | 0x133 : 'x', # switch X
66 | 0x134 : 'y', # switch Y
67 | 0x135 : 'z', # switch Capture
68 | 0x136 : 'tl', # switch L
69 | 0x137 : 'tr', # switch R
70 | 0x138 : 'tl2', # switch LZ
71 | 0x139 : 'tr2', # switch RZ
72 | 0x13a : 'select', # switch -
73 | 0x13b : 'start', # switch +
74 | 0x13c : 'mode', # switch Home
75 | 0x13d : 'thumbl',
76 | 0x13e : 'thumbr',
77 |
78 | 0x220 : 'dpad_up',
79 | 0x221 : 'dpad_down',
80 | 0x222 : 'dpad_left',
81 | 0x223 : 'dpad_right',
82 |
83 | # XBox 360 controller uses these codes.
84 | 0x2c0 : 'dpad_left',
85 | 0x2c1 : 'dpad_right',
86 | 0x2c2 : 'dpad_up',
87 | 0x2c3 : 'dpad_down',
88 | }
89 |
90 | axis_map = []
91 | button_map = []
92 |
93 | # Open the joystick device.
94 | fn = '/dev/input/js0'
95 | print('Opening %s...' % fn)
96 | jsdev = open(fn, 'rb')
97 |
98 | # Get the device name.
99 | #buf = bytearray(63)
100 | buf = array.array('B', [0] * 64)
101 | ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len)
102 | js_name = buf.tobytes().rstrip(b'\x00').decode('utf-8')
103 | print('Device name: %s' % js_name)
104 |
105 | # Get number of axes and buttons.
106 | buf = array.array('B', [0])
107 | ioctl(jsdev, 0x80016a11, buf) # JSIOCGAXES
108 | num_axes = buf[0]
109 |
110 | buf = array.array('B', [0])
111 | ioctl(jsdev, 0x80016a12, buf) # JSIOCGBUTTONS
112 | num_buttons = buf[0]
113 |
114 | # Get the axis map.
115 | buf = array.array('B', [0] * 0x40)
116 | ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP
117 |
118 | for axis in buf[:num_axes]:
119 | axis_name = axis_names.get(axis, 'unknown(0x%02x)' % axis)
120 | axis_map.append(axis_name)
121 | axis_states[axis_name] = 0.0
122 |
123 | # Get the button map.
124 | buf = array.array('H', [0] * 200)
125 | ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP
126 |
127 | for btn in buf[:num_buttons]:
128 | btn_name = button_names.get(btn, 'unknown(0x%03x)' % btn)
129 | button_map.append(btn_name)
130 | button_states[btn_name] = 0
131 |
132 | print('%d axes found: %s' % (num_axes, ', '.join(axis_map)))
133 | print('%d buttons found: %s' % (num_buttons, ', '.join(button_map)))
134 |
135 | # Main event loop
136 | while True:
137 | evbuf = jsdev.read(8)
138 | if evbuf:
139 | time, value, type, number = struct.unpack('IhBB', evbuf)
140 |
141 | if type & 0x80:
142 | print("(initial)", end="")
143 |
144 | if type & 0x01:
145 | button = button_map[number]
146 | if button:
147 | button_states[button] = value
148 | if value:
149 | print("%s pressed" % (button))
150 | else:
151 | print("%s released" % (button))
152 |
153 | if type & 0x02:
154 | axis = axis_map[number]
155 | if axis:
156 | fvalue = value / 32767.0
157 | axis_states[axis] = fvalue
158 | print("%s: %.3f" % (axis, fvalue))
--------------------------------------------------------------------------------
/nscontroller/autofire.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import (
4 | "time"
5 |
6 | "github.com/omakoto/go-common/src/common"
7 | "github.com/omakoto/raspberry-switch-control/nscontroller/utils"
8 | "github.com/pborman/getopt/v2"
9 | )
10 |
11 | var (
12 | tickInterval = getopt.IntLong("tick", 't', 10, "Tick interval in milliseconds")
13 | )
14 |
15 | type AutofireMode int
16 |
17 | const (
18 | AutofireModeDeactivated = AutofireMode(iota)
19 | AutofireModeNormal
20 | AutofireModeInvert
21 | AutofireModeToggle
22 | )
23 |
24 | type buttonState struct {
25 | mode AutofireMode
26 |
27 | // interval is the autofire interval for each button.
28 | interval time.Duration
29 |
30 | // autoLastTimestamp is the timestamp of the last on or off autofire event.
31 | autoLastTimestamp time.Time
32 |
33 | // realButtonPressed is whether the button is actually pressed or not.
34 | realButtonPressed bool
35 |
36 | // autofireEnabled is whether autofire is on (so events will be continuously produced) or off.
37 | autofireOn bool
38 |
39 | // lastValue is the last reported value to the next consumer.
40 | lastValue bool
41 | }
42 |
43 | type AutoFirer struct {
44 | syncer *utils.Synchronized
45 | next Consumer
46 | states []buttonState
47 | ticker *time.Ticker
48 | stop chan bool
49 | }
50 |
51 | var _ Worker = (*AutoFirer)(nil)
52 |
53 | func NewAutoFirer(next Consumer) *AutoFirer {
54 | return &AutoFirer{
55 | utils.NewSynchronized(),
56 | next,
57 | make([]buttonState, ActionButtonLast),
58 | nil,
59 | nil,
60 | }
61 | }
62 |
63 | func (af *AutoFirer) Run() {
64 | af.syncer.Run(func() {
65 | if af.ticker != nil {
66 | common.Fatal("AutoFirer already running")
67 | return
68 | }
69 | common.Debug("AutoFirer started")
70 | af.ticker = time.NewTicker(time.Duration(*tickInterval) * time.Millisecond)
71 | af.stop = make(chan bool)
72 |
73 | ticker := af.ticker
74 | stop := af.stop
75 |
76 | go func() {
77 | loop:
78 | for {
79 | select {
80 | case <-ticker.C:
81 | af.tick()
82 | case <-stop:
83 | break loop
84 | }
85 | }
86 | af.syncer.Run(func() {
87 | af.ticker = nil
88 | af.stop = nil
89 | })
90 | common.Debug("AutoFirer stopped")
91 | }()
92 | })
93 | }
94 |
95 | func (af *AutoFirer) Close() error {
96 | af.syncer.Run(func() {
97 | if af.ticker != nil {
98 | common.Debug("AutoFirer stopping")
99 | af.stop <- true
100 | } else {
101 | common.Debug("AutoFirer not running")
102 | }
103 | })
104 | return nil
105 | }
106 |
107 | func (af *AutoFirer) SetAutofire(a Action, mode AutofireMode, interval time.Duration) {
108 | common.OrFatalf(interval >= 0, "interval must be >= 0 but was: %d", interval)
109 | af.syncer.Run(func() {
110 | af.states[a].mode = mode
111 | af.states[a].interval = interval
112 |
113 | af.setAutofireLocked(&Event{time.Now(), a, 0}, true)
114 | })
115 | }
116 |
117 | func (af *AutoFirer) setAutofireLocked(ev *Event, force bool) {
118 | bs := &af.states[ev.Action]
119 | pressed := ev.Value == 1
120 |
121 | if bs.realButtonPressed == pressed && !force {
122 | return // Button state hasn't changed; ignore.
123 | }
124 |
125 | bs.realButtonPressed = pressed
126 |
127 | switch bs.mode {
128 | case AutofireModeDeactivated:
129 | af.next(ev)
130 | case AutofireModeNormal:
131 | bs.autofireOn = ev.pressed()
132 | af.sendAutofireEventLocked(ev.Timestamp, ev.Action, pressed)
133 | case AutofireModeInvert:
134 | bs.autofireOn = !ev.pressed()
135 | af.sendAutofireEventLocked(ev.Timestamp, ev.Action, !pressed)
136 | case AutofireModeToggle:
137 | if pressed {
138 | bs.autofireOn = !bs.autofireOn
139 | af.sendAutofireEventLocked(ev.Timestamp, ev.Action, bs.autofireOn)
140 | }
141 | }
142 | }
143 |
144 | func (af *AutoFirer) sendAutofireEventLocked(timestamp time.Time, a Action, pressed bool) {
145 | bs := &af.states[a]
146 |
147 | ev := Event{Timestamp: timestamp, Action: a, Value: BoolToValue(pressed)}
148 | af.next(&ev)
149 |
150 | bs.autoLastTimestamp = ev.Timestamp
151 | bs.lastValue = pressed
152 | }
153 |
154 | func (af *AutoFirer) Consume(ev *Event) {
155 | af.syncer.Run(func() {
156 | if ev.Action.isButton() {
157 | af.setAutofireLocked(ev, false)
158 | } else {
159 | // Just forward any axis events.
160 | af.next(ev)
161 | }
162 | })
163 | }
164 |
165 | func (af *AutoFirer) tick() {
166 | af.syncer.Run(func() {
167 | // common.Debug("AutoFirer tick")
168 |
169 | now := time.Now()
170 | for a := ActionButtonStart; a < ActionButtonLast; a++ {
171 | bs := &af.states[a]
172 |
173 | if bs.mode == AutofireModeDeactivated || !bs.autofireOn {
174 | continue
175 | }
176 | nextTimestamp := bs.autoLastTimestamp.Add(bs.interval)
177 | if nextTimestamp.After(now) {
178 | return
179 | }
180 |
181 | // Synthesis an event.
182 | af.sendAutofireEventLocked(nextTimestamp, a, !bs.lastValue)
183 | }
184 |
185 | })
186 | }
187 |
--------------------------------------------------------------------------------
/nscontroller/backend_proxy.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import (
4 | "fmt"
5 | "github.com/omakoto/go-common/src/common"
6 | "github.com/omakoto/raspberry-switch-control/nscontroller/utils"
7 | "io"
8 | )
9 |
10 | type BackendProxy struct {
11 | syncer *utils.Synchronized
12 | out io.WriteCloser
13 | }
14 |
15 | var _ io.Closer = (*BackendProxy)(nil)
16 |
17 | func NewBackendConsumer(out io.WriteCloser) (*BackendProxy, error) {
18 | return &BackendProxy{utils.NewSynchronized(), out}, nil
19 | }
20 |
21 | func (b *BackendProxy) Close() error {
22 | return b.out.Close()
23 | }
24 |
25 | func (b *BackendProxy) Consume(ev *Event) {
26 | b.syncer.Run(func() {
27 | command := ""
28 |
29 | switch ev.Action {
30 | case ActionButtonA:
31 | command = "a"
32 | case ActionButtonB:
33 | command = "b"
34 | case ActionButtonX:
35 | command = "x"
36 | case ActionButtonY:
37 | command = "y"
38 |
39 | case ActionButtonMinus:
40 | command = "-"
41 | case ActionButtonPlus:
42 | command = "+"
43 |
44 | case ActionButtonHome:
45 | command = "h"
46 | case ActionButtonCapture:
47 | command = "c"
48 |
49 | case ActionButtonDpadUp:
50 | command = "pu"
51 | case ActionButtonDpadDown:
52 | command = "pd"
53 | case ActionButtonDpadLeft:
54 | command = "pl"
55 | case ActionButtonDpadRight:
56 | command = "pr"
57 |
58 | case ActionButtonL:
59 | command = "l1"
60 | case ActionButtonR:
61 | command = "r1"
62 | case ActionButtonLZ:
63 | command = "l2"
64 | case ActionButtonRZ:
65 | command = "r2"
66 |
67 | case ActionButtonLeftStickPress:
68 | command = "lp"
69 | case ActionButtonRightStickPress:
70 | command = "rp"
71 |
72 | case ActionAxisLX:
73 | command = "lx"
74 | case ActionAxisLY:
75 | command = "ly"
76 |
77 | case ActionAxisRX:
78 | command = "rx"
79 | case ActionAxisRY:
80 | command = "ry"
81 | }
82 |
83 | msg := fmt.Sprint(command, " ", ev.Value, "\n")
84 |
85 | _, err := b.out.Write([]byte(msg))
86 | common.Checkf(err, "Unable to write the message")
87 | })
88 | }
89 |
--------------------------------------------------------------------------------
/nscontroller/cmd/nsbackend/fifo.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "errors"
5 | "os"
6 | "syscall"
7 |
8 | "github.com/omakoto/go-common/src/common"
9 | )
10 |
11 | func mustCreateFifo(path string) *os.File {
12 | common.Debugf("Creating FIFO at '%s'", path)
13 |
14 | _, err := os.Stat(path)
15 | if err == nil {
16 | // File exists. Delete it.
17 | err = os.Remove(path)
18 | common.Checkf(err, "Cannot delete file: '%s'", path)
19 | } else if !errors.Is(err, os.ErrNotExist) {
20 | common.Checkf(err, "Cannot create file '%s': stat failed", path)
21 | }
22 | err = syscall.Mkfifo(path, 0666)
23 | common.Checkf(err, "Makefifo failed for '%s'", path)
24 |
25 | file, err := os.OpenFile(path, os.O_RDWR, 0666)
26 | common.Checkf(err, "Open failed for '%s'", path)
27 |
28 | return file
29 | }
30 |
--------------------------------------------------------------------------------
/nscontroller/cmd/nsbackend/nsbackend.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "math"
7 | "os"
8 | "strconv"
9 | "strings"
10 | "sync"
11 | "syscall"
12 | "time"
13 |
14 | "github.com/omakoto/go-common/src/common"
15 | "github.com/omakoto/go-common/src/daemon"
16 | "github.com/omakoto/go-common/src/fileutils"
17 | "github.com/omakoto/raspberry-switch-control/nscontroller"
18 | "github.com/pborman/getopt/v2"
19 | )
20 |
21 | const (
22 | analogToDigitalThreshold = 1.0
23 | )
24 |
25 | var (
26 | help = getopt.BoolLong("help", 'h', "help")
27 | debug = getopt.BoolLong("debug", 'd', "Enable debug output")
28 | device = getopt.StringLong("device", 'f', "/dev/hidg0", "Specify device file")
29 | startAsDaemon = getopt.BoolLong("daemon", 'x', "Run as daemon (implies --make-fifo)")
30 | createFifo = getopt.BoolLong("make-fifo", 0, "Create a FIFO and read commands from it")
31 | fifo = getopt.StringLong("fifo", 0, "/tmp/nsbackend.fifo", "Specify FIFO filename")
32 | autoReleaseMillis = getopt.IntLong("auto-release-millis", 'a', 50, "Set auto-release delay in milliseconds")
33 | usbTickIntervalMillis = getopt.IntLong("tick-interval-millis", 0, 5, "Send updates to Switch every this milliseconds")
34 |
35 | autoReleaseDur time.Duration
36 | )
37 |
38 | // The delay needs to be bigger than the interval within startInputReport().
39 | const AUTO_RELEASE_MILLIS_MIN = 20
40 |
41 | func parseCommand(s string) (command string, arg float64, autoRelease bool, err error, dur time.Duration) {
42 | command = ""
43 | arg = 0
44 |
45 | arr := strings.Fields(s)
46 | if len(arr) == 0 {
47 | return "", 0, false, nil, 0
48 | }
49 | cmdIndex := 0
50 |
51 | if len(arr[0]) > 0 && '0' <= arr[0][0] && arr[0][0] <= '9' {
52 | durationSec, err := strconv.ParseFloat(arr[0], 32)
53 | if err != nil {
54 | common.Warnf("Invalid float: %#v", arr[1])
55 | return "", 0, false, err, 0
56 | }
57 | dur = time.Duration(durationSec * float64(time.Second))
58 | cmdIndex = 1
59 | }
60 |
61 | command = arr[cmdIndex]
62 | if len(arr) > cmdIndex+1 {
63 | arg, err = strconv.ParseFloat(arr[cmdIndex+1], 32)
64 | if err != nil {
65 | common.Warnf("Invalid float: %#v", arr[1])
66 | return "", 0, false, err, 0
67 | }
68 | if arg < -1 {
69 | arg = -1
70 | } else if arg > 1 {
71 | arg = 1
72 | }
73 | } else {
74 | arg = 1
75 | autoRelease = true
76 | }
77 |
78 | ar := ""
79 | if autoRelease {
80 | ar = " (auto-release)"
81 | }
82 | common.Debugf("Command=%#v arg=%f%s (dur=%v)", command, arg, ar, dur)
83 | return
84 | }
85 |
86 | func aToD(arg float64) (neg, pos uint8) {
87 | if arg >= analogToDigitalThreshold {
88 | pos = 1
89 | neg = 0
90 | } else if arg <= -analogToDigitalThreshold {
91 | pos = 0
92 | neg = 1
93 | } else {
94 | pos = 0
95 | neg = 0
96 | }
97 | return
98 | }
99 |
100 | type Coordinator struct {
101 | con *nscontroller.Controller
102 | ch chan string
103 | wg sync.WaitGroup
104 | started bool
105 | }
106 |
107 | func NewCoordinator(con *nscontroller.Controller) Coordinator {
108 | return Coordinator{
109 | con: con,
110 | ch: make(chan string, 100),
111 | }
112 | }
113 |
114 | func (co *Coordinator) checkStarted() {
115 | if !co.started {
116 | panic("Not started")
117 | }
118 | }
119 |
120 | func (co *Coordinator) Send(command string) {
121 | co.checkStarted()
122 | if command == "" {
123 | return
124 | }
125 | co.ch <- command
126 | }
127 |
128 | func (co *Coordinator) SendDelayed(command string, delay time.Duration) {
129 | co.checkStarted()
130 | go func() {
131 | time.Sleep(delay)
132 | co.Send(command)
133 | }()
134 | }
135 |
136 | func (co *Coordinator) Close() {
137 | co.ch <- ""
138 | }
139 |
140 | func (co *Coordinator) Start() {
141 | if co.started {
142 | panic("Already started")
143 | }
144 | co.started = true
145 | co.wg.Add(1)
146 | go func() {
147 | defer co.wg.Done()
148 | for command := range co.ch {
149 | if command == "" {
150 | break
151 | }
152 | co.sendToController(command)
153 | }
154 | }()
155 | }
156 |
157 | func (co *Coordinator) Wait() {
158 | co.checkStarted()
159 | co.wg.Wait()
160 | }
161 |
162 | func (co *Coordinator) sendToController(command string) {
163 | command, arg, autoRelease, err, dur := parseCommand(command)
164 | if err != nil || command == "" {
165 | return
166 | }
167 |
168 | // Digital button arg: 0 or 1
169 | var darg uint8 = 0
170 | if math.Abs(arg) >= analogToDigitalThreshold {
171 | darg = 1
172 | }
173 | fdarg := float64(darg)
174 |
175 | // Hmm, analog stick Y is inverted?
176 | con := co.con
177 |
178 | switch command {
179 | case "a": // A
180 | con.Input.Button.A = darg
181 | case "b": // B
182 | con.Input.Button.B = darg
183 | case "x": // X
184 | con.Input.Button.X = darg
185 | case "y": // Y
186 | con.Input.Button.Y = darg
187 |
188 | case "h": // Home
189 | con.Input.Button.Home = darg
190 | case "c": // Capture
191 | con.Input.Button.Capture = darg
192 |
193 | case "m", "-": // Minus
194 | con.Input.Button.Minus = darg
195 | case "p", "+": // Plus
196 | con.Input.Button.Plus = darg
197 |
198 | case "l1": // L1
199 | con.Input.Button.L = darg
200 | case "l2": // L2
201 | con.Input.Button.ZL = darg
202 | case "r1": // R1
203 | con.Input.Button.R = darg
204 | case "r2": // R2
205 | con.Input.Button.ZR = darg
206 |
207 | case "pu": // D-pad up
208 | con.Input.Dpad.Up = darg
209 | case "pd": // D-pad down
210 | con.Input.Dpad.Down = darg
211 | case "pl": // D-pad left
212 | con.Input.Dpad.Left = darg
213 | case "pr": // D-pad right
214 | con.Input.Dpad.Right = darg
215 |
216 | case "pur": // D-pad
217 | con.Input.Dpad.Up = darg
218 | con.Input.Dpad.Right = darg
219 | case "pul": // D-pad
220 | con.Input.Dpad.Up = darg
221 | con.Input.Dpad.Left = darg
222 | case "pdr": // D-pad
223 | con.Input.Dpad.Down = darg
224 | con.Input.Dpad.Right = darg
225 | case "pdl": // D-pad
226 | con.Input.Dpad.Down = darg
227 | con.Input.Dpad.Left = darg
228 |
229 | case "px": // D-pad alternative
230 | con.Input.Dpad.Left, con.Input.Dpad.Right = aToD(arg)
231 | case "py": // D-pad alternative
232 | con.Input.Dpad.Up, con.Input.Dpad.Down = aToD(arg)
233 |
234 | case "lp": // Left stick press
235 | con.Input.Stick.Left.Press = darg
236 | case "rp": // Right stick press
237 | con.Input.Stick.Right.Press = darg
238 |
239 | case "lx": // Left stick X
240 | con.Input.Stick.Left.X = arg
241 | case "ly": // Left stick Y
242 | con.Input.Stick.Left.Y = -arg
243 |
244 | // Left stick alternative
245 | case "lu":
246 | con.Input.Stick.Left.X = 0
247 | con.Input.Stick.Left.Y = -fdarg
248 | case "ld":
249 | con.Input.Stick.Left.X = 0
250 | con.Input.Stick.Left.Y = -fdarg
251 | case "ll":
252 | con.Input.Stick.Left.X = -fdarg
253 | con.Input.Stick.Left.Y = 0
254 | case "lr":
255 | con.Input.Stick.Left.X = fdarg
256 | con.Input.Stick.Left.Y = 0
257 | case "lur":
258 | con.Input.Stick.Left.X = fdarg
259 | con.Input.Stick.Left.Y = fdarg
260 | case "lul":
261 | con.Input.Stick.Left.X = -fdarg
262 | con.Input.Stick.Left.Y = fdarg
263 | case "ldr":
264 | con.Input.Stick.Left.X = fdarg
265 | con.Input.Stick.Left.Y = -fdarg
266 | case "ldl":
267 | con.Input.Stick.Left.X = -fdarg
268 | con.Input.Stick.Left.Y = -fdarg
269 |
270 | case "rx": // Right stick X
271 | con.Input.Stick.Right.X = arg
272 | case "ry": // Right stick Y
273 | con.Input.Stick.Right.Y = -arg
274 |
275 | // Right stick alternative
276 | case "ru":
277 | con.Input.Stick.Right.X = 0
278 | con.Input.Stick.Right.Y = fdarg
279 | case "rd":
280 | con.Input.Stick.Right.X = 0
281 | con.Input.Stick.Right.Y = -fdarg
282 | case "rl":
283 | con.Input.Stick.Right.X = -fdarg
284 | con.Input.Stick.Right.Y = 0
285 | case "rr":
286 | con.Input.Stick.Right.X = fdarg
287 | con.Input.Stick.Right.Y = 0
288 | case "rur":
289 | con.Input.Stick.Right.X = fdarg
290 | con.Input.Stick.Right.Y = fdarg
291 | case "rul":
292 | con.Input.Stick.Right.X = -fdarg
293 | con.Input.Stick.Right.Y = fdarg
294 | case "rdr":
295 | con.Input.Stick.Right.X = fdarg
296 | con.Input.Stick.Right.Y = -fdarg
297 | case "rdl":
298 | con.Input.Stick.Right.X = -fdarg
299 | con.Input.Stick.Right.Y = -fdarg
300 |
301 | default:
302 | common.Warnf("Unknown command: %#v\n", command)
303 | return
304 | }
305 |
306 | con.Send()
307 | con.Dump()
308 |
309 | if autoRelease {
310 | ds := ""
311 | if dur > 0 {
312 | ds = fmt.Sprintf("%f ", math.Max(0, (dur-autoReleaseDur).Seconds()))
313 | }
314 | co.SendDelayed(ds+command+" 0", autoReleaseDur)
315 | } else {
316 | time.Sleep(dur)
317 | }
318 | }
319 |
320 | func mainLoop(con *nscontroller.Controller, input *os.File) error {
321 | co := NewCoordinator(con)
322 | scanner := bufio.NewScanner(input)
323 |
324 | co.Start()
325 |
326 | fmt.Printf("nsbackend: Waiting for input... (^D to exit)\n")
327 | for scanner.Scan() {
328 | input := strings.ToLower(strings.TrimSpace(scanner.Text()))
329 | if input == "q" {
330 | break
331 | }
332 | co.Send(input)
333 | }
334 | fmt.Printf("nsbackend: exiting...\n")
335 |
336 | co.Close()
337 | co.Wait()
338 |
339 | return scanner.Err()
340 | }
341 |
342 | func maybeHandleSubcommand() int {
343 | if len(os.Args) > 1 {
344 | subcommand := os.Args[1]
345 | if !strings.HasPrefix(subcommand, "-") {
346 | switch subcommand {
347 | case "usb-init-script-path":
348 | printUsbInitScriptPath()
349 | return 0
350 | case "show-usb-init-script":
351 | printUsbInitScript()
352 | return 0
353 | default:
354 | common.Fatalf("Unknown subcommand: %s", subcommand)
355 | }
356 | }
357 | }
358 | return -1
359 | }
360 |
361 | func asyncConnect(con *nscontroller.Controller) {
362 | go func() {
363 | // Wait until the device shows up
364 | if !fileutils.FileExists(con.Path()) {
365 | fmt.Printf("Waiting for device '%s' to show up...\n", *device)
366 | for {
367 | if fileutils.FileExists(con.Path()) {
368 | break
369 | }
370 | time.Sleep(time.Millisecond * 100)
371 | }
372 | }
373 |
374 | fmt.Printf("Opening %s...\n", *device)
375 | err := con.Connect()
376 | fmt.Printf("Opened %s\n", *device)
377 | common.Checkf(err, "Unable to connect to device '%s'", *device)
378 | }()
379 | }
380 |
381 | func realMain() int {
382 | syscall.Umask(0)
383 |
384 | if ret := maybeHandleSubcommand(); ret >= 0 {
385 | return ret
386 | }
387 |
388 | getopt.Parse()
389 | if *help {
390 | getopt.Usage()
391 | return 0
392 | }
393 |
394 | if *debug {
395 | // con.LogLevel = 2
396 | common.DebugEnabled = true
397 | common.VerboseEnabled = true
398 | }
399 |
400 | if *startAsDaemon {
401 | if daemon.Start() {
402 | // parent
403 | return 0
404 | }
405 | // In daemon mode, always use FIFO
406 | *createFifo = true
407 | }
408 |
409 | if *autoReleaseMillis < AUTO_RELEASE_MILLIS_MIN {
410 | *autoReleaseMillis = AUTO_RELEASE_MILLIS_MIN
411 | }
412 | autoReleaseDur = time.Duration(*autoReleaseMillis * int(time.Millisecond))
413 | if device == nil {
414 | *device = "/dev/hidg0"
415 | }
416 |
417 | input := os.Stdin
418 |
419 | if *createFifo {
420 | fmt.Printf("Creating FIFO at %s...\n", input.Name())
421 | input = mustCreateFifo(*fifo)
422 | fmt.Printf("To stop it, run: echo q > '%s'\n", input.Name())
423 | fmt.Printf("Reading input from '%s'...\n", input.Name())
424 | }
425 |
426 | con := nscontroller.NewController(*device, time.Duration(*usbTickIntervalMillis*int(time.Millisecond)))
427 | defer con.Close()
428 |
429 | // Open the USB gadget device asynchronously.
430 | asyncConnect(con)
431 |
432 | err := mainLoop(con, input)
433 | common.Check(err, "Failed to read from input")
434 |
435 | return 0
436 | }
437 |
438 | func main() {
439 | common.RunAndExit(realMain)
440 | }
441 |
--------------------------------------------------------------------------------
/nscontroller/cmd/nsbackend/subcommands.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "os"
7 | "path/filepath"
8 |
9 | "github.com/omakoto/go-common/src/common"
10 | )
11 |
12 | func usbInitScriptPath() string {
13 | thisFile, _ := common.GetSourceInfo()
14 | return filepath.Clean(filepath.Dir(thisFile) + "/../../scripts/switch-controller-gadget")
15 | }
16 |
17 | func printUsbInitScriptPath() {
18 | fmt.Printf("%s\n", usbInitScriptPath())
19 | }
20 |
21 | func printUsbInitScript() {
22 | script, err := os.Open(usbInitScriptPath())
23 | common.Checke(err)
24 |
25 | content, err := io.ReadAll(script)
26 | common.Checke(err)
27 |
28 | fmt.Printf("%s", content)
29 | }
30 |
--------------------------------------------------------------------------------
/nscontroller/cmd/nsfrontend/nsfrontend.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "strings"
7 |
8 | "github.com/omakoto/go-common/src/common"
9 | "github.com/omakoto/raspberry-switch-control/nscontroller"
10 | "github.com/omakoto/raspberry-switch-control/nscontroller/js"
11 | "github.com/pborman/getopt/v2"
12 | )
13 |
14 | var (
15 | debug = getopt.BoolLong("debug", 'd', "Enable debug output")
16 | joystick = getopt.StringLong("joystick", 'j', "/dev/input/js0", "Specify joystick device file")
17 | out = getopt.StringLong("out", 'o', "/dev/stdout", "Specify backend file")
18 |
19 | myName = common.MustGetBinName()
20 | )
21 |
22 | func mustGetDispatcher(js *js.Js) nscontroller.JoystickDispatcher {
23 | if strings.Contains(js.Name, "X-Box One") || strings.Contains(js.Name, "Xbox") {
24 | return nscontroller.XBoxOneJoystickDispatcher
25 | }
26 | if strings.Contains(js.Name, "Nintendo Switch Pro Controller") {
27 | return nscontroller.NSProJoystickDispatcher
28 | }
29 | if strings.Contains(js.Name, "Sony Interactive Entertainment Wireless Controller") {
30 | return nscontroller.PsJoystickDispatcher
31 | }
32 | common.Fatalf("Unknown joystick: %s", js.Name)
33 | return nil
34 | }
35 |
36 | func realMain() int {
37 | getopt.Parse()
38 |
39 | if *debug {
40 | common.DebugEnabled = true
41 | }
42 |
43 | out, err := os.OpenFile(*out, os.O_WRONLY, 0)
44 | common.Checkf(err, "open failed")
45 |
46 | js, err := js.NewJs(*joystick)
47 | common.Checke(err)
48 |
49 | backend, err := nscontroller.NewBackendConsumer(out)
50 | common.Checke(err)
51 | defer backend.Close()
52 |
53 | autoFirer := nscontroller.NewAutoFirer(backend.Consume)
54 | defer autoFirer.Close()
55 |
56 | joystick, err := nscontroller.NewJoystickInput(js, mustGetDispatcher(js), autoFirer.Consume)
57 | common.Checke(err)
58 | defer joystick.Close()
59 |
60 | stdinProxy, err := nscontroller.NewStreamInput(os.Stdin, backend.Consume)
61 | common.Checke(err)
62 | defer stdinProxy.Close()
63 |
64 | autoFirer.Run()
65 | joystick.Run()
66 | stdinProxy.Run()
67 |
68 | fmt.Printf("nsfrontend started: Accepting command from stdin... (^D to finish)\n")
69 |
70 | // ^D to finish
71 | stdinProxy.WaitClose()
72 |
73 | common.Debugf("%s finishing", myName)
74 |
75 | return 0
76 | }
77 |
78 | func main() {
79 | common.RunAndExit(realMain)
80 | }
81 |
--------------------------------------------------------------------------------
/nscontroller/events.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import (
4 | "io"
5 | "time"
6 | )
7 |
8 | type Action int
9 |
10 | // Buttons and axes for Switch.
11 | const (
12 | ActionNone = Action(iota)
13 |
14 | ActionButtonA
15 | ActionButtonB
16 | ActionButtonX
17 | ActionButtonY
18 |
19 | ActionButtonMinus
20 | ActionButtonPlus
21 |
22 | ActionButtonHome
23 | ActionButtonCapture
24 |
25 | ActionButtonL
26 | ActionButtonR
27 | ActionButtonLZ
28 | ActionButtonRZ
29 |
30 | ActionButtonDpadUp
31 | ActionButtonDpadDown
32 | ActionButtonDpadLeft
33 | ActionButtonDpadRight
34 |
35 | ActionButtonLeftStickPress
36 | ActionButtonRightStickPress
37 |
38 | // for synthetic events
39 | ActionButtonSynth1
40 | // for synthetic events
41 | ActionButtonSynth2
42 | // for synthetic events
43 | ActionButtonSynth3
44 | // for synthetic events
45 | ActionButtonSynth4
46 |
47 | ActionAxisLX
48 | ActionAxisLY
49 |
50 | ActionAxisRX
51 | ActionAxisRY
52 |
53 | ActionLast
54 |
55 | ActionButtonStart = ActionButtonA
56 | ActionButtonLast = ActionAxisLX
57 |
58 | ActionAxisStart = ActionAxisLX
59 | ActionAxisLast = ActionLast
60 | )
61 |
62 | func (a Action) isButton() bool {
63 | return ActionButtonStart <= a && a < ActionButtonLast
64 | }
65 |
66 | func (a Action) isAxis() bool {
67 | return ActionAxisStart <= a && a < ActionAxisLast
68 | }
69 |
70 | type Event struct {
71 | Timestamp time.Time
72 | Action Action
73 | Value float64
74 | }
75 |
76 | func (ev *Event) pressed() bool {
77 | return ev.Value == 1
78 | }
79 |
80 | func NewEventFromAction(a Action, value float64) Event {
81 | return Event{
82 | Timestamp: time.Now(),
83 | Action: a,
84 | Value: value,
85 | }
86 | }
87 |
88 | type Consumer func(ev *Event)
89 |
90 | type Worker interface {
91 | io.Closer
92 | Run()
93 | }
94 |
95 | func BoolToValue(pressed bool) float64 {
96 | if pressed {
97 | return 1
98 | }
99 | return 0
100 | }
101 |
102 | func ValueToBool(v float64) bool {
103 | return v == 1
104 | }
105 |
--------------------------------------------------------------------------------
/nscontroller/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/omakoto/raspberry-switch-control/nscontroller
2 |
3 | go 1.23
4 |
5 | toolchain go1.23.0
6 |
7 | require (
8 | github.com/omakoto/go-common v0.0.0-20250106043038-04d11d1e6ee4
9 | github.com/pborman/getopt v0.0.0-20190409184431-ee0cd42419d3
10 | golang.org/x/sys v0.24.0
11 | )
12 |
13 | require github.com/davecgh/go-spew v1.1.1 // indirect
14 |
--------------------------------------------------------------------------------
/nscontroller/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/omakoto/go-common v0.0.0-20250106012551-bd15a26150cb h1:tCyR3r2UQhNSW8Qb4Udr8urd3xRpQ6f9uyyT4Om7zNk=
4 | github.com/omakoto/go-common v0.0.0-20250106012551-bd15a26150cb/go.mod h1:79jtLB8yi647+nptKL2Zf2y6zhJAT1ta16hdzi+3RLw=
5 | github.com/omakoto/go-common v0.0.0-20250106043038-04d11d1e6ee4 h1:I1EF105AHqR4kOBHoNnqV+MbuXZKekjvL31a2dZMPsY=
6 | github.com/omakoto/go-common v0.0.0-20250106043038-04d11d1e6ee4/go.mod h1:79jtLB8yi647+nptKL2Zf2y6zhJAT1ta16hdzi+3RLw=
7 | github.com/pborman/getopt v0.0.0-20190409184431-ee0cd42419d3 h1:YtFkrqsMEj7YqpIhRteVxJxCeC3jJBieuLr0d4C4rSA=
8 | github.com/pborman/getopt v0.0.0-20190409184431-ee0cd42419d3/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
9 | golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
10 | golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
11 |
--------------------------------------------------------------------------------
/nscontroller/js/js_linux.go:
--------------------------------------------------------------------------------
1 | //go:build linux
2 |
3 | // Package js is a simple API to interact with the joystick (on Linux).
4 | package js
5 |
6 | // Based on: https://gist.githubusercontent.com/rdb/8864666/raw/516178252bbe1cfe8067145b11223ee54c5d9698/js_linux.py
7 | // API reference: https://www.kernel.org/doc/Documentation/input/joystick-api.txt
8 |
9 | import (
10 | "bytes"
11 | "encoding/binary"
12 | "fmt"
13 | "io"
14 | "os"
15 | "time"
16 | "unsafe"
17 |
18 | "github.com/omakoto/go-common/src/common"
19 | "golang.org/x/sys/unix"
20 | )
21 |
22 | // TODO Introduce constants
23 |
24 | /**
25 | Button layout: Pro controller
26 | X
27 | Y A
28 | B
29 |
30 | Button layout: X-box one controller
31 | Y
32 | X B
33 | A
34 | */
35 |
36 | var axisNameMap = map[int]string{
37 | 0x00: "x", // switch/xbox L-stick
38 | 0x01: "y", // switch/xbox L-stick
39 | 0x02: "z", // xbox L2 [-1..1]
40 | 0x03: "rx", // switch/xbox R-stick
41 | 0x04: "ry", // switch/xbox R-stick
42 | 0x05: "rz", // xbox R2 [-1...1]
43 | 0x06: "trottle",
44 | 0x07: "rudder",
45 | 0x08: "wheel",
46 | 0x09: "gas",
47 | 0x0a: "brake",
48 | 0x10: "hat0x", // switch/xbox D-pad
49 | 0x11: "hat0y", // switch/xbox D-pad
50 | 0x12: "hat1x",
51 | 0x13: "hat1y",
52 | 0x14: "hat2x",
53 | 0x15: "hat2y",
54 | 0x16: "hat3x",
55 | 0x17: "hat3y",
56 | 0x18: "pressure",
57 | 0x19: "distance",
58 | 0x1a: "tilt_x",
59 | 0x1b: "tilt_y",
60 | 0x1c: "tool_width",
61 | 0x20: "volume",
62 | 0x28: "misc",
63 | }
64 |
65 | var buttonNameMap = map[int]string{
66 | 0x120: "trigger",
67 | 0x121: "thumb",
68 | 0x122: "thumb2",
69 | 0x123: "top",
70 | 0x124: "top2",
71 | 0x125: "pinkie",
72 | 0x126: "base",
73 | 0x127: "base2",
74 | 0x128: "base3",
75 | 0x129: "base4",
76 | 0x12a: "base5",
77 | 0x12b: "base6",
78 | 0x12f: "dead",
79 | 0x130: "a", // switch B / xbox A
80 | 0x131: "b", // switch A / xbox B
81 | 0x132: "c",
82 | 0x133: "x", // switch X / xbox X
83 | 0x134: "y", // switch Y / xbox Y
84 | 0x135: "z", // switch Capture
85 | 0x136: "tl", // switch L / xbox L
86 | 0x137: "tr", // switch R / xbox R
87 | 0x138: "tl2", // switch LZ
88 | 0x139: "tr2", // switch RZ
89 | 0x13a: "select", // switch - / xbox select
90 | 0x13b: "start", // switch + / xbox start
91 | 0x13c: "mode", // switch Home / xbox center
92 | 0x13d: "thumbl", // switch / xbox left stick press
93 | 0x13e: "thumbr", // switch / xbox right stick press
94 |
95 | 0x220: "dpad_up",
96 | 0x221: "dpad_down",
97 | 0x222: "dpad_left",
98 | 0x223: "dpad_right",
99 |
100 | // XBox 360 controller uses these codes.
101 | 0x2c0: "dpad_left",
102 | 0x2c1: "dpad_right",
103 | 0x2c2: "dpad_up",
104 | 0x2c3: "dpad_down",
105 | }
106 |
107 | // Element represents a single axis or button.
108 | type Element struct {
109 | // Number is the number given to the axis/button.
110 | Number int
111 | // Name is the name of the axis/button.
112 | Name string
113 | // Name is the last known value of the axis/button in the range of [-1..1].
114 | Value float64
115 | // Name is the initial value of the axis/button in the range of [-1..1]. (NOT IMPLEMENTED YET)
116 | InitialValue float64
117 | }
118 |
119 | func (e *Element) setInitialValue() {
120 | e.InitialValue = e.Value
121 | }
122 |
123 | // Js represents a joystick input device.
124 | type Js struct {
125 | DevicePath string
126 | Name string
127 | NumAxes int
128 | NumButtons int
129 | Axes []Element
130 | Buttons []Element
131 | in io.ReadCloser
132 | }
133 |
134 | // JoystickEvent is a single joystick event.
135 | type JoystickEvent struct {
136 | Timestamp time.Time
137 | Value float64
138 | Element *Element
139 | }
140 |
141 | const (
142 | jsEventButton = 0x01 // button pressed/released
143 | jsEventAxis = 0x02 // joystick moved
144 | jsEventInit = 0x80 // initial state of device
145 |
146 | jsiocgnameBase = 0x80006a13
147 | jsiocgaxes = 0x80016a11
148 | jsiocgbuttons = 0x80016a12
149 | jsiocgaxmap = 0x80406a32
150 | jsiocgbtnmap = 0x80406a34
151 | )
152 |
153 | func jsiocgname(length int) uintptr {
154 | return uintptr(jsiocgnameBase) + uintptr(0x10000)*uintptr(length)
155 | }
156 |
157 | // NewJs creates a new Js instance with the given device file.
158 | func NewJs(device string) (*Js, error) {
159 | common.Debugf("Opening %s ...", device)
160 | in, err := os.OpenFile(device, os.O_RDONLY, 0)
161 | if err != nil {
162 | return nil, fmt.Errorf("unable to open %#v: %w", device, err)
163 | }
164 |
165 | js := &Js{DevicePath: device, in: in}
166 |
167 | // Get num axes and buttons.
168 | js.NumAxes, err = unix.IoctlGetInt(int(in.Fd()), jsiocgaxes)
169 | if err != nil {
170 | return nil, fmt.Errorf("unable to get number of axes of %#v: %w", device, err)
171 | }
172 | js.NumButtons, err = unix.IoctlGetInt(int(in.Fd()), jsiocgbuttons)
173 | if err != nil {
174 | return nil, fmt.Errorf("unable to get number of buttons of %#v: %w", device, err)
175 | }
176 |
177 | // Get device name.
178 | nameBuf := make([]byte, 256)
179 | _, _, errno := unix.Syscall(unix.SYS_IOCTL, in.Fd(), jsiocgname(len(nameBuf)), uintptr(unsafe.Pointer(&nameBuf[0])))
180 | if errno != 0 {
181 | return nil, fmt.Errorf("unable to get device name of %#v: %w", device, errno)
182 | }
183 | js.Name = string(bytes.TrimRight(nameBuf, "\000"))
184 |
185 | // Get the axis names.
186 | axisCodes := make([]byte, js.NumAxes)
187 | _, _, errno = unix.Syscall(unix.SYS_IOCTL, in.Fd(), uintptr(jsiocgaxmap), uintptr(unsafe.Pointer(&axisCodes[0])))
188 | if errno != 0 {
189 | return nil, fmt.Errorf("unable to get axis map of %#v: %w", device, errno)
190 | }
191 | js.Axes = make([]Element, js.NumAxes)
192 | for i, v := range axisCodes {
193 | js.Axes[i].Number = int(v)
194 | name, found := axisNameMap[int(v)]
195 | if !found {
196 | name = fmt.Sprintf("unknown:0x%x", v)
197 | }
198 | js.Axes[i].Name = name
199 | }
200 |
201 | // Get the button names.
202 | buttonCodes := make([]uint16, js.NumButtons)
203 | _, _, errno = unix.Syscall(unix.SYS_IOCTL, in.Fd(), uintptr(jsiocgbtnmap), uintptr(unsafe.Pointer(&buttonCodes[0])))
204 | if errno != 0 {
205 | return nil, fmt.Errorf("unable to get button map of %#v: %w", device, errno)
206 | }
207 | js.Buttons = make([]Element, js.NumButtons)
208 | for i, v := range buttonCodes {
209 | js.Buttons[i].Number = int(v)
210 | name, found := buttonNameMap[int(v)]
211 | if !found {
212 | name = fmt.Sprintf("unknown:0x%x", v)
213 | }
214 | js.Buttons[i].Name = name
215 | }
216 |
217 | //// Read the initial state. -> not working
218 | //common.Debug("Reading initial state...")
219 | //timeout := unix.Timeval{}
220 | //timeout.Sec = 1
221 | //for {
222 | // fdSet := &unix.FdSet{}
223 | // fdSet.Bits[0] = 1 << in.Fd()
224 | // s, err := unix.Select(1, fdSet, nil, nil, &timeout)
225 | // common.Check(err, "select")
226 | // common.Debugf("select returned %d", s)
227 | // if s < 1 {
228 | // break
229 | // }
230 | // _, err = js.Read()
231 | // if err != nil {
232 | // return nil, err
233 | // }
234 | //}
235 | js.setInitialValues()
236 |
237 | common.Debugf("%s ready to read", js.DevicePath)
238 | common.Dump("Js:", &js)
239 |
240 | return js, nil
241 | }
242 |
243 | func (js *Js) setInitialValues() {
244 | for i := 0; i < len(js.Axes); i++ {
245 | js.Axes[i].setInitialValue()
246 | }
247 | for i := 0; i < len(js.Buttons); i++ {
248 | js.Buttons[i].setInitialValue()
249 | }
250 | }
251 |
252 | func (js *Js) Close() error {
253 | if js.in == nil {
254 | return nil
255 | }
256 | err := js.in.Close()
257 | js.in = nil
258 | return err
259 | }
260 |
261 | // osJsEvent is a single event from the joystick device.
262 | type osJsEvent struct {
263 | // Time is event timestamp in milliseconds
264 | Time uint32
265 | // Value is: fix an axis, [-32767 .. 32767]. for a button, 1 (pressed) or 0 (released).
266 | Value int16
267 | // EventType is a bit field of JsEventXxx values.
268 | EventType uint8
269 | // Number is an axis or button number, 0-based.
270 | Number uint8
271 | }
272 |
273 | func (js *Js) Read() (JoystickEvent, error) {
274 | event := JoystickEvent{}
275 |
276 | // Read the OS event.
277 | var oev osJsEvent
278 | err := binary.Read(js.in, binary.LittleEndian, &oev)
279 | if err == io.EOF {
280 | return event, err
281 | }
282 | if err != nil {
283 | return event, fmt.Errorf("unable to read from %#v: %w", js.DevicePath, err)
284 | }
285 | common.Dump("OsEvent:", &oev)
286 |
287 | // Convert to the result.
288 | event.Timestamp = time.Now()
289 |
290 | switch oev.EventType &^ jsEventInit {
291 | case jsEventAxis:
292 | event.Element = &js.Axes[oev.Number]
293 | event.Value = float64(oev.Value) / 32767.0
294 | case jsEventButton:
295 | event.Element = &js.Buttons[oev.Number]
296 | event.Value = 0
297 | if oev.Value != 0 {
298 | event.Value = 1
299 | }
300 | }
301 | event.Element.Value = event.Value
302 | common.Dump("Event:", &event)
303 |
304 | return event, nil
305 | }
306 |
--------------------------------------------------------------------------------
/nscontroller/jsinput.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import (
4 | "github.com/omakoto/go-common/src/common"
5 | "github.com/omakoto/raspberry-switch-control/nscontroller/js"
6 | "io"
7 | )
8 |
9 | type JoystickDispatcher func(ev *js.JoystickEvent, con Consumer)
10 |
11 | type JoystickInput struct {
12 | js *js.Js
13 | dispatcher JoystickDispatcher
14 | next Consumer
15 | }
16 |
17 | var _ Worker = (*JoystickInput)(nil)
18 |
19 | func NewJoystickInput(js *js.Js, dispatcher JoystickDispatcher, next Consumer) (*JoystickInput, error) {
20 | return &JoystickInput{js, dispatcher, next}, nil
21 | }
22 |
23 | func (j *JoystickInput) Close() error {
24 | return j.js.Close()
25 | }
26 |
27 | func (j *JoystickInput) Run() {
28 | go func() {
29 | for {
30 | ev, err := j.js.Read()
31 | if err == io.EOF {
32 | common.Debug("Joystick closing")
33 | return
34 | }
35 | common.Checke(err)
36 | common.Debugf("Joystick input=%x", ev.Element.Number)
37 |
38 | j.dispatcher(&ev, j.next)
39 | }
40 | }()
41 | }
42 |
--------------------------------------------------------------------------------
/nscontroller/nscon.go:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: GPL-3.0-only
2 |
3 | // Forked from https://github.com/mzyy94/nscon/blob/master/nscon.go
4 |
5 | package nscontroller
6 |
7 | import (
8 | "encoding/hex"
9 | "errors"
10 | "fmt"
11 | "io"
12 | "log"
13 | "math"
14 | "os"
15 | "sync"
16 | "time"
17 |
18 | "github.com/omakoto/go-common/src/common"
19 | )
20 |
21 | var SPI_ROM_DATA = map[byte][]byte{
22 | 0x60: {
23 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
24 | 0xff, 0xff, 0x03, 0xa0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0xff, 0xff, 0xff, 0xff,
25 | 0xf0, 0xff, 0x89, 0x00, 0xf0, 0x01, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0xf9, 0xff, 0x06, 0x00,
26 | 0x09, 0x00, 0xe7, 0x3b, 0xe7, 0x3b, 0xe7, 0x3b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xba, 0x15, 0x62,
27 | 0x11, 0xb8, 0x7f, 0x29, 0x06, 0x5b, 0xff, 0xe7, 0x7e, 0x0e, 0x36, 0x56, 0x9e, 0x85, 0x60, 0xff,
28 | 0x32, 0x32, 0x32, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
29 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
30 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
31 | 0x50, 0xfd, 0x00, 0x00, 0xc6, 0x0f, 0x0f, 0x30, 0x61, 0x96, 0x30, 0xf3, 0xd4, 0x14, 0x54, 0x41,
32 | 0x15, 0x54, 0xc7, 0x79, 0x9c, 0x33, 0x36, 0x63, 0x0f, 0x30, 0x61, 0x96, 0x30, 0xf3, 0xd4, 0x14,
33 | 0x54, 0x41, 0x15, 0x54, 0xc7, 0x79, 0x9c, 0x33, 0x36, 0x63, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
34 | },
35 | 0x80: {
36 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
38 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xb2, 0xa1, 0xbe, 0xff, 0x3e, 0x00, 0xf0, 0x01, 0x00, 0x40,
39 | 0x00, 0x40, 0x00, 0x40, 0xfe, 0xff, 0xfe, 0xff, 0x08, 0x00, 0xe7, 0x3b, 0xe7, 0x3b, 0xe7, 0x3b,
40 | },
41 | }
42 |
43 | type ControllerInput struct {
44 | Dpad struct {
45 | Up, Down, Left, Right uint8
46 | }
47 | Button struct {
48 | A, B, X, Y, R, ZR, L, ZL uint8
49 | Home, Plus, Minus, Capture uint8
50 | }
51 | Stick struct {
52 | Left, Right struct {
53 | X, Y float64
54 | Press uint8
55 | }
56 | }
57 | }
58 |
59 | type Controller struct {
60 | mu sync.Mutex
61 | path string
62 | fp *os.File
63 | count uint8
64 | stopCounter chan struct{}
65 | stopInput chan struct{}
66 | stopCommunicate chan struct{}
67 | Input ControllerInput
68 | currentInput ControllerInput
69 | tickInterval time.Duration
70 | LogLevel int
71 | }
72 |
73 | // NewController creates an instance of Controller with device path
74 | func NewController(path string, tickInterval time.Duration) *Controller {
75 | return &Controller{
76 | path: path,
77 | tickInterval: tickInterval,
78 | }
79 | }
80 |
81 | func (c *Controller) Path() string {
82 | return c.path
83 | }
84 |
85 | // Close closes all channel and device file
86 | func (c *Controller) Close() {
87 | if c.fp == nil {
88 | if c.LogLevel > 0 {
89 | log.Println("Already closed.")
90 | }
91 | return
92 | }
93 | close(c.stopCounter)
94 | close(c.stopInput)
95 | close(c.stopCommunicate)
96 | // TODO: Send close magic packet
97 | c.fp.Close()
98 | c.fp = nil
99 | }
100 |
101 | func (c *Controller) startCounter() {
102 | ticker := time.NewTicker(c.tickInterval)
103 |
104 | go func() {
105 | defer ticker.Stop()
106 | for {
107 | select {
108 | case <-ticker.C:
109 | c.count++
110 | case <-c.stopCounter:
111 | return
112 | }
113 | }
114 | }()
115 | }
116 |
117 | func packShorts(short1, short2 uint16) (data []byte) {
118 | data = make([]byte, 3)
119 | data[0] = uint8(short1 & 0xff)
120 | data[1] = uint8(((short2 << 4) & 0xf0) | ((short1 >> 8) & 0x0f))
121 | data[2] = uint8((short2 >> 4) & 0xff)
122 | return data
123 | }
124 |
125 | func bitInput(input, offset uint8) uint8 {
126 | if input == 0 {
127 | return 0
128 | }
129 | return 1 << offset
130 | }
131 |
132 | func (c *Controller) Send() {
133 | c.mu.Lock()
134 | c.currentInput = c.Input
135 | c.mu.Unlock()
136 | }
137 |
138 | func (c *Controller) Dump() {
139 | c.mu.Lock()
140 | common.Dump("State:", c.Input)
141 | c.mu.Unlock()
142 | }
143 |
144 | func (c *Controller) getInputBuffer() []byte {
145 | c.mu.Lock()
146 | ci := c.currentInput
147 | left := bitInput(ci.Button.Y, 0) |
148 | bitInput(ci.Button.X, 1) |
149 | bitInput(ci.Button.B, 2) |
150 | bitInput(ci.Button.A, 3) |
151 | bitInput(ci.Button.R, 6) |
152 | bitInput(ci.Button.ZR, 7)
153 |
154 | center := bitInput(ci.Button.Minus, 0) |
155 | bitInput(ci.Button.Plus, 1) |
156 | bitInput(ci.Stick.Right.Press, 2) |
157 | bitInput(ci.Stick.Left.Press, 3) |
158 | bitInput(ci.Button.Home, 4) |
159 | bitInput(ci.Button.Capture, 5)
160 |
161 | right := bitInput(ci.Dpad.Down, 0) |
162 | bitInput(ci.Dpad.Up, 1) |
163 | bitInput(ci.Dpad.Right, 2) |
164 | bitInput(ci.Dpad.Left, 3) |
165 | bitInput(ci.Button.L, 6) |
166 | bitInput(ci.Button.ZL, 7)
167 |
168 | lx := uint16(math.Round((1 + ci.Stick.Left.X) * 2047.5))
169 | ly := uint16(math.Round((1 + ci.Stick.Left.Y) * 2047.5))
170 | rx := uint16(math.Round((1 + ci.Stick.Right.X) * 2047.5))
171 | ry := uint16(math.Round((1 + ci.Stick.Right.Y) * 2047.5))
172 |
173 | c.mu.Unlock()
174 |
175 | leftStick := packShorts(lx, ly)
176 | rightStick := packShorts(rx, ry)
177 |
178 | return []byte{0x81, left, center, right, leftStick[0], leftStick[1],
179 | leftStick[2], rightStick[0], rightStick[1], rightStick[2], 0x00}
180 | }
181 |
182 | func (c *Controller) startInputReport() {
183 | ticker := time.NewTicker(c.tickInterval)
184 | fmt.Print(".")
185 |
186 | go func() {
187 | defer ticker.Stop()
188 | for {
189 | select {
190 | case <-ticker.C:
191 | fmt.Print(".")
192 | c.write(0x30, c.count, c.getInputBuffer())
193 | case <-c.stopInput:
194 | return
195 | }
196 | }
197 | }()
198 | }
199 |
200 | func (c *Controller) uart(ack bool, subCmd byte, data []byte) {
201 | ackByte := byte(0x00)
202 | if ack {
203 | ackByte = 0x80
204 | if len(data) > 0 {
205 | ackByte |= subCmd
206 | }
207 | }
208 | c.write(0x21, c.count, append(append(c.getInputBuffer(), []byte{ackByte, subCmd}...), data...))
209 | }
210 |
211 | func (c *Controller) write(ack byte, cmd byte, buf []byte) {
212 | data := append(append([]byte{ack, cmd}, buf...), make([]byte, 62-len(buf))...)
213 | c.fp.Write(data)
214 | if c.LogLevel > 0 {
215 | if ack == 0x30 {
216 | if c.LogLevel > 2 {
217 | log.Println("write:", hex.EncodeToString(data))
218 | }
219 | } else {
220 | log.Println("write:", hex.EncodeToString(data))
221 | }
222 | }
223 | }
224 |
225 | // Connect begins connection to device
226 | func (c *Controller) Connect() error {
227 | var err error
228 | if c.fp != nil {
229 | return errors.New("already connected")
230 | }
231 |
232 | c.fp, err = os.OpenFile(c.path, os.O_RDWR|os.O_SYNC, os.ModeDevice)
233 | if err != nil {
234 | return err
235 | }
236 |
237 | c.stopCounter = make(chan struct{})
238 | c.stopInput = make(chan struct{})
239 | c.stopCommunicate = make(chan struct{})
240 |
241 | c.startCounter()
242 |
243 | // Reset magic packet
244 | c.write(0x81, 0x03, []byte{})
245 | c.write(0x81, 0x01, []byte{0x00, 0x03})
246 |
247 | go func() {
248 | buf := make([]byte, 128)
249 |
250 | for {
251 | select {
252 | case <-c.stopCommunicate:
253 | return
254 | default:
255 | }
256 |
257 | n, err := c.fp.Read(buf)
258 | if err == io.EOF {
259 | if c.LogLevel > 0 {
260 | log.Println("EOF")
261 | }
262 | break
263 | }
264 | if c.LogLevel > 0 {
265 | log.Println("read:", hex.EncodeToString(buf[:n]), err)
266 | }
267 | switch buf[0] {
268 | case 0x80:
269 | switch buf[1] {
270 | case 0x01:
271 | c.write(0x81, buf[1], []byte{0x00, 0x03, 0x00, 0x00, 0x5e, 0x00, 0x53, 0x5e})
272 | case 0x02, 0x03:
273 | c.write(0x81, buf[1], []byte{})
274 | case 0x04:
275 | c.startInputReport()
276 | case 0x05:
277 | close(c.stopInput)
278 | c.stopInput = make(chan struct{})
279 | }
280 | case 0x01:
281 | switch buf[10] {
282 | case 0x01: // Bluetooth manual pairing
283 | c.uart(true, buf[10], []byte{0x03, 0x01})
284 | case 0x02: // Request device info
285 | c.uart(true, buf[10], []byte{0x03, 0x48, 0x03,
286 | 0x02, 0x5e, 0x53, 0x00, 0x5e, 0x00, 0x00, 0x03, 0x01})
287 | case 0x03, 0x08, 0x30, 0x38, 0x40, 0x41, 0x48: // Empty response
288 | c.uart(true, buf[10], []byte{})
289 | case 0x04: // Empty response
290 | c.uart(true, buf[10], []byte{})
291 | case 0x10: // Read SPI ROM
292 | data, ok := SPI_ROM_DATA[buf[12]]
293 | if ok {
294 | c.uart(true, buf[10], append(buf[11:16],
295 | data[buf[11]:buf[11]+buf[15]]...))
296 | if c.LogLevel > 1 {
297 | log.Printf("Read SPI address: %02x%02x[%d] %v\n",
298 | buf[12], buf[11], buf[15], data[buf[11]:buf[11]+buf[15]])
299 | }
300 | } else {
301 | c.uart(false, buf[10], []byte{})
302 | if c.LogLevel > 1 {
303 | log.Printf("Unknown SPI address: %02x[%d]\n", buf[12], buf[15])
304 | }
305 | }
306 | case 0x21:
307 | // FIXME: Check ack value
308 | c.uart(true, buf[10], []byte{0x01, 0x00, 0xff, 0x00, 0x03, 0x00, 0x05, 0x01})
309 | default:
310 | if c.LogLevel > 1 {
311 | log.Println("UART unknown request", buf[10], buf)
312 | }
313 | }
314 |
315 | case 0x00:
316 | case 0x10:
317 | default:
318 | if c.LogLevel > 1 {
319 | log.Println("unknown request", buf[0])
320 | }
321 | }
322 | }
323 | }()
324 |
325 | return nil
326 | }
327 |
--------------------------------------------------------------------------------
/nscontroller/nsprojoystick.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import "github.com/omakoto/raspberry-switch-control/nscontroller/js"
4 |
5 | // NSProJoystickDispatcher is a dispatcher for the Switch Pro controller.
6 | func NSProJoystickDispatcher(jev *js.JoystickEvent, con Consumer) {
7 | var action Action = ActionNone
8 |
9 | value := jev.Value
10 |
11 | switch jev.Element.Number {
12 | case 0x00: // "x", // switch/xbox L-stick
13 | action = ActionAxisLX
14 | case 0x01: // "y", // switch/xbox L-stick
15 | action = ActionAxisLY
16 | case 0x03: // "rx", // switch/xbox R-stick
17 | action = ActionAxisRX
18 | case 0x04: // "ry", // switch/xbox R-stick
19 | action = ActionAxisRY
20 |
21 | case 0x130: // "a", // switch B / xbox A
22 | action = ActionButtonB
23 | case 0x131: // "b", // switch A / xbox B
24 | action = ActionButtonA
25 | case 0x133: // "x", // switch Y / xbox X
26 | action = ActionButtonX
27 | case 0x134: // "y", // switch X / xbox Y
28 | action = ActionButtonY
29 | case 0x135: // "z"
30 | action = ActionButtonCapture
31 |
32 | case 0x136: // "tl", // switch L / xbox L
33 | action = ActionButtonL
34 | case 0x137: // "tr", // switch R / xbox R
35 | action = ActionButtonR
36 |
37 | case 0x138: // "tl2", // switch LZ
38 | action = ActionButtonLZ
39 | case 0x139: // "tr2", // switch RZ
40 | action = ActionButtonRZ
41 |
42 | case 0x13a: // "select", // switch - / xbox select
43 | action = ActionButtonMinus
44 | case 0x13b: // "start", // switch + / xbox start
45 | action = ActionButtonPlus
46 | case 0x13c: // "mode", // switch Home / xbox center
47 | action = ActionButtonHome
48 |
49 | case 0x13d: // "thumbl", // switch / xbox left stick press
50 | action = ActionButtonLeftStickPress
51 | case 0x13e: // "thumbr", // switch / xbox right stick press
52 | action = ActionButtonRightStickPress
53 | }
54 |
55 | if action != ActionNone {
56 | con(&Event{jev.Timestamp, action, value})
57 | return
58 | }
59 |
60 | // D-pad requires a special handling
61 | switch jev.Element.Number {
62 | case 0x10: // "hat0x", // switch/xbox D-pad
63 | left := 0.0
64 | right := 0.0
65 | if value < 0 {
66 | left = 1
67 | right = 0
68 | } else if value > 0 {
69 | left = 0
70 | right = 1
71 | }
72 | con(&Event{jev.Timestamp, ActionButtonDpadLeft, left})
73 | con(&Event{jev.Timestamp, ActionButtonDpadRight, right})
74 | case 0x11: // "hat0y", // switch/xbox D-pad
75 | up := 0.0
76 | down := 0.0
77 | if value < 0 {
78 | up = 1
79 | down = 0
80 | } else if value > 0 {
81 | up = 0
82 | down = 1
83 | }
84 | con(&Event{jev.Timestamp, ActionButtonDpadUp, up})
85 | con(&Event{jev.Timestamp, ActionButtonDpadDown, down})
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/nscontroller/psjoystick.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import "github.com/omakoto/raspberry-switch-control/nscontroller/js"
4 |
5 | // PsJoystickDispatcher is a dispatcher for the PS controller. (Only tested with a PS4 controller.)
6 | func PsJoystickDispatcher(jev *js.JoystickEvent, con Consumer) {
7 | var action Action = ActionNone
8 |
9 | value := jev.Value
10 |
11 | switch jev.Element.Number {
12 | case 0x00: // "x"
13 | action = ActionAxisLX
14 | case 0x01: // "y"
15 | action = ActionAxisLY
16 | case 0x03: // "rx"
17 | action = ActionAxisRX
18 | case 0x04: // "ry"
19 | action = ActionAxisRY
20 |
21 | case 0x130: // "a"
22 | action = ActionButtonB
23 | case 0x131: // "b"
24 | action = ActionButtonA
25 | case 0x133: // "x"
26 | action = ActionButtonX
27 | case 0x134: // "y"
28 | action = ActionButtonY
29 |
30 | case 0x136: // "tl"
31 | action = ActionButtonL
32 | case 0x137: // "tr"
33 | action = ActionButtonR
34 | case 0x138: // "tl2"
35 | action = ActionButtonLZ
36 | case 0x139: // "tr2"
37 | action = ActionButtonRZ
38 |
39 | case 0x13a: // "select", // switch - / xbox select
40 | action = ActionButtonMinus
41 | case 0x13b: // "start", // switch + / xbox start
42 | action = ActionButtonPlus
43 | case 0x13c: // "mode", // switch Home / xbox center
44 | action = ActionButtonHome
45 |
46 | case 0x13d: // "thumbl", // switch / xbox left stick press
47 | action = ActionButtonLeftStickPress
48 | case 0x13e: // "thumbr", // switch / xbox right stick press
49 | action = ActionButtonRightStickPress
50 | }
51 | if action != ActionNone {
52 | con(&Event{jev.Timestamp, action, value})
53 | return
54 | }
55 |
56 | // D-pad requires a special handling
57 | switch jev.Element.Number {
58 | case 0x10: // "hat0x", // switch/xbox D-pad
59 | left := 0.0
60 | right := 0.0
61 | if value < 0 {
62 | left = 1
63 | right = 0
64 | } else if value > 0 {
65 | left = 0
66 | right = 1
67 | }
68 | con(&Event{jev.Timestamp, ActionButtonDpadLeft, left})
69 | con(&Event{jev.Timestamp, ActionButtonDpadRight, right})
70 | case 0x11: // "hat0y", // switch/xbox D-pad
71 | up := 0.0
72 | down := 0.0
73 | if value < 0 {
74 | up = 1
75 | down = 0
76 | } else if value > 0 {
77 | up = 0
78 | down = 1
79 | }
80 | con(&Event{jev.Timestamp, ActionButtonDpadUp, up})
81 | con(&Event{jev.Timestamp, ActionButtonDpadDown, down})
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/nscontroller/scripts/switch-controller-gadget:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copied from:
4 | # https://gist.github.com/mzyy94/60ae253a45e2759451789a117c59acf9#file-add_procon_gadget-sh
5 |
6 | device=/dev/hidg0
7 |
8 | if (( $(id -u) != 0 )) ; then
9 | echo "Error: the script needs to be run as root" 1>&2
10 | exit 1
11 | fi
12 |
13 | if [[ -e $device ]]; then
14 | echo "Device $device already exists" 1>&2
15 | exit 0
16 | fi
17 |
18 | set -e
19 |
20 | cd /sys/kernel/config/usb_gadget/
21 | mkdir -p procon
22 | cd procon
23 | echo 0x057e > idVendor
24 | echo 0x2009 > idProduct
25 | echo 0x0200 > bcdDevice
26 | echo 0x0200 > bcdUSB
27 | echo 0x00 > bDeviceClass
28 | echo 0x00 > bDeviceSubClass
29 | echo 0x00 > bDeviceProtocol
30 |
31 | mkdir -p strings/0x409
32 | echo "000000000001" > strings/0x409/serialnumber
33 | echo "Nintendo Co., Ltd." > strings/0x409/manufacturer
34 | echo "Pro Controller" > strings/0x409/product
35 |
36 | mkdir -p configs/c.1/strings/0x409
37 | echo "Nintendo Switch Pro Controller" > configs/c.1/strings/0x409/configuration
38 | echo 500 > configs/c.1/MaxPower
39 | echo 0xa0 > configs/c.1/bmAttributes
40 |
41 | mkdir -p functions/hid.usb0
42 | echo 0 > functions/hid.usb0/protocol
43 | echo 0 > functions/hid.usb0/subclass
44 | echo 64 > functions/hid.usb0/report_length
45 | echo 050115000904A1018530050105091901290A150025017501950A5500650081020509190B290E150025017501950481027501950281030B01000100A1000B300001000B310001000B320001000B35000100150027FFFF0000751095048102C00B39000100150025073500463B0165147504950181020509190F2912150025017501950481027508953481030600FF852109017508953F8103858109027508953F8103850109037508953F9183851009047508953F9183858009057508953F9183858209067508953F9183C0 | xxd -r -ps > functions/hid.usb0/report_desc
46 |
47 | ln -s functions/hid.usb0 configs/c.1/
48 |
49 | ls /sys/class/udc > UDC # Does it synchronously create the device file??
50 |
51 | chmod 666 $device
52 |
53 | ls -l $device
54 |
--------------------------------------------------------------------------------
/nscontroller/streaminput.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import (
4 | "bufio"
5 | "io"
6 | "regexp"
7 | "strings"
8 | "sync"
9 | "time"
10 |
11 | "github.com/omakoto/go-common/src/common"
12 | )
13 |
14 | const streamInputOffDelay = time.Millisecond * 60
15 |
16 | type StreamInput struct {
17 | in io.ReadCloser
18 | next Consumer
19 | wg *sync.WaitGroup
20 | }
21 |
22 | var _ Worker = (*StreamInput)(nil)
23 |
24 | func NewStreamInput(in io.ReadCloser, next Consumer) (*StreamInput, error) {
25 | return &StreamInput{
26 | in,
27 | next,
28 | &sync.WaitGroup{},
29 | }, nil
30 | }
31 |
32 | func (t *StreamInput) Close() error {
33 | return t.in.Close()
34 | }
35 |
36 | func (t *StreamInput) press(a Action) {
37 | now := time.Now()
38 | on := Event{
39 | Timestamp: now,
40 | Action: a,
41 | Value: 1,
42 | }
43 | t.next(&on)
44 | go (func() {
45 | off := Event{
46 | Timestamp: now.Add(streamInputOffDelay),
47 | Action: a,
48 | Value: 0,
49 | }
50 | select {
51 | case <-time.After(streamInputOffDelay):
52 | t.next(&off)
53 | }
54 | })()
55 | }
56 |
57 | func (t *StreamInput) Run() {
58 | comment_re := regexp.MustCompile(`#.*`)
59 |
60 | t.wg.Add(1)
61 | go func() {
62 | defer t.wg.Done()
63 | scanner := bufio.NewScanner(t.in)
64 | for scanner.Scan() {
65 | in := scanner.Text()
66 | command := strings.TrimSpace(comment_re.ReplaceAllString(in, ""))
67 | switch command {
68 | case "a": // A
69 | t.press(ActionButtonA)
70 | case "b": // B
71 | t.press(ActionButtonB)
72 | case "x": // X
73 | t.press(ActionButtonX)
74 | case "y": // Y
75 | t.press(ActionButtonY)
76 |
77 | case "h": // Home
78 | t.press(ActionButtonHome)
79 | case "c": // Capture
80 | t.press(ActionButtonCapture)
81 |
82 | case "m", "-": // Minus
83 | t.press(ActionButtonMinus)
84 | case "p", "+": // Plus
85 | t.press(ActionButtonPlus)
86 |
87 | case "l1": // L1
88 | t.press(ActionButtonL)
89 | case "l2": // L2
90 | t.press(ActionButtonLZ)
91 | case "r1": // R1
92 | t.press(ActionButtonR)
93 | case "r2": // R2
94 | t.press(ActionButtonRZ)
95 |
96 | case "pu": // D-pad up
97 | t.press(ActionButtonDpadUp)
98 | case "pd": // D-pad down
99 | t.press(ActionButtonDpadDown)
100 | case "pl": // D-pad left
101 | t.press(ActionButtonDpadLeft)
102 | case "pr": // D-pad right
103 | t.press(ActionButtonDpadRight)
104 |
105 | case "pur": // D-pad
106 | t.press(ActionButtonDpadUp)
107 | t.press(ActionButtonDpadRight)
108 | case "pul": // D-pad
109 | t.press(ActionButtonDpadUp)
110 | t.press(ActionButtonDpadLeft)
111 | case "pdr": // D-pad
112 | t.press(ActionButtonDpadDown)
113 | t.press(ActionButtonDpadRight)
114 | case "pdl": // D-pad
115 | t.press(ActionButtonDpadDown)
116 | t.press(ActionButtonDpadLeft)
117 |
118 | case "lp": // Left stick press
119 | t.press(ActionButtonLeftStickPress)
120 | case "rp": // Right stick press
121 | t.press(ActionButtonRightStickPress)
122 |
123 | default:
124 | common.Warnf("Unknown command: %#v\n", command)
125 | continue
126 | }
127 | }
128 | }()
129 | }
130 |
131 | func (t *StreamInput) WaitClose() {
132 | t.wg.Wait()
133 | }
134 |
--------------------------------------------------------------------------------
/nscontroller/utils/sync.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import "sync"
4 |
5 | type Synchronized struct {
6 | Mutex *sync.Mutex
7 | }
8 |
9 | func NewSynchronized() *Synchronized {
10 | return &Synchronized{&sync.Mutex{}}
11 | }
12 |
13 | func (s *Synchronized) Run(f func()) {
14 | s.Mutex.Lock()
15 | defer s.Mutex.Unlock()
16 |
17 | f()
18 | }
19 |
20 | func (s *Synchronized) RunForValue(f func() interface{}) interface{} {
21 | s.Mutex.Lock()
22 | defer s.Mutex.Unlock()
23 |
24 | return f()
25 | }
26 |
--------------------------------------------------------------------------------
/nscontroller/xboxjoystick.go:
--------------------------------------------------------------------------------
1 | package nscontroller
2 |
3 | import "github.com/omakoto/raspberry-switch-control/nscontroller/js"
4 |
5 | const xboxTriggerThreshold = -0.8
6 |
7 | func xboxTriggerToButton(v float64) float64 {
8 | if v < xboxTriggerThreshold {
9 | return 0
10 | }
11 | return 1
12 | }
13 |
14 | // XBoxOneJoystickDispatcher takes an JoystickEvent and dispatches.
15 | func XBoxOneJoystickDispatcher(jev *js.JoystickEvent, con Consumer) {
16 | var action Action = ActionNone
17 |
18 | value := jev.Value
19 |
20 | switch jev.Element.Number {
21 | case 0x00: // "x", // switch/xbox L-stick
22 | action = ActionAxisLX
23 | case 0x01: // "y", // switch/xbox L-stick
24 | action = ActionAxisLY
25 | case 0x03: // "rx", // switch/xbox R-stick
26 | action = ActionAxisRX
27 | case 0x04: // "ry", // switch/xbox R-stick
28 | action = ActionAxisRY
29 |
30 | case 0x130: // "a", // switch B / xbox A
31 | action = ActionButtonB // a<->b swapped
32 | case 0x131: // "b", // switch A / xbox B
33 | action = ActionButtonA // a<->b swapped
34 | case 0x133: // "x", // switch Y / xbox X
35 | action = ActionButtonY // x<->y swapped
36 | case 0x134: // "y", // switch X / xbox Y
37 | action = ActionButtonX // x<->y swapped
38 |
39 | case 0x136: // "tl", // switch L / xbox L
40 | action = ActionButtonL
41 | case 0x137: // "tr", // switch R / xbox R
42 | action = ActionButtonR
43 | case 0x13a: // "select", // switch - / xbox select
44 | action = ActionButtonMinus
45 | case 0x13b: // "start", // switch + / xbox start
46 | action = ActionButtonPlus
47 | case 0x13c: // "mode", // switch Home / xbox center
48 | action = ActionButtonHome
49 |
50 | case 0x13d: // "thumbl", // switch / xbox left stick press
51 | action = ActionButtonLeftStickPress
52 | case 0x13e: // "thumbr", // switch / xbox right stick press
53 | action = ActionButtonRightStickPress
54 |
55 | case 0x02: // "z", // xbox L2 [-1..1]
56 | action = ActionButtonLZ
57 | value = xboxTriggerToButton(value)
58 | case 0x05: // "rz", // xbox R2 [-1...1]
59 | action = ActionButtonRZ
60 | value = xboxTriggerToButton(value)
61 | }
62 | if action != ActionNone {
63 | con(&Event{jev.Timestamp, action, value})
64 | return
65 | }
66 |
67 | // D-pad requires a special handling
68 | switch jev.Element.Number {
69 | case 0x10: // "hat0x", // switch/xbox D-pad
70 | left := 0.0
71 | right := 0.0
72 | if value < 0 {
73 | left = 1
74 | right = 0
75 | } else if value > 0 {
76 | left = 0
77 | right = 1
78 | }
79 | con(&Event{jev.Timestamp, ActionButtonDpadLeft, left})
80 | con(&Event{jev.Timestamp, ActionButtonDpadRight, right})
81 | case 0x11: // "hat0y", // switch/xbox D-pad
82 | up := 0.0
83 | down := 0.0
84 | if value < 0 {
85 | up = 1
86 | down = 0
87 | } else if value > 0 {
88 | up = 0
89 | down = 1
90 | }
91 | con(&Event{jev.Timestamp, ActionButtonDpadUp, up})
92 | con(&Event{jev.Timestamp, ActionButtonDpadDown, down})
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/presubmit.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | cd "${0%/*}/nscontroller/"
6 |
7 | go get -v -t honnef.co/go/tools/cmd/...
8 | go get -v -t golang.org/x/lint/golint
9 |
10 | gofmt -s -d $(find . -type f -name '*.go') |& perl -pe 'END{exit($. > 0 ? 1 : 0)}'
11 |
12 | go test -v -race ./... # Run all the tests with the race detector enabled
13 |
14 | echo "Running extra checks..."
15 | go vet ./... # go vet is the official Go static analyzer
16 | # staticcheck ./... | grep -Pv '(func .* unused)' | perl -pe 'END{exit($. > 0 ? 1 : 0)}'
17 | # golint $(go list ./...) | grep -Pv '(exported .* should have)' | perl -pe 'END{exit($. > 0 ? 1 : 0)}'
18 |
--------------------------------------------------------------------------------