Repository navigation
Expand file tree
/
Copy pathjctool_linux_interactive.cpp
More file actions
1807 lines (1664 loc) · 71.7 KB
/
Copy pathjctool_linux_interactive.cpp
File metadata and controls
1807 lines (1664 loc) · 71.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Joy-Con Toolkit (Linux CLI) - interactive menu with the features of Joy-Con Toolkit's
// window. The controller protocol code is in cli/jc_core.cpp; the menus below follow the
// window's handlers (linux/mono/src/FormJoy.cs / jctool/FormJoy.h), with the same checks,
// warnings and SPI offsets.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/select.h>
#include <deque>
#include <string>
#include <chrono>
#include <cmath>
#include <vector>
#include "cli/jc_core.h"
#include "cli/png.h"
#define VENDOR_ID_NINTENDO 0x057E
#define PRODUCT_JOY_CON_L 0x2006
#define PRODUCT_JOY_CON_R 0x2007
#define PRODUCT_PRO 0x2009
static bool temp_celsius = true;
// ---------------------------------------------------------------------------------------------
// Input
static void quit_program(int code);
static std::string fmt_color_prompt(const char *question, const u8 *rgb) {
char buf[128];
snprintf(buf, sizeof(buf), "%s [%02X%02X%02X]: ", question, rgb[0], rgb[1], rgb[2]);
return buf;
}
// Lines typed ahead during a long operation (see ui_poll), used by the next prompts
static std::deque<std::string> pending_lines;
// Reads one line from stdin (without the newline). False at end of input.
static bool get_line(std::string &out) {
if (!pending_lines.empty()) {
out = pending_lines.front();
pending_lines.pop_front();
return true;
}
char line[256];
if (!fgets(line, sizeof(line), stdin))
return false;
size_t n = strlen(line);
while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r'))
line[--n] = 0;
out = line;
return true;
}
// Reads a line from stdin. Ends the program at end of input.
static std::string read_line(const char *prompt) {
std::string line;
if (prompt)
printf("%s", prompt);
fflush(stdout);
if (!get_line(line)) {
printf("\n");
quit_program(0);
}
return line;
}
// Reads a number from stdin. Returns 0 on success, -1 on bad input, -2 at end of input.
int read_number(const char *format, int *value) {
std::string line;
fflush(stdout);
if (!get_line(line))
return -2;
return sscanf(line.c_str(), format, value) == 1 ? 0 : -1;
}
static bool ask_yes_no(const char *question) {
std::string answer = read_line((std::string(question) + " [y/N]: ").c_str());
return answer == "y" || answer == "Y" || answer == "yes" || answer == "Yes";
}
// Asks for a number (decimal, or hex with 0x). Empty input keeps the current value.
static int ask_int(const char *question, int current, int min, int max) {
while (true) {
std::string answer = read_line((std::string(question) + " [" + std::to_string(current) + "]: ").c_str());
if (answer.empty())
return current;
char *end = NULL;
long v = strtol(answer.c_str(), &end, 0);
if (end && *end == 0 && v >= min && v <= max)
return (int)v;
printf(" Enter a number from %d to %d.\n", min, max);
}
}
// Asks for an RGB color as RRGGBB hex. Empty input keeps the current value.
static bool ask_color(const char *question, u8 *rgb) {
while (true) {
std::string answer = read_line(fmt_color_prompt(question, rgb).c_str());
if (answer.empty())
return false;
if (answer[0] == '#')
answer = answer.substr(1);
unsigned v;
char tail;
if (answer.size() == 6 && sscanf(answer.c_str(), "%6x%c", &v, &tail) == 1) {
rgb[0] = (v >> 16) & 0xFF;
rgb[1] = (v >> 8) & 0xFF;
rgb[2] = v & 0xFF;
return true;
}
printf(" Enter a color as RRGGBB (hex), e.g. FF3C28.\n");
}
}
// True when a line was typed (Enter) since the last check. Used to stop long operations.
static bool stdin_has_line() {
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
struct timeval tv = { 0, 0 };
return select(1, &fds, NULL, NULL, &tv) > 0;
}
// ---------------------------------------------------------------------------------------------
// Connection
static std::string accepted_third_party_path;
struct found_device {
std::string path;
u16 product_id;
int type;
std::string name;
std::string serial;
};
static const char *type_name(int type) {
switch (type) {
case JOYCON_L: return "Joy-Con (L)";
case JOYCON_R: return "Joy-Con (R)";
case PROCON: return "Pro Controller";
default: return "None";
}
}
static std::string wstr(const wchar_t *w) {
std::string s;
if (w)
for (; *w; w++)
s += (*w < 128) ? (char)*w : '?';
return s;
}
// Nintendo controllers, and third-party ones that report as a "Wireless Gamepad" (like the
// window's pseudo-third-party support). hidraw gives Bluetooth devices an empty manufacturer.
static std::vector<found_device> find_controllers() {
std::vector<found_device> list;
struct hid_device_info *devs = hid_enumerate(0, 0);
for (struct hid_device_info *cur = devs; cur; cur = cur->next) {
found_device d;
d.path = cur->path;
d.product_id = cur->product_id;
d.serial = wstr(cur->serial_number);
std::string product = wstr(cur->product_string);
std::string maker = wstr(cur->manufacturer_string);
if (cur->vendor_id == VENDOR_ID_NINTENDO && cur->product_id == PRODUCT_JOY_CON_L)
d.type = JOYCON_L;
else if (cur->vendor_id == VENDOR_ID_NINTENDO && cur->product_id == PRODUCT_JOY_CON_R)
d.type = JOYCON_R;
else if (cur->vendor_id == VENDOR_ID_NINTENDO && cur->product_id == PRODUCT_PRO)
d.type = PROCON;
else if (product == "Wireless Gamepad" && (maker == "Nintendo" || maker.empty()) && cur->usage == 0x0005)
d.type = -PROCON; // Third-party, used as a Pro Controller
else
continue;
d.name = d.type > 0 ? type_name(d.type) : "Third-party \"Wireless Gamepad\" (as Pro Controller)";
list.push_back(d);
}
hid_free_enumeration(devs);
return list;
}
static int connect_device(const found_device &d) {
if (d.type < 0 && d.path != accepted_third_party_path) {
printf("\nA potential third-party device has been detected:\n\n\t%s\n\n", d.name.c_str());
if (!ask_yes_no("Editing could be potentially unstable. Would you like to use this device anyways?"))
return -1;
}
if (handle)
hid_close(handle);
handle = hid_open_path(d.path.c_str());
if (!handle) {
fprintf(stderr, "[-] Failed to open %s (permissions? see linux/udev)\n", d.path.c_str());
handle_type = NOTHING;
return -1;
}
if (d.type < 0)
accepted_third_party_path = d.path;
handle_type = d.type < 0 ? PROCON : d.type;
timming_byte = 0;
// Like the window at start: quiet input reports, busy LEDs
silence_input_report();
set_led_busy();
printf("[+] Connected to %s\n", type_name(handle_type));
return 0;
}
int select_device(void) {
std::vector<found_device> list = find_controllers();
if (list.empty()) {
fprintf(stderr, "[-] No Joy-Con or Pro Controller found\n"
" Pair it (see linux/README.md), check /dev/hidraw* permissions\n"
" and that the hid_nintendo driver is not holding it.\n");
return -1;
}
printf("\n=== Available Devices ===\n");
for (size_t i = 0; i < list.size(); i++) {
printf("[%zu] %s", i, list[i].name.c_str());
if (!list[i].serial.empty())
printf(" (%s)", list[i].serial.c_str());
printf(" %s\n", list[i].path.c_str());
}
int choice = 0;
if (list.size() > 1) {
printf("\nSelect device [0-%zu]: ", list.size() - 1);
if (read_number("%d", &choice) != 0 || choice < 0 || choice >= (int)list.size()) {
fprintf(stderr, "[-] Invalid selection\n");
return -1;
}
}
return connect_device(list[choice]);
}
// The window checked the connection before every action.
static bool need_device() {
if (handle)
return true;
printf("[-] No device connected. Select one first.\n");
return select_device() == 0;
}
static void quit_program(int code) {
if (handle)
hid_close(handle);
hid_exit();
exit(code);
}
// ---------------------------------------------------------------------------------------------
// What the window showed (called by cli/jc_core.cpp)
static std::string live_command; // A line typed during an IR stream (live config)
// Enter (an empty line) stops a long operation, like the window's Stop/Cancel buttons.
// During an IR stream, "e", "g" and "r" lines change the camera settings. Anything else
// was typed ahead and is kept for the next prompts.
void ui_poll() {
if (!stdin_has_line())
return;
char buf[256];
if (!fgets(buf, sizeof(buf), stdin))
return;
std::string line = buf;
while (!line.empty() && (line.back() == '\n' || line.back() == '\r'))
line.pop_back();
if (!line.empty()) {
if (enable_IRVideoPhoto && (line[0] == 'e' || line[0] == 'g' || line[0] == 'r'))
live_command = line; // Handled by the IR stream (ui_ir_frame)
else
pending_lines.push_back(line);
return;
}
cancel_spi_dump = true;
enable_button_test = false;
enable_IRVideoPhoto = false;
enable_NFCScanning = false;
printf("\nStopping...\n");
}
void ui_spi_progress(u32 offset) {
printf("\r %.2fKB of 512KB (Enter to cancel)", offset / 1024.0f);
fflush(stdout);
}
void ui_custom_command(const std::string &sent, const std::string &reply_cmd, const std::string &reply) {
printf("\nSent:\n%s\n", sent.c_str());
if (!reply_cmd.empty())
printf("%s\n", reply_cmd.c_str());
printf("\n%s\n", reply.c_str());
}
void ui_button_test_info(const std::string &text) {
printf("%s\n\n", text.c_str() + (text.compare(0, 2, "\n\n") == 0 ? 2 : 0));
printf("Live input (Enter to stop):\n\0337"); // Save the cursor position
}
void ui_button_test(const std::string &report, const std::string &sensors) {
printf("\0338\033[J%s\n\n%s", report.c_str(), sensors.c_str()); // Redraw from the saved position
fflush(stdout);
}
void ui_nfc_uid(const std::string &text) {
printf("\n%s\n", text.c_str());
}
void ui_nfc_tag(const std::string &text) {
printf("%s\n", text.c_str());
}
// show_ntag_contents
void ui_ntag_contents(u8 *ntag_buf, u8 ntag_pages) {
const char *model = ntag_pages == 45 ? "213" : ntag_pages == 135 ? "215" : ntag_pages == 231 ? "216" : "???";
const char *kind = ntag_buf[16] == 0xA5 ? " (Amiibo)" : ntag_buf[16] == 0x01 ? " (NDEF)" : "";
printf("NTAG %s%s\n\n", model, kind);
for (int i = 0; i < ntag_pages; i++) {
printf("%02X: ", i);
for (int j = 0; j < 4; j++)
printf("%02X ", ntag_buf[i * 4 + j]);
printf("|");
for (int j = 0; j < 4; j++) {
u8 c = ntag_buf[i * 4 + j];
printf("%c", (c < 0x20 || c > 0x7e) ? '.' : c);
}
printf("|\n");
}
}
// ---------------------------------------------------------------------------------------------
// IR camera settings (the window's IR Camera panel) and images
enum { IR_GREY = 0, IR_NIGHT = 1, IR_IRONBOW = 2, IR_INFRARED = 3 };
static struct {
int resolution = 0; // 0: 240x320, 1: 120x160, 2: 60x80, 3: 30x40
int mode = 0; // 0: Capture, 1: Pointing, 2: Clustering
int colorize = IR_IRONBOW;
bool leds_far = true; // Far/Narrow (75°) Leds 1/2
bool leds_near = true; // Near/Wide (130°) Leds 3/4
int intensity_far = 15; // 0-15
int intensity_near = 16; // 0-16
bool flashlight = false;
bool strobe = false;
bool ex_filter = true; // External IR filter
bool selfie = false;
int exposure = 300; // us, 0-600
bool auto_exposure = false; // For streaming (Capture always uses it)
int gain = 2; // Digital gain 1-20 (streaming without auto exposure)
bool denoise = true;
int edge_smoothing = 35;
int color_interpolation = 68;
int custom_reg = 0; // Live config: register address (page << 8 | reg)
int custom_val = 0;
} ir;
static int ir_image_width = 320;
static int ir_image_height = 240;
static bool ir_show_preview = true;
static int ir_frames_shown = 0;
static std::string ir_status_text;
static std::vector<u8> ir_last_capture;
static int ir_last_capture_w = 0, ir_last_capture_h = 0;
static const char *ir_res_names[] = { "240x320", "120x160", "60x80", "30x40" };
static const char *ir_mode_names[] = { "Capture", "Pointing", "Clustering" };
static const char *ir_color_names[] = { "Greyscale", "Night vision", "Ironbow", "Infrared" };
// prepareSendIRConfig: the camera configuration from the settings
static bool build_ir_config(ir_image_config &cfg, bool startNewConfig) {
memset(&cfg, 0, sizeof(cfg));
if (startNewConfig) {
static const int widths[] = { 320, 160, 80, 40 }, heights[] = { 240, 120, 60, 30 };
static const u8 res_regs[] = { 0x00, 0x50, 0x64, 0x69 }, frags[] = { 0xff, 0x3f, 0x0f, 0x03 };
int r = ir.resolution;
if (ir.auto_exposure && r == 3)
r = 2; // The window disables 30x40 with auto exposure
ir_image_width = widths[r];
ir_image_height = heights[r];
cfg.ir_res_reg = res_regs[r];
ir_max_frag_no = frags[r];
if (ir.mode == 0)
cfg.ir_mode = 0x07;
else {
cfg.ir_mode = ir.mode == 1 ? 0x04 : 0x06;
ir_image_width = 320;
ir_image_height = 240;
}
}
else
cfg.ir_res_reg = ir.resolution == 3 ? 0x69 : 0x00;
// Enable IR Leds. Only the following configurations are supported.
if (ir.leds_far && ir.leds_near)
cfg.ir_leds = 0x00; // Both Far/Narrow 75° and Near/Wide 130° Led groups are enabled.
else if (ir.leds_far && !ir.leds_near)
cfg.ir_leds = 0x20; // Only Far/Narrow 75° Led group is enabled.
else if (!ir.leds_far && ir.leds_near)
cfg.ir_leds = 0x10; // Only Near/Wide 130° Led group is enabled.
else
cfg.ir_leds = 0x30; // Both groups disabled
// IR Leds Intensity
cfg.ir_leds_intensity = (u16)((ir.intensity_far << 8) | ir.intensity_near);
// IR Leds Effects
if (ir.flashlight)
cfg.ir_leds |= 0x01;
if (ir.strobe && !ir.flashlight)
cfg.ir_leds |= 0x80;
// External Light filter (Dark-frame subtraction). Disabled with the leds in flashlight mode.
cfg.ir_ex_light_filter = ((ir.ex_filter || ir.strobe) && !ir.flashlight) ? 0x03 : 0x00;
// Flip image
cfg.ir_flip = ir.selfie ? 0x02 : 0x00;
// Exposure time (Shutter speed) is in us. Valid values are 0 to 600us or 0 - 1/1666.66s
cfg.ir_exposure = (u16)(ir.exposure * 31200 / 1000);
if (!ir.auto_exposure && enable_IRVideoPhoto) {
enable_IRAutoExposure = false;
cfg.ir_digital_gain = (u8)ir.gain;
}
else {
enable_IRAutoExposure = true;
cfg.ir_digital_gain = 1; // Disable digital gain for auto exposure
}
//De-noise algorithms
cfg.ir_denoise = (ir.denoise ? 0x01 : 0x00) << 16;
cfg.ir_denoise |= (u32)((ir.edge_smoothing & 0xFF) << 8);
cfg.ir_denoise |= (u32)(ir.color_interpolation & 0xFF);
return true;
}
static void ir_pixel_rgb(u8 v, u8 *rgb) {
switch (ir.colorize) {
case IR_IRONBOW: {
u32 c = ir_iron_palette(v);
rgb[0] = (c >> 16) & 0xFF; rgb[1] = (c >> 8) & 0xFF; rgb[2] = c & 0xFF;
break;
}
case IR_GREY: rgb[0] = rgb[1] = rgb[2] = v; break;
case IR_NIGHT: rgb[0] = 0; rgb[1] = v; rgb[2] = 0; break;
default: rgb[0] = v; rgb[1] = 0; rgb[2] = 0; break;
}
}
// setIRPictureWindow: colorize and rotate 90° clockwise, like the window shows and saves it.
static std::vector<u8> ir_render(const u8 *image, int &out_w, int &out_h) {
int w = ir_image_width, h = ir_image_height;
out_w = h;
out_h = w;
std::vector<u8> rgb((size_t)out_w * out_h * 3);
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++) {
// Rotate90FlipNone: source (x, y) goes to (h - 1 - y, x)
u8 *px = &rgb[((size_t)x * out_w + (h - 1 - y)) * 3];
ir_pixel_rgb(image[y * w + x], px);
}
return rgb;
}
// Terminal preview with 24-bit color half blocks (each character is 2 pixels tall)
static void ir_print_preview(const std::vector<u8> &rgb, int w, int h, bool redraw) {
if (!ir_show_preview || !isatty(1))
return;
int cols = 48;
int rows = (int)((long)h * cols / w / 2);
if (redraw)
printf("\0338");
else
printf("\n\0337");
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
int x = c * w / cols;
const u8 *top = &rgb[((size_t)((2 * r) * h / (2 * rows)) * w + x) * 3];
const u8 *bot = &rgb[((size_t)((2 * r + 1) * h / (2 * rows)) * w + x) * 3];
printf("\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm▀", top[0], top[1], top[2], bot[0], bot[1], bot[2]);
}
printf("\033[0m\n");
}
}
void ui_ir_status(const std::string &text) {
ir_status_text = text;
printf("\r\033[K%s", text.c_str());
fflush(stdout);
}
void ui_ir_help(const std::string &text) {
std::string one_line = text;
for (char &c : one_line)
if (c == '\n')
c = ' ';
printf("\r\033[K%s", one_line.c_str());
fflush(stdout);
}
void ui_ir_exposure(int exposure) {
ir.exposure = exposure;
}
static void ir_apply_live_command();
void ui_ir_frame(const u8 *image) {
int w, h;
std::vector<u8> rgb = ir_render(image, w, h);
if (!enable_IRVideoPhoto) {
// Capture: saved like the window does (the frame that ends the capture is kept last)
write_png_rgb("IRcamera.png", rgb.data(), w, h);
ir_last_capture = rgb;
ir_last_capture_w = w;
ir_last_capture_h = h;
}
else {
// Stream: the newest frame, for an image viewer that reloads it
write_png_rgb("IRstream.png", rgb.data(), w, h);
printf("\r\033[K");
ir_print_preview(rgb, w, h, ir_frames_shown++ > 0);
printf("Streaming: IRstream.png updated. Enter: stop; e <us>: exposure; g <1-20>: gain; r <reg> <val>: register\n");
if (!live_command.empty())
ir_apply_live_command();
}
}
// btn_IRConfigLive_Click during a stream
static void ir_apply_live_command() {
std::string cmd = live_command;
live_command.clear();
int a = 0, b = 0;
if (sscanf(cmd.c_str(), "e %d", &a) == 1)
ir.exposure = CLAMP(a, 0, 600);
else if (sscanf(cmd.c_str(), "g %d", &a) == 1)
ir.gain = CLAMP(a, 1, 20);
else if (sscanf(cmd.c_str(), "r %i %i", &a, &b) == 2) {
ir.custom_reg = a & 0xFFFF;
ir.custom_val = b & 0xFF;
}
else
return;
ir_image_config cfg;
build_ir_config(cfg, false);
cfg.ir_custom_register = (u32)(ir.custom_reg | (ir.custom_val << 16));
ir_sensor_config_live(cfg);
printf("Applied: exposure %dus, gain %d, register %04X = %02X\n", ir.exposure, ir.gain, ir.custom_reg, ir.custom_val);
}
// ---------------------------------------------------------------------------------------------
// Menu
void print_menu(void) {
printf("\n");
printf("=== Joy-Con Toolkit (Linux CLI) ===");
if (handle)
printf(" [%s]", type_name(handle_type));
printf("\n");
printf(" 1. Detect and select device\n");
printf(" 2. Get device info\n");
printf(" 3. Get battery status\n");
printf(" 4. Set player LED\n");
printf(" 5. Test vibration\n");
printf(" 6. Read calibration data\n");
printf(" 7. Colors (view / change)\n");
printf(" 8. Backup SPI flash\n");
printf(" 9. Restore from an SPI backup\n");
printf("10. Serial number (change / restore)\n");
printf("11. Edit calibration and stick parameters\n");
printf("12. Button, stick and 6-axis test\n");
printf("13. HD Rumble player\n");
printf("14. IR camera (Joy-Con R)\n");
printf("15. NFC / amiibo scan (Joy-Con R, Pro)\n");
printf("16. Debug: send a custom command\n");
printf("17. List HID devices\n");
printf("18. Disconnect the controller\n");
printf(" 0. Exit\n");
printf("Select: ");
}
// ---------------------------------------------------------------------------------------------
// Device info, battery, temperature (full_refresh, update_battery, update_temperature)
static void show_battery() {
u8 batt_info[3] = { 0 };
get_battery(batt_info);
int batt_percent = 0;
int batt = (batt_info[0] & 0xF0) >> 4;
// Calculate aproximate battery percent from regulated voltage
u16 batt_volt = (u16)(batt_info[1] + (batt_info[2] << 8));
if (batt_volt < 0x560)
batt_percent = 1;
else if (batt_volt > 0x55F && batt_volt < 0x5A0)
batt_percent = (int)(((batt_volt - 0x60) & 0xFF) / 7.0f + 1);
else if (batt_volt > 0x59F && batt_volt < 0x5E0)
batt_percent = (int)(((batt_volt - 0xA0) & 0xFF) / 2.625f + 11);
else if (batt_volt > 0x5DF && batt_volt < 0x618)
batt_percent = (int)((batt_volt - 0x5E0) / 1.8965f + 36);
else if (batt_volt > 0x617 && batt_volt < 0x658)
batt_percent = (int)(((batt_volt - 0x18) & 0xFF) / 1.8529f + 66);
else if (batt_volt > 0x657)
batt_percent = 100;
static const char *states[] = { "Empty (disconnected?)", "Empty, charging", "Low, please charge your device!",
"Low, charging", "Medium", "Medium, charging", "Good", "Good, charging", "Full", "Almost full, charging" };
printf("Battery: %.2fV - %d%% (%s)\n", (batt_volt * 2.5) / 1000, batt_percent, batt <= 9 ? states[batt] : "?");
}
static void show_temperature() {
u8 temp_info[2] = { 0 };
get_temperature(temp_info);
// Convert reading to Celsius according to datasheet
float temperature_c = 25.0f + uint16_to_int16(temp_info[1] << 8 | temp_info[0]) * 0.0625f;
if (temp_celsius)
printf("Temperature: %.1f\u00B0C\n", temperature_c);
else
printf("Temperature: %.1f\u00B0F\n", temperature_c * 1.8f + 32);
}
static void show_colors() {
u8 c[12] = { 0 };
if (get_spi_data(0x6050, 12, c) != 0) {
printf("Colors: Error!\n");
return;
}
printf("Body: #%02X%02X%02X\n", c[0], c[1], c[2]);
printf("Buttons: #%02X%02X%02X\n", c[3], c[4], c[5]);
if (handle_type == PROCON)
printf("Grips: left #%02X%02X%02X, right #%02X%02X%02X\n", c[6], c[7], c[8], c[9], c[10], c[11]);
}
void cmd_device_info(void) {
if (!need_device())
return;
u8 device_info[10] = { 0 };
get_device_info(device_info);
printf("\nController: %s\n", type_name(handle_type));
printf("FW Version: %X.%02X\n", device_info[0], device_info[1]);
printf("MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
device_info[4], device_info[5], device_info[6], device_info[7], device_info[8], device_info[9]);
if (handle_type != PROCON)
printf("S/N: %s\n", get_sn(0x6001, 0xF).c_str());
else
printf("S/N: Not supported\n");
show_battery();
show_temperature();
show_colors();
// Calibration in use: a user calibration (magic B2 A1) overrides the factory one
u8 user_cal[22], sensor_cal[2];
memset(user_cal, 0xFF, sizeof(user_cal));
memset(sensor_cal, 0xFF, sizeof(sensor_cal));
get_spi_data(0x8010, 22, user_cal);
get_spi_data(0x8026, 2, sensor_cal);
std::string cal;
if (handle_type != JOYCON_R && user_cal[0] == 0xB2 && user_cal[1] == 0xA1)
cal += handle_type == PROCON ? "left stick, " : "stick, ";
if (handle_type != JOYCON_L && user_cal[11] == 0xB2 && user_cal[12] == 0xA1)
cal += handle_type == PROCON ? "right stick, " : "stick, ";
if (sensor_cal[0] == 0xB2 && sensor_cal[1] == 0xA1)
cal += "6-axis, ";
if (cal.empty())
printf("Calibration: factory\n");
else
printf("Calibration: user (%s)\n", cal.substr(0, cal.size() - 2).c_str());
}
void cmd_battery_status(void) {
if (!need_device())
return;
printf("\n");
show_battery();
show_temperature();
if (ask_yes_no("Switch the temperature between Celsius and Fahrenheit?")) {
temp_celsius = !temp_celsius;
show_temperature();
}
}
void cmd_set_player_led(void) {
if (!need_device())
return;
printf("\nLED patterns (combine by adding):\n");
printf(" 0x01: Player 1\n");
printf(" 0x02: Player 2\n");
printf(" 0x04: Player 3\n");
printf(" 0x08: Player 4\n");
printf(" Add 0x10-0x80 to flash the same LEDs instead\n");
int pattern = ask_int("Enter pattern (e.g. 0x01)", 0x01, 0, 0xFF);
u8 arg = (u8)pattern;
u8 reply[49];
if (send_subcommand(0x30, &arg, 1, reply) == 0)
printf("[+] LED command acknowledged\n");
else
printf("[-] No response\n");
}
void cmd_test_vibration(void) {
if (!need_device())
return;
printf("\n[*] Sending the rumble confirmation pattern...\n");
send_rumble();
printf("[+] Done\n");
}
// ---------------------------------------------------------------------------------------------
// Calibration (btn_refreshUserCal_Click, btn_writeUserCal_Click, btn_writeStickParams_Click)
struct stick_cal { bool valid; int x_minus, x_center, x_plus, y_minus, y_center, y_plus; };
// Left stick data is ordered max-above-center, center, min-below-center; right stick is
// center, min-below-center, max-above-center.
static stick_cal decode_stick(u8 *d, bool left) {
u16 p[6];
decode_stick_params(p, d);
decode_stick_params(p + 2, d + 3);
decode_stick_params(p + 4, d + 6);
stick_cal c;
c.valid = true;
int center = left ? 2 : 0, minus = left ? 4 : 2, plus = left ? 0 : 4;
c.x_center = p[center]; c.y_center = p[center + 1];
c.x_minus = p[center] - p[minus]; c.y_minus = p[center + 1] - p[minus + 1];
c.x_plus = p[center] + p[plus]; c.y_plus = p[center + 1] + p[plus + 1];
return c;
}
static void print_stick(const char *name, const stick_cal &c) {
if (!c.valid)
printf(" %s: No calibration\n", name);
else
printf(" %s: center (%d, %d) X [%d - %d] Y [%d - %d]\n", name,
c.x_center, c.y_center, c.x_minus, c.x_plus, c.y_minus, c.y_plus);
}
static void print_sensor(const char *name, const u8 *d) {
s16 v[12];
for (int i = 0; i < 12; i++)
v[i] = uint16_to_int16(d[i * 2] | (d[i * 2 + 1] << 8));
printf(" %s Acc: origin %6d %6d %6d sensitivity %6d %6d %6d\n", name, v[0], v[1], v[2], v[3], v[4], v[5]);
printf(" %s Gyro: origin %6d %6d %6d sensitivity %6d %6d %6d\n", name, v[6], v[7], v[8], v[9], v[10], v[11]);
}
void cmd_read_calibration(void) {
if (!need_device())
return;
u8 factory_stick[18] = { 0 }, user_stick[22] = { 0 }, factory_sensor[24] = { 0 }, user_sensor[26] = { 0 };
u8 sensor_model[6] = { 0 }, stick_model[0x24] = { 0 };
get_spi_data(0x603D, 18, factory_stick);
get_spi_data(0x8010, 22, user_stick);
get_spi_data(0x6020, 24, factory_sensor);
get_spi_data(0x8026, 26, user_sensor);
get_spi_data(0x6080, 6, sensor_model);
get_spi_data(0x6086, 0x12, stick_model);
get_spi_data(0x6098, 0x12, stick_model + 0x12);
bool left = handle_type != JOYCON_R, right = handle_type != JOYCON_L;
printf("\nStick calibration (factory):\n");
if (left) print_stick("Left stick ", decode_stick(factory_stick, true));
if (right) print_stick("Right stick", decode_stick(factory_stick + 9, false));
printf("Stick calibration (user):\n");
if (left) {
stick_cal c = { false, 0, 0, 0, 0, 0, 0 };
if ((user_stick[0] | user_stick[1] << 8) == 0xA1B2) c = decode_stick(user_stick + 2, true);
print_stick("Left stick ", c);
}
if (right) {
stick_cal c = { false, 0, 0, 0, 0, 0, 0 };
if ((user_stick[11] | user_stick[12] << 8) == 0xA1B2) c = decode_stick(user_stick + 13, false);
print_stick("Right stick", c);
}
printf("6-axis calibration:\n");
print_sensor("Factory", factory_sensor);
if ((user_sensor[0] | user_sensor[1] << 8) == 0xA1B2)
print_sensor("User ", user_sensor + 2);
else
printf(" User: No calibration\n");
u16 p[2];
printf("Device parameters (factory):\n");
printf(" Flat surface ACC offset: %04X %04X %04X\n",
sensor_model[0] | sensor_model[1] << 8, sensor_model[2] | sensor_model[3] << 8, sensor_model[4] | sensor_model[5] << 8);
decode_stick_params(p, stick_model + 3);
printf(" %s: deadzone %d, range ratio %d\n", handle_type == PROCON ? "Left stick " : "Stick", p[0], p[1]);
if (handle_type == PROCON) {
decode_stick_params(p, stick_model + 0x15);
printf(" Right stick: deadzone %d, range ratio %d\n", p[0], p[1]);
}
}
static void edit_stick(const char *name, stick_cal &c) {
printf("%s:\n", name);
c.x_minus = ask_int(" X minimum", c.x_minus, 0, 0xFFF);
c.x_center = ask_int(" X center ", c.x_center, 0, 0xFFF);
c.x_plus = ask_int(" X maximum", c.x_plus, 0, 0xFFF);
c.y_minus = ask_int(" Y minimum", c.y_minus, 0, 0xFFF);
c.y_center = ask_int(" Y center ", c.y_center, 0, 0xFFF);
c.y_plus = ask_int(" Y maximum", c.y_plus, 0, 0xFFF);
}
// Guided stick calibration (Linux addition, like the window's Calibrate.. button): measures the
// center with the stick at rest, then the range while it's rotated along its edge.
static bool stick_wizard(bool left, stick_cal &c) {
const int Sectors = 24, Samples = 30, MaxSpread = 0x60, MinHalf = 0x300;
u8 mode = 0x30;
u8 reply[49];
send_subcommand(0x03, &mode, 1, reply);
int rx[Samples], ry[Samples], count = 0, pos = 0;
int x = -1, y = -1, cx = 0, cy = 0, lx = 0, hx = 0, ly = 0, hy = 0;
bool sector[Sectors] = { false };
int step = 0;
bool ok = false;
auto stable = [&]() {
if (count < Samples) return false;
int a = 4095, b = 0, e = 4095, f = 0;
for (int i = 0; i < Samples; i++) {
a = std::min(a, rx[i]); b = std::max(b, rx[i]);
e = std::min(e, ry[i]); f = std::max(f, ry[i]);
}
return b - a <= MaxSpread && f - e <= MaxSpread;
};
auto sectors = [&]() { int n = 0; for (bool d : sector) n += d; return n; };
printf("\n1/2 Let go of the stick so it rests at its center, then press Enter (q + Enter: cancel).\n");
auto last_print = std::chrono::steady_clock::now();
while (true) {
u8 buf[49];
int res = jc_hid_read_timeout(handle, buf, 49, 20);
if (res > 12 && (buf[0] == 0x30 || buf[0] == 0x21)) {
u8 *d = buf + (left ? 6 : 9);
x = d[0] | ((d[1] & 0xF) << 8);
y = (d[1] >> 4) | (d[2] << 4);
if (step == 0) {
rx[pos] = x; ry[pos] = y;
pos = (pos + 1) % Samples;
count = std::min(count + 1, Samples);
}
else {
lx = std::min(lx, x); hx = std::max(hx, x);
ly = std::min(ly, y); hy = std::max(hy, y);
int dx = x - cx, dy = y - cy;
if (dx * dx + dy * dy > MinHalf * MinHalf) {
double a = atan2((double)dy, (double)dx) + M_PI;
sector[std::min(Sectors - 1, (int)(a / (2 * M_PI) * Sectors))] = true;
}
}
}
auto now = std::chrono::steady_clock::now();
if (x >= 0 && now - last_print > std::chrono::milliseconds(100)) {
last_print = now;
if (step == 0)
printf("\r Now: X %03X Y %03X %s ", x, y, stable() ? "(at rest)" : "(hold still)");
else
printf("\r Now: X %03X Y %03X X %03X-%03X Y %03X-%03X directions %d/%d ", x, y, lx, hx, ly, hy, sectors(), Sectors);
fflush(stdout);
}
if (!stdin_has_line())
continue;
char line[64];
if (!fgets(line, sizeof(line), stdin) || line[0] == 'q')
break;
if (step == 0) {
if (!stable()) {
printf("\n The stick isn't at rest yet (or no reports). Let go of it and press Enter again.\n");
continue;
}
int sx = 0, sy = 0;
for (int i = 0; i < Samples; i++) { sx += rx[i]; sy += ry[i]; }
cx = (sx + Samples / 2) / Samples;
cy = (sy + Samples / 2) / Samples;
lx = hx = cx; ly = hy = cy;
step = 1;
printf("\n2/2 Slowly rotate the stick along its outer edge, pushed all the way, until every\n"
" direction is covered (2-3 turns). Then press Enter.\n");
continue;
}
if (sectors() < Sectors) {
printf("\n Not every direction yet (%d/%d). Keep rotating, then press Enter.\n", sectors(), Sectors);
continue;
}
if (cx - lx < MinHalf || hx - cx < MinHalf || cy - ly < MinHalf || hy - cy < MinHalf) {
printf("\n The range is too small. Push the stick all the way to its edge while rotating.\n");
continue;
}
c.x_minus = lx; c.x_center = cx; c.x_plus = hx;
c.y_minus = ly; c.y_center = cy; c.y_plus = hy;
printf("\n[+] Measured: X %03X / %03X / %03X Y %03X / %03X / %03X (min / center / max)\n", lx, cx, hx, ly, cy, hy);
ok = true;
break;
}
mode = 0x3F;
send_subcommand(0x03, &mode, 1, reply);
if (!ok)
printf("\nCalibration cancelled.\n");
return ok;
}
static void encode_stick(u8 *out, const stick_cal &c, bool left) {
u16 pair[2];
// Center X,Y
pair[0] = (u16)c.x_center; pair[1] = (u16)c.y_center;
encode_stick_params(out + (left ? 3 : 0), pair);
// +Axis X,Y
pair[0] = (u16)(c.x_plus - c.x_center); pair[1] = (u16)(c.y_plus - c.y_center);
encode_stick_params(out + (left ? 0 : 6), pair);
// -Axis X,Y
pair[0] = (u16)(c.x_center - c.x_minus); pair[1] = (u16)(c.y_center - c.y_minus);
encode_stick_params(out + (left ? 6 : 3), pair);
}
void cmd_edit_calibration(void) {
if (!need_device())
return;
printf("\n 1. User stick and 6-axis calibration\n 2. Stick device parameters (factory)\n 0. Back\n");
int choice = ask_int("Select", 0, 0, 2);
if (choice == 1) {
u8 user_stick_cal[22] = { 0 }, user_sensor_cal[26] = { 0 }, factory_stick[18] = { 0 };
get_spi_data(0x8010, 22, user_stick_cal);
msleep(100);
get_spi_data(0x8026, 26, user_sensor_cal);
msleep(100);
get_spi_data(0x603D, 18, factory_stick);
bool left = handle_type != JOYCON_R, right = handle_type != JOYCON_L;
stick_cal lc = decode_stick(factory_stick, true), rc = decode_stick(factory_stick + 9, false);
bool l_on = false, r_on = false, s_on = false;
if (left && (user_stick_cal[0] | user_stick_cal[1] << 8) == 0xA1B2) { lc = decode_stick(user_stick_cal + 2, true); l_on = true; }
if (right && (user_stick_cal[11] | user_stick_cal[12] << 8) == 0xA1B2) { rc = decode_stick(user_stick_cal + 13, false); r_on = true; }
s_on = (user_sensor_cal[0] | user_sensor_cal[1] << 8) == 0xA1B2;
int acc[3], gyro[3];
for (int i = 0; i < 3; i++) {
acc[i] = user_sensor_cal[2 + i * 2] | user_sensor_cal[3 + i * 2] << 8;
gyro[i] = user_sensor_cal[14 + i * 2] | user_sensor_cal[15 + i * 2] << 8;
}
printf("\nA user calibration that is disabled is erased (the factory one is used).\n");
if (left) {
l_on = ask_yes_no(l_on ? "Keep a left stick user calibration? (currently set)" : "Set a left stick user calibration? (currently none)");
if (l_on) {
if (!ask_yes_no("Measure it with the guided calibration? (n: type the values)") || !stick_wizard(true, lc))
edit_stick("Left stick", lc);
}
}
if (right) {
r_on = ask_yes_no(r_on ? "Keep a right stick user calibration? (currently set)" : "Set a right stick user calibration? (currently none)");
if (r_on) {
if (!ask_yes_no("Measure it with the guided calibration? (n: type the values)") || !stick_wizard(false, rc))
edit_stick("Right stick", rc);
}
}
s_on = ask_yes_no(s_on ? "Keep a 6-axis user calibration? (currently set)" : "Set a 6-axis user calibration? (currently none)");
if (s_on) {
const char *axis[] = { "X", "Y", "Z" };
for (int i = 0; i < 3; i++)
acc[i] = ask_int((std::string(" Acc ") + axis[i] + " origin (0-65535)").c_str(), acc[i], 0, 0xFFFF);
for (int i = 0; i < 3; i++)
gyro[i] = ask_int((std::string(" Gyro ") + axis[i] + " origin (0-65535)").c_str(), gyro[i], 0, 0xFFFF);
}
if (!ask_yes_no("Are you sure you want to continue?"))
return;
memset(user_stick_cal, 0, 22);
memset(user_sensor_cal, 0, 26);
if (left && l_on) {
user_stick_cal[0] = 0xB2; user_stick_cal[1] = 0xA1;
encode_stick(user_stick_cal + 2, lc, true);
}
else
memset(user_stick_cal, 0xFF, 11); // Erase left stick user cal
if (right && r_on) {
user_stick_cal[11] = 0xB2; user_stick_cal[12] = 0xA1;
encode_stick(user_stick_cal + 13, rc, false);
}
else
memset(&user_stick_cal[11], 0xFF, 11); // Erase right stick user cal
if (s_on) {
user_sensor_cal[0] = 0xB2; user_sensor_cal[1] = 0xA1;
for (int i = 0; i < 3; i++) {
user_sensor_cal[2 + i * 2] = acc[i] & 0xFF; user_sensor_cal[3 + i * 2] = acc[i] >> 8;
user_sensor_cal[14 + i * 2] = gyro[i] & 0xFF; user_sensor_cal[15 + i * 2] = gyro[i] >> 8;
}
}
else
memset(user_sensor_cal, 0xFF, 26); // Erase user sensor cal
int res = write_spi_data(0x8010, 22, user_stick_cal);
if (res == 0) {
msleep(100);
res = write_spi_data(0x8026, 26, user_sensor_cal);
}
printf(res == 0 ? "[+] The user calibration was written to SPI!\n" : "[-] Failed to write user calibration to SPI! Please try again..\n");
}
else if (choice == 2) {
u8 main_left[3] = { 0 }, pro_right[3] = { 0 };
u16 p[4] = { 0 };
get_spi_data(0x6089, 3, main_left);