Skip to content

Python - #1

Merged
HelaFaye merged 60 commits into
masterfrom
Linux
Oct 13, 2026
Merged

HelaFaye merged 60 commits into
masterfrom
Linux

Conversation

@HelaFaye

Copy link
Copy Markdown
Owner

Ported to python for better cross-platform support.

linkoid and others added 30 commits December 29, 2020 17:00
HID info will only list on startup now.
Resolve the device_connection() conflict with linkoid's pseudo-third-party
support: keep fienestar's handle_type enum and priority selection, and move
third-party detection into open_third_party_controller(), which runs when no
Nintendo VID/PID device is found (Any or Pro Controller priority).

Fixes carried in the merge:
- Open third-party devices with hid_open_path() instead of hid_open() with
  the vendor and product ids swapped.
- Only ask about a third-party device once; reopen an accepted device
  silently so check_if_connected() does not prompt on every action.
- Selecting "Any" in the priority drop-down now resets the priority to
  NOTHING instead of JOYCON_R.

Co-authored-by: linkoid <36754150+linkoid@users.noreply.github.com>
Ported from mas1850/jc_toolkit@03e5e50 and 7325daf:
- jctool project: PlatformToolset v143, .NET Framework 4.7.2, latest
  installed Windows 10 SDK.
- Sleep(1) before opening the Pro Controller handle.
- README: project information and v5.2.0 changelog; prerequisites updated
  for the new toolset and framework.

Not ported: license comments placed before the <?xml?> declaration (makes
the XML/MSBuild files invalid), a personal SPI dump, a resource compiler
temp file and a generated colors.xml.
Ported from arpruss/jc_toolkit@d7ed33c..b622263: adds a Mode group
(Capture / Pointing / Cluster) to the IR settings. Pointing (mode 4) and
Clustering (mode 6) draw the reported blobs' bounding boxes and centroids
into a 320x240 frame. Also stops the IR picture border flashing by setting
the picture size before the image and not resetting AutoScaleDimensions on
every frame.

Not ported: that branch was built on an older jctool.cpp and dropped the
NTAG213/215/216 raw data reading and the Tag contents box, so NFC stays as
it is on master. The 1.5x IR preview size is also not ported, because it
overflows the IR group box. The step8 register-set ack check keeps the
original x0700 test for image transfer and also accepts the reply arpruss
saw in pointing/clustering.
- docs/LINUX_PORTING.md: step-by-step guide for porting to Linux with C# on
  Mono (recommended) or Python + Kivy, covering Bluetooth pairing, udev,
  hid-nintendo, the USB handshake from HID-Joy-Con-Whispering, hidraw vs
  Windows hidapi differences, translation tables and an acceptance checklist.
- linux/udev: rules so the logged-in user can open the controllers.
- linux/mono: hidapi-hidraw P/Invoke binding, C# port of the connection
  logic (priority + pseudo-third-party) and SPI/device info helpers, a
  jcprobe CLI, and a converter that turns FormJoy.h's designer code into
  C#. The converted form builds with mcs and runs on Mono 6.8.
- linux/python: jcprobe.py (hidraw module) and a .resx image extractor.
- linux/mono/src: jctool.cpp and FormJoy.h ported to C# (unsafe code keeps
  the packed packet structs, offsets, retry loops and goto flow), the
  converted designer, data tables, Overrides, and Main().
- hidapi-hidraw wrapper that reproduces the Windows hidapi behaviour the
  protocol code relies on (49-byte write padding, 0-length read drains one
  report, -d traffic log).
- FakeJoyCon emulator plus --selftest and --demo modes for testing without
  a controller.
- Font substitution for missing Windows fonts.
- Color picker: build paths with Path.Combine so colors.xml is found on Linux.
- FakeJoyCon emulates the IR MCU in image transfer mode, so --selftest and
  --demo exercise the IR pipeline (fragments, colorize, rotate, PNG).
- --selftest also covers the debug console and the HD rumble player.
- Bound the NFC copy lengths taken from controller replies and avoid a
  divide by zero in the IR FPS readout.
- Build the color picker as Latin-1 so its degree sign shows correctly.
- linux/README.md: install, build and step-by-step testing instructions,
  read-only first, with troubleshooting.
- Drop the designer-only preview (the full app replaces it).
A bare 'udevadm trigger' replays events for every device, including the
Bluetooth adapter, which can drop Bluetooth connections.
Adds a millisecond timestamp to each logged write/read and logs read
timeouts, to find where time is spent in slow IR transfers.
hidraw queues writes instead of blocking like Windows, so IR fragment ACKs
reached the Joy-Con back to back and some were dropped; each dropped ACK
stalled the transfer for 1 second (162 of 176 seconds in a real capture).
Keep 0x11 output reports at least 15ms apart (JCTOOL_MCU_WRITE_GAP_MS to
tune, 0 to disable).
The Joy-Con's report timer shows it answered each IR ACK within ~15ms, so
the 1 second stalls happen on the PC side between the ACK and the next
read. With JCTOOL_TIMESTAMPS=1 and -d, the log now records any hid_write,
status label, frame drawing or DoEvents step that takes 30ms or more.
MCU write pacing stays available through JCTOOL_MCU_WRITE_GAP_MS.
--demo also keeps a following -l/-d/-f option.
The Windows code updated the IR status label and ran DoEvents after every
fragment (up to 512 per capture). Under Mono on XWayland some of those
calls stall for about a second while the Joy-Con waits for the app.
Finished frames are still drawn every time.
Under Mono on XWayland, Application.DoEvents() often blocks for about a
second. The IR loop called it between fragments while the Joy-Con waited
for the ACK, so captures crawled or never finished.

The IR transfer now runs on a worker thread. Status text, stats, auto
exposure and frames are handed to the UI thread, keeping only the newest
of each. A live config change while streaming is sent by the worker
between fragments, where the Windows build sent it from DoEvents().

Self-test: a capture while the window stalls 1s at a time now takes 5s
(it took 500s before), plus stream, live config and stop.
Stop, like every button, first checks the connection, which closed and
reopened the controller handle while the IR thread was reading from it,
crashing in hid_read_timeout. Keep the handle while the IR thread runs.

Also dispose each IR frame's images right away (libgdiplus holds them in
native memory until finalized) and keep traffic_log.txt open instead of
reopening it for every packet.
Marks configure, IR thread start and end, and the window update in
traffic_log.txt, and prints an IR thread error to the terminal, to find
where a reported freeze stops. A start request while the IR thread is
still running is ignored instead of starting a second one.
The capture loop treated a frame as done once its last fragment arrived
in order. If the Joy-Con skipped a fragment near the end and resent it
only later, the saved frame kept that strip from the previous frame,
which has a different exposure, seen as a bright bar at the image edge.

Track which fragments of each frame arrived. When the frame that would
end a capture is incomplete, take the next one instead (up to 3 times).
Incomplete frames are noted in the -d log. Self-test reproduces the skip
with the emulator.
The Joy-Con answers the auto exposure register write in place of the next
fragment and doesn't resend it (the original code's TODO notes this), so
every frame after an adjustment is missing one fragment. With complete
frames required, each retry frame adjusted again and lost another one, so
captures ran out all retries (4 frames, ~54s at 240x320).

Adjust once per capture; the retry frame then comes through complete.
Streaming still adjusts every frame. The emulator now drops a fragment
after a register write like the Joy-Con does.
JCTOOL_IR_QUICK=1: Capture adjusts the exposure on the first fragment of
the first frame, so that frame takes the fragment the Joy-Con drops for
the register write and the second, complete frame is saved (2 frames
instead of 3).

JCTOOL_IR_NO_REACK=1: experiment, don't re-send the ACK when the Joy-Con
reports no new data, to compare transfer speed over Linux Bluetooth.

Both are noted at the start of each IR run in the -d log and documented
in linux/README.md.
Tested on a Joy-Con (R) over Bluetooth: without re-sending the ACK on
empty reports, the Joy-Con sent ~8 empty reports per fragment and took
135ms per fragment instead of 29ms (a 240x320 capture took 69s instead
of 30s). The original behavior stays.
Tested on a Joy-Con (R) at 240x320: 19.1s and 19.5s per capture instead
of 30.5s, with complete frames, and the auto exposure adjustment shows in
the saved image. JCTOOL_IR_QUICK=0 restores the Windows build's timing.
Restore the original Capture behavior as the default and replace the
JCTOOL_IR_QUICK environment variable with a "Quick capture" checkbox in
IR Camera Settings, under Auto Exposure. It only affects Capture.
The Joy-Con reports white pixels on the full sensor at every resolution
(a 60x80 capture reported 8302, more than its 4800 pixels). The original
code divided by the current resolution's pixel count, so below 240x320
auto exposure overreacted: a 60x80 capture dropped the exposure from
160us to 0 and every later frame, and the next capture, was black.

Divide by the full sensor count, capped like the u16 count (as the
original already did at 240x320, which is unchanged).
HelaFaye and others added 29 commits September 28, 2026 18:43
- jctool_linux_interactive.cpp: Interactive menu with device selection
- Support for multiple Joy-Con detection and selection
- Menu-driven interface for battery, LED, vibration, device info
- Stub for calibration data reading (SPI read implementation)
- Updated CMakeLists.txt and Makefile.linux for three binaries
Build: only jctool_linux_interactive.cpp exists (jctool_linux.cpp and
jctool_linux_full.cpp were never committed), and a binary named jctool
can't be written at the repository root because the jctool/ folder is
there. Build one binary, jctool-cli, from Makefile.linux or CMake.

Protocol, matching Joy-Con Toolkit:
- Send neutral rumble data with subcommands, and wait for the reply to
  the subcommand (0x21 echoing it) instead of taking the first report.
- Device info: type, firmware and MAC from their real offsets.
- Battery: level and charging bit from the report, and the voltage.
- Rumble: repeat the test tone for a second, then return to neutral.
- Calibration: read factory and user stick calibration and factory
  6-axis calibration from SPI (was a stub).
- Name devices by product id (hidraw gives Bluetooth devices an empty
  product string), and handle bad input and end of input instead of
  looping forever.

Document it in linux/README.md.
… skips auto exposure

A 120x160 capture once kept receiving 240x320 rows: the Joy-Con
acknowledged the new settings but didn't apply them, and every frame kept
the placeholder stats a run's first frame carries. When the saved frame
still has those, set the camera up again and capture once more; if that
fails too, say so instead of "Done".

Quick capture based its exposure change on those placeholder stats, so
it now skips the auto exposure adjustment and uses the Exposure value as
set (still 2 frames).
A second 120x160 capture that stayed at 240x320 sent new frames with
real stats, so comparing stats with the leftover first frame missed it.
Check the saved frame's layout too: a real image is smoothest at its own
width. On a Joy-Con (R) log, good frames were 1.25-1.75x rougher at any
other width and stuck frames 30-100x smoother at 320 wide; flag a frame
when another width is under half as rough. Nearly uniform frames are
skipped.

The emulator's test image is now 2D at the current resolution, and it
can emulate a camera that keeps sending 240x320 rows.
…setup

JCTOOL_IR_SKIP_LEFTOVER=1: on the leftover first frame's first fragment,
ACK its last fragment, hoping the Joy-Con starts a new frame (at 240x320
the leftover frame took ~10s of a 24s capture). If the next fragment is
a new fragment 0 with other data, the capture continues from there;
otherwise it carries on as before. The -d log says which happened.

JCTOOL_IR_PATIENT_SETUP=1: wait ~20 reports (~300ms) for each camera
setup reply before re-sending, instead of 9 (~135ms). A Joy-Con (R)
answered after 120-150ms, so early re-sends caused duplicate replies
that made the next step re-send too.

Both are off by default and noted at the start of each run in the log.
jctool-cli now has every feature of the window, in a text menu:
device info (FW, MAC, S/N, battery, temperature, colors), player LEDs,
rumble, calibration view and editing, stick device parameters, colors,
SPI backup, restore (colors, S/N, user calibration, factory reset of
user calibration, full restore) with the window's backup checks, S/N
change and restore, live button/stick/6-axis test, HD Rumble player
(.bnvib/.jcvib with equalizer and loops) and tunes, IR camera (all
settings, capture, stream with live changes, quick capture, PNG output
and a terminal preview), NFC/amiibo scan, debug custom commands, HID
listing and disconnect.

The protocol code (cli/jc_core.cpp) is ported from the Linux build's
JcTool.cs, itself a port of jctool.cpp, including its Linux fixes. The
IR palette, rumble tunes and amplitude tables come from the original
headers. cli/png.cpp writes PNGs without extra libraries.

Enter stops long operations; other lines typed meanwhile are kept for
the next prompts. cli/test/run_tests.sh builds the CLI against an
emulated controller (cli/test/fake_hidapi.cpp, a C++ port of
FakeJoyCon.cs) and checks every menu: 42 checks, including the flash
contents after each write and the IR image pixel by pixel.
Mono's WinForms imports the desktop color scheme through GTK 2 (the
"Unable to locate theme engine" warning comes from that). With a dark
KDE theme, message box and dialog buttons became dark with unreadable
labels. Save Mono's built-in system colors, let the import run once at
startup, then put the built-in colors back. JCTOOL_DESKTOP_COLORS=1
keeps the desktop's colors.
Prints the Mono version, the desktop-related environment variables, the
system colors at start, after Mono's desktop color import and after the
reset, the theme engine and a default button's colors.
On Mono 6.12 the desktop color import changed the system colors but
KnownColors.Update didn't change them back (seen with --diag-colors).
Also set the theme's ColorControl, ColorControlText, ... properties,
which the import uses.
The blank dialog buttons weren't a color problem: Mono draws dialog
buttons 23px tall and only draws a label if its whole line fits. Its
default font (Microsoft Sans Serif) falls back to the desktop's sans
font, and Noto Sans' 15px line doesn't fit, so every label was
skipped. Reproduced with Noto Sans as the fallback font.

Use Liberation Sans (or Arimo, DejaVu Sans) as Mono's default font when
Microsoft Sans Serif isn't installed: 12.6px lines, labels drawn again.
Dialogs keep the desktop's (dark) colors; the light color reset is now
opt-in with JCTOOL_CLASSIC_COLORS=1. --diag-colors also shows the
default font and a button label's line height.
A 60x80 stream on a Joy-Con (R) sent only 240x320 rows (vertical bars),
although the same settings had just worked for a capture. Check a stream's
first frames with the capture's row-width test; two stuck frames in a row
stop it, and the GUI and jctool-cli set the camera up again once.
Self-test and CLI test with an emulated stuck camera.
A 30x40 stream on a Joy-Con (R) sent 320 pixel rows (vertical bars), but
the row-width check skipped widths that don't divide the frame evenly
(1200 pixels are 3.75 rows of 320). Compare any width with at least 3 rows;
only 30x40 gains a width. Tests for the check and a stuck 30x40 CLI stream.
Playing HD rumble during a stream aborted in glibc inside hid_read_timeout:
the IR thread and the window thread called hidapi on the same device at
once, and hidapi frees and replaces a per-device error string on every
call. On Windows both ran on the window thread, one call at a time.
Serialize native hidapi calls with a lock; long reads wait in 10ms slices
so the other thread's writes still get through. The emulated controller
counts overlapping calls; self-test plays HD rumble during a stream.
After HD rumble during a stream the battery read 0.00V and the app froze:
the IR thread and the window thread each read the other's replies. On
Windows the IR loop ran on the window thread and let such commands run in
between frames. Now a window command takes the controller for all of its
calls until the window is idle again; the IR thread waits meanwhile.

Status bar: link health (reports per second and the longest wait for one,
from the app's own traffic), with details in the tooltip.

The emulated Joy-Con now sends empty IR reports every 15ms like a real one.
Self-test: battery read during a stream, link health.
- The menu bar shows whether the factory or a user calibration is in use
  (details in the tooltip); clicking it opens the calibration editor with
  the controller's values. The CLI's device info shows the same.
- Calibrate.. in each stick box of the calibration editor: measures the
  center (stick at rest) and range (rotated along its edge) from full input
  reports and fills in the fields. Nothing is written until Write Cal.
  The CLI offers the same in menu 11.
- Write Cal's SPI write is split from its dialog so the self-test can use
  it; self-test and CLI tests drive the wizard with an emulated stick and
  check the written calibration reads back.
… info section

- Edit Calibration gets tabs: a visual guided stick calibration (hold-still
  indicator, direction ring, trace and range box), a guided motion (6-axis)
  calibration (bubble level, stillness progress; writes the measured gyro and
  accelerometer offsets with the factory sensitivities), and the original
  editor (Manual), moved into its own tab unchanged.
- The wizards read the controller only while measuring and write only what
  they measured, after a confirmation.
- Calibration status moves from the menu bar to a third row of the info
  section, with a Calibrate.. link. The separate wizard window and the
  per-stick buttons are gone.
- Self-test drives both wizards with an emulated stick and motion sensors
  and checks the written calibration.
Mono's LinkLabel clipped the right-aligned text to "ate..".
- Sticks and Motion tabs: Use factory erases that user calibration (after a
  confirmation), so the controller goes back to its factory calibration.
- Motion tab option: two positions. After the first still measurement, turn
  the controller 180 degrees flat on the same surface (the gyro measures the
  turn, shown as an arc) and measure again. The surface's tilt reverses and
  averages out of the accelerometer offsets.
- Self-test: two positions on a tilted surface give the exact offsets; Use
  factory erases the stick and motion user calibration.
The second measurement no longer starts on its own when the gyro reads 180
degrees: Confirm turn is enabled then, and the user clicks it after letting
go of the controller. Self-test checks it waits for the confirmation.
A 180 degree turn on a Joy-Con (R) read as 205: 0.070 dps per count (936 /
13371) is 14% high. The gyro's +-2000 dps range over 16 bits is 0.061
(4000 / 65536), which matches the measured turn.
The HD Rumble Player gets tabs: Files (the original player) and MIDI, which
plays MIDI on the rumble. The idea comes from Musical-Joycons by sarossilli;
this is a separate implementation:
- Standard MIDI Files (format 0/1, tempo changes, SMPTE time), per part or
  all parts except drums.
- Live input from ALSA raw MIDI devices (/dev/snd/midiC*D*), with a channel
  filter and the sustain pedal.
- The highest held note plays on the high band (octave-shifted into
  400-1252 Hz), the lowest on the low band (100-626 Hz); velocity and volume
  set the amplitude, encoded with the HD Rumble Player's tables. Rumble is
  sent from its own thread on every change and every 25ms while notes sound.
- Self-test: encoding, parsing a generated MIDI file, playback on the
  emulated controller (drums skipped), and live input through a FIFO with
  the sustain pedal.
A Joy-Con (R) showed the notes playing but didn't vibrate: the controller
ignores rumble reports until subcommand 0x48 enables vibration, which the
HD Rumble Player sends before playing a file. Send it when MIDI starts and
disable vibration when it stops. The emulated controller now ignores rumble
until vibration is enabled, like a real one.
python/jctool: a Python port of the toolkit for a cross-platform (Kivy) app.
- core.py: the protocol, from cli/jc_core.cpp (same packets, reply checks and
  retries, with the Linux build's fixes: complete IR frames, auto exposure on
  the full sensor, stuck-camera detection for captures and streams, bounded
  NFC lengths).
- hidio.py: hidapi (cython-hidapi: Windows, macOS, Linux) with the Windows
  behaviour the protocol expects, a lock per device, link health and the
  traffic log.
- ops.py: device info, battery, colors, SPI backup checks and restores, S/N,
  HD Rumble files, IR settings and images, NTAG dumps, debug commands.
- calibration.py: user calibration and stick parameters, the guided stick and
  motion (one or two positions) calibrations, Use factory.
- midi.py: MIDI files and devices (mido/python-rtmidi) on the HD Rumble.
- fake.py: the emulated controller; tests/: 31 pytest tests.
- tables.py: generated from jctool/*.h by tools/gen_tables.py.
Cross-platform (Windows, macOS, Linux) Kivy frontend over the Python
protocol core: Device, Backup, Serial, Calibration (Sticks/Motion/Manual),
Button test, HD Rumble (Files/MIDI), IR Camera, NFC and Debug screens,
link health and calibration status, --demo/--selftest/-d options,
pyproject.toml with a jctool entry point, and README.
- scripts/setup_venv.sh / .bat make python/.venv; scripts/build.py builds
  the desktop app (PyInstaller, packaging/jctool.spec) or the Android APK
  (buildozer.spec)
- GitHub Actions workflow: tests, then Linux, Windows, macOS and Android
  builds as artifacts (and a release on v* tags)
- Linux uses hidapi's hidraw backend (its hid module is libusb, which
  can't see Bluetooth controllers); USB controllers get the 0x80 handshake
- Android: USB host backend (android_usb.py: Java to open, usbdevfs for
  reports), USB attach filter, Android file picker, app folder for files
- Small screens: the panels scroll, the tabs and status bar stay
- App icon
Android's Bluetooth service hands a paired controller to the kernel,
which makes a /dev/hidraw node only root can open. native/jctool_hidraw.c
is a helper built with the NDK for each of the APK's ABIs and run through
su: it lists the HID devices, opens a controller's hidraw node, relays
reports over its stdin/stdout, and moves the controller from hid_nintendo
to hid-generic while it's open (and back after).

- jctool/hidraw_bridge.py: the app's side, with hidapi's interface
  (JCTOOL_HID_BACKEND=bridge on desktop Linux too)
- jctool/android_hid.py: Android's backend, Bluetooth and USB together
- scripts/build.py compiles the helper with the NDK before buildozer
- tests: the helper compiled with the system's cc, over a fake /sys and
  /dev with the emulated Joy-Con behind a seqpacket socket (device info,
  colors, SPI dump, IR capture, driver hand-off, errors)
While hid_nintendo is loaded, the kernel's hid-generic refuses to bind a
Joy-Con ("No such device"), so after the unbind no hidraw node came
back. Tested on Arch: it binds with hid.ignore_special_drivers=1. The
helper turns that on for the bind and puts the old value back.

The test's fake sysfs now holds the helper inside the bind and checks
the parameter there (the previous helper fails it).
Seen on a Joy-Con (R) with FW 4.19: a MIFARE tag is detected (type byte
0x04), then the NTAG read requests only get 'tag detected' back, and the
scan ended with error 8 after 10 tries, with no dump. Only NTAG contents
can be read, so the scan now stops at the UID and says so.

- Stopping a scan before a tag is there ends it (no reads)
- Errors 6-8 in the NFC tab say what to do
- The emulated Joy-Con detects tags (no contents); tests for a MIFARE
  tag, no tag, and stopping
@HelaFaye
HelaFaye merged commit 1e45488 into master Oct 13, 2026
4 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants