-
Notifications
You must be signed in to change notification settings - Fork 4
/
usbms.c
2479 lines (2269 loc) · 86 KB
/
usbms.c
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
/*
KoboUSBMS: USBMS helper for KOReader
Copyright (C) 2020-2024 NiLuJe <ninuje@gmail.com>
SPDX-License-Identifier: GPL-3.0-or-later
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "usbms.h"
// Wrapper function to use syslog as a libevdev log handler
// c.f., libevdev_dflt_log_func @ libevdev/libevdev.c
__attribute__((format(printf, 7, 0))) static void
libevdev_to_syslog(const struct libevdev* dev __attribute__((unused)),
enum libevdev_log_priority priority,
void* data __attribute__((unused)),
const char* file,
int line,
const char* func,
const char* format,
va_list args)
{
const char* prefix;
switch (priority) {
case LIBEVDEV_LOG_ERROR:
prefix = "libevdev error";
break;
case LIBEVDEV_LOG_INFO:
prefix = "libevdev info";
break;
case LIBEVDEV_LOG_DEBUG:
prefix = "libevdev debug";
break;
default:
prefix = "libevdev INVALID LOG PRIORITY";
break;
}
if (priority == LIBEVDEV_LOG_DEBUG) {
syslog(LOG_INFO, "%s in %s:%d:%s:", prefix, file, line, func);
} else {
syslog(LOG_INFO, "%s in %s:", prefix, func);
}
vsyslog(LOG_INFO, format, args);
}
static void
setup_usb_ids(DEVICE_ID_T device_code)
{
// Map device IDs to USB Product IDs, as we're going to need that in the scripts
// c.f., https://github.com/kovidgoyal/calibre/blob/9d881ed2fcff219887579571f1bb48bdf41437d4/src/calibre/devices/kobo/driver.py#L1402-L1416
// c.f., https://github.com/baskerville/plato/blob/d96e40737060b569ae875f37d6d741fd5ccc802c/contrib/plato.sh#L38-L56
// NOTE: Keep 'em in FBInk order to make my life easier
uint32_t pid = 0xDEAD;
switch (device_code) {
case DEVICE_KOBO_TOUCH_A: // Touch A (trilogy)
case DEVICE_KOBO_TOUCH_B: // Touch B (trilogy)
case DEVICE_KOBO_TOUCH_C: // Touch C (trilogy)
pid = 0x4163;
break;
case DEVICE_KOBO_MINI: // Mini (pixie)
pid = 0x4183;
break;
case DEVICE_KOBO_GLO: // Glo (kraken)
pid = 0x4173;
break;
case DEVICE_KOBO_GLO_HD: // Glo HD (alyssum)
pid = 0x4223;
break;
case DEVICE_KOBO_TOUCH_2: // Touch 2.0 (pika)
pid = 0x4224;
break;
case DEVICE_KOBO_AURA: // Aura (phoenix)
pid = 0x4203;
break;
case DEVICE_KOBO_AURA_HD: // Aura HD (dragon)
pid = 0x4193;
break;
case DEVICE_KOBO_AURA_H2O: // Aura H2O (dahlia)
pid = 0x4213;
break;
case DEVICE_KOBO_AURA_H2O_2: // Aura H2O² (snow)
case DEVICE_KOBO_AURA_H2O_2_R2: // Aura H2O² r2 (snow)
pid = 0x4227;
break;
case DEVICE_KOBO_AURA_ONE: // Aura ONE (daylight)
case DEVICE_KOBO_AURA_ONE_LE: // Aura ONE LE (daylight)
pid = 0x4225;
break;
case DEVICE_KOBO_AURA_SE: // Aura SE (star)
case DEVICE_KOBO_AURA_SE_R2: // Aura SE r2 (star)
pid = 0x4226;
break;
case DEVICE_KOBO_CLARA_HD: // Clara HD (nova)
pid = 0x4228;
break;
case DEVICE_KOBO_FORMA: // Forma (frost)
case DEVICE_KOBO_FORMA_32GB: // Forma 32GB (frost)
pid = 0x4229;
break;
case DEVICE_KOBO_LIBRA_H2O: // Libra H2O (storm)
pid = 0x4232;
break;
case DEVICE_KOBO_NIA: // Nia (luna)
pid = 0x4230;
break;
case DEVICE_KOBO_ELIPSA: // Elipsa (europa)
pid = 0x4233;
break;
case DEVICE_KOBO_LIBRA_2: // Libra 2 (io)
pid = 0x4234;
break;
case DEVICE_KOBO_SAGE: // Sage (cadmus)
pid = 0x4231;
break;
case DEVICE_KOBO_CLARA_2E: // Clara 2E (goldfinch)
pid = 0x4235;
break;
case DEVICE_KOBO_ELIPSA_2E: // Elipsa 2E (condor)
pid = 0x4236;
break;
case DEVICE_KOBO_LIBRA_COLOUR: // Kobo Libra Colour (monza)
pid = 0x4237;
break;
case DEVICE_TOLINO_VISION_COLOR: // Tolino Vision Color (monza)
pid = 0x5237;
break;
case DEVICE_KOBO_CLARA_BW: // Kobo Clara B&W (spa)
pid = 0x4239;
break;
case DEVICE_TOLINO_SHINE_BW: // Tolino Shine B&W (spa)
pid = 0x5239;
break;
case DEVICE_KOBO_CLARA_COLOUR: // Kobo Clara Colour (spa)
pid = 0x4238;
break;
case DEVICE_TOLINO_SHINE_COLOR: // Tolino Shine Color (spa)
pid = 0x5238;
break;
case 0U:
pid = 0x4163;
break;
default:
PFLOG(LOG_WARNING, "Can't match device code (%hu) to a USB Product ID!", device_code);
break;
}
// Push it to the env…
char pid_str[8] = { 0 };
snprintf(pid_str, sizeof(pid_str) - 1U, "0x%04X", pid);
PFLOG(LOG_NOTICE, "USB product ID: %s", pid_str);
setenv("USB_PRODUCT_ID", pid_str, 1);
}
static bool
ioctl_is_usb_plugged(int ntxfd, bool foo __attribute__((unused)))
{
// Check if we're plugged in…
unsigned long ptr = 0U;
int rc = ioctl(ntxfd, CM_USB_Plug_IN, &ptr);
if (rc == -1) {
PFLOG(LOG_WARNING, "Could not query USB status (ioctl: %m)");
}
return !!ptr;
}
static bool
sysfs_is_usb_plugged(int foo __attribute__((unused)), bool log_status)
{
bool is_plugged = false;
FILE* f = fopen(BATT_STATUS_SYSFS, "re");
if (f) {
char status[16] = { 0 };
size_t size = fread(status, sizeof(*status), sizeof(status) - 1U, f);
fclose(f);
if (size > 0) {
// Strip trailing LF
if (status[size - 1U] == '\n') {
status[size - 1U] = '\0';
}
if (log_status) {
LOG(LOG_DEBUG, "Battery status: %s", status);
}
} else {
LOG(LOG_WARNING, "Could not read the battery status from sysfs!");
}
// c.f., power_supply_show_property @ drivers/power/supply/power_supply_sysfs.c
// & include/linux/power_supply.h
// NOTE: Match the behavior of the NXP ntx_io ioctl (c.f., _Is_USB_plugged):
// false if discharging, true otherwise.
// NOTE: The charger type check ought to then confirm that…
if (strncmp(status, "Unknown", 7U) == 0U) {
is_plugged = true;
} else if (strncmp(status, "Charging", 8U) == 0U) {
is_plugged = true;
} else if (strncmp(status, "Discharging", 11U) == 0U) {
is_plugged = false;
} else if (strncmp(status, "Not charging", 12U) == 0U) {
is_plugged = true;
} else if (strncmp(status, "Full", 4U) == 0U) {
is_plugged = true;
}
}
return is_plugged;
}
static bool
sysfs_is_usb_online(int foo __attribute__((unused)), bool log_status)
{
bool is_plugged = false;
FILE* f = fopen(USB_ONLINE_SYSFS, "re");
if (f) {
char status[16] = { 0 };
size_t size = fread(status, sizeof(*status), sizeof(status) - 1U, f);
fclose(f);
if (size > 0) {
// Strip trailing LF
if (status[size - 1U] == '\n') {
status[size - 1U] = '\0';
}
if (log_status) {
LOG(LOG_DEBUG, "USB power supply online: %s", status);
}
} else {
LOG(LOG_WARNING, "Could not read the usb online entry from sysfs!");
}
// NOTE: Match the behavior of the NXP ntx_io ioctl (c.f., _Is_USB_plugged when HWConfig says PMIC == BD71828):
// false if 0, true otherwise.
// NOTE: The charger type check ought to then confirm that…
if (status[0] == '0') {
is_plugged = false;
} else {
is_plugged = true;
}
}
return is_plugged;
}
// Check if the standalone USB-C controller thinks there's something plugged in
// c.f., drivers/input/misc/P15USB30216C.c
static int
is_usbc_plugged(bool log_status)
{
// Only found on a few Mk. 8 & Mk. 9 boards...
if (!USBC_PLUG_SYSFS) {
return -1;
}
FILE* f = fopen(USBC_PLUG_SYSFS, "re");
if (!f) {
return -1;
}
bool is_plugged = false;
char usbc_conn[8] = { 0 };
size_t size = fread(usbc_conn, sizeof(*usbc_conn), sizeof(usbc_conn) - 1U, f);
fclose(f);
f = NULL;
if (size > 0) {
// Strip trailing LF
if (usbc_conn[size - 1U] == '\n') {
usbc_conn[size - 1U] = '\0';
}
}
// Should only ever be 0 or 1
// NOTE: The i2c read exposes more information about what kind of device is on the other end of the cable,
// but that information is, sadly, lost to us (it *is* printed to dmesg, at least).
if (usbc_conn[0] == '1') {
is_plugged = true;
}
if (log_status) {
LOG(LOG_DEBUG,
"Standalone USB-C controller cable detection: %s",
is_plugged ? "Connected" : "Disconnected");
}
return is_plugged;
}
// Return a fancy battery icon given the charge percentage…
static const char*
get_battery_icon(uint8_t charge)
{
if (charge >= 100) {
return "\U000f0079";
} else if (charge >= 90) {
return "\U000f0082";
} else if (charge >= 80) {
return "\U000f0081";
} else if (charge >= 70) {
return "\U000f0080";
} else if (charge >= 60) {
return "\U000f007f";
} else if (charge >= 50) {
return "\U000f007e";
} else if (charge >= 40) {
return "\U000f007d";
} else if (charge >= 30) {
return "\U000f007c";
} else if (charge >= 20) {
return "\U000f007b";
} else if (charge >= 10) {
return "\U000f007a";
} else {
return "\U000f0083";
}
}
// NOTE: Inspired from git's strtoul_ui @ git-compat-util.h
static int
strtoul_hhu(const char* str, uint8_t* restrict result)
{
// NOTE: We want to *reject* negative values (which strtoul does not)!
if (strchr(str, '-')) {
PFLOG(LOG_WARNING, "Passed a negative value (`%s`) to strtoul_hhu", str);
return -EINVAL;
}
// Now that we know it's positive, we can go on with strtoul…
char* endptr;
errno = 0; // To distinguish success/failure after call
unsigned long int val = strtoul(str, &endptr, 10);
if ((errno == ERANGE && val == ULONG_MAX) || (errno != 0 && val == 0)) {
PFLOG(LOG_WARNING, "strtoul: %m");
return -EINVAL;
}
// NOTE: It fact, always clamp to CHAR_MAX, since we may need to cast to a signed representation later.
if (val > CHAR_MAX) {
PFLOG(LOG_WARNING, "Passed a value larger than CHAR_MAX to strtoul_hhu, clamping it down to CHAR_MAX");
val = CHAR_MAX;
}
if (endptr == str) {
PFLOG(LOG_WARNING, "No digits were found in value `%s` assigned to a variable expecting an uint8_t", str);
return -EINVAL;
}
// If we got here, strtoul() successfully parsed at least part of a number.
// But we do want to enforce the fact that the input really was *only* an integer value.
if (*endptr != '\0') {
PFLOG(
LOG_WARNING,
"Found trailing characters (`%s`) behind value '%lu' assigned from string `%s` to a variable expecting an uint8_t",
endptr,
val,
str);
return -EINVAL;
}
// Make sure there isn't a loss of precision on this arch when casting explicitly
if ((uint8_t) val != val) {
PFLOG(LOG_WARNING, "Loss of precision when casting value '%lu' to an uint8_t.", val);
return -EINVAL;
}
*result = (uint8_t) val;
return EXIT_SUCCESS;
}
// Pilfered from NickelMenu ;).
// c.f., https://github.com/pgaskin/NickelMenu/blob/85cd558715886069e70cbdcb1f9de43843e49e9f/src/util.h#L14-L23
static char*
strtrim(char* s)
{
if (!s) {
return NULL;
}
char* a = s;
char* b = s + strlen(s);
for (; a < b && isspace((unsigned char) (*a)); a++) {
;
}
for (; b > a && isspace((unsigned char) (*(b - 1))); b--) {
;
}
*b = '\0';
return a;
}
// Based on timespecsub from <bsd/sys/time.h>
static void
timespec_delta(struct timespec* t2, struct timespec* t1, struct timespec* td)
{
td->tv_sec = t2->tv_sec - t1->tv_sec;
td->tv_nsec = t2->tv_nsec - t1->tv_nsec;
if (td->tv_nsec < 0) {
td->tv_sec--;
td->tv_nsec += 1000000000L;
}
}
static time_t
elapsed_time(struct timespec* t2, struct timespec* t1)
{
// Compute the elapsed time between the two timestamps
struct timespec td = { 0 };
timespec_delta(t2, t1, &td);
// We don't need nanosecond precision, just round up if necessary
if (td.tv_nsec >= 500000000L) {
td.tv_sec++;
td.tv_nsec = 0;
}
return td.tv_sec;
}
// Yield for a bit on devices where we can't rely on MXCFB_WAIT_FOR_UPDATE_COMPLETE...
static int
stub_wait_for_update_complete(int fbfd __attribute__((unused)), uint32_t marker __attribute__((unused)))
{
// c.f., https://github.com/koreader/koreader-base/blob/21f4b974c7ab64a149075adc32318f87bf71dcdc/ffi/framebuffer_mxcfb.lua#L230-L235
const struct timespec zzz = { 0L, 250 * 1000000L }; // 250ms
return nanosleep(&zzz, NULL);
}
// Attempt to figure out the current frontlight intensity…
static uint8_t
get_frontlight_intensity(void)
{
// If all else fails, don't touch the FL by ensuring we return 0
uint8_t intensity = 0U;
// On Mk. 7, we can actually get it from sysfs, making our life far easier…
FILE* f = fopen(FL_INTENSITY_SYSFS, "re");
if (f) {
char fl_intensity[8] = { 0 };
size_t size = fread(fl_intensity, sizeof(*fl_intensity), sizeof(fl_intensity) - 1U, f);
fclose(f);
f = NULL;
if (size > 0) {
// Strip trailing LF
if (fl_intensity[size - 1U] == '\n') {
fl_intensity[size - 1U] = '\0';
}
}
if (strtoul_hhu(fl_intensity, &intensity) < 0) {
PFLOG(LOG_WARNING,
"Could not convert sysfs frontlight intensity value `%s` to an uint8_t!",
fl_intensity);
} else {
// We're good, don't bother trying to parse KOReader's settings!
PFLOG(LOG_INFO, "sysfs says frontlight intensity is at %hhu%%", intensity);
return intensity;
}
}
const char* ko_dir = getenv("KOREADER_DIR");
if (!ko_dir) {
PFLOG(LOG_WARNING, "Unable to compute KOReader directory!");
return intensity;
}
// Now, try to parse KOReader's settings…
char ko_settings[PATH_MAX] = { 0 };
snprintf(ko_settings, sizeof(ko_settings) - 1U, "%s/settings.reader.lua", ko_dir);
f = fopen(ko_settings, "re");
if (f) {
bool found_state = false;
bool fl_state = false;
bool found_intensity = false;
uint8_t fl_intensity = 0U;
char* line = NULL;
line = calloc(PIPE_BUF, sizeof(*line));
if (!line) {
PFLOG(LOG_ERR, "calloc: %m");
fclose(f);
return intensity;
}
while (fgets(line, PIPE_BUF, f)) {
char* cur_line = line;
if (strstr(cur_line, "[\"is_frontlight_on\"]")) {
char* setting_key = strsep(&cur_line, "=");
if (!setting_key) {
PFLOG(LOG_WARNING,
"Could not parse 'is_frontline_on' in KOReader's settings (key)");
continue;
}
char* setting_value = strsep(&cur_line, ",");
if (!setting_value) {
PFLOG(LOG_WARNING,
"Could not parse 'is_frontline_on' in KOReader's settings (value)");
continue;
}
setting_value = strtrim(setting_value);
if (strcmp(setting_value, "true") == 0) {
found_state = true;
fl_state = true;
PFLOG(LOG_INFO, "Frontlight is enabled in KOReader");
} else if (strcmp(setting_value, "false") == 0) {
found_state = true;
fl_state = false;
PFLOG(LOG_INFO, "Frontlight is disabled in KOReader");
} else {
PFLOG(LOG_WARNING,
"Could not parse 'is_frontline_on' value! (`%s`)",
setting_value);
}
} else if (strstr(cur_line, "[\"frontlight_intensity\"]")) {
char* setting_key = strsep(&cur_line, "=");
if (!setting_key) {
PFLOG(LOG_WARNING,
"Could not parse 'frontlight_intensity' in KOReader's settings (key)");
continue;
}
char* setting_value = strsep(&cur_line, ",");
if (!setting_value) {
PFLOG(LOG_WARNING,
"Could not parse 'frontlight_intensity' in KOReader's settings (value)");
continue;
}
setting_value = strtrim(setting_value);
if (strtoul_hhu(setting_value, &fl_intensity) < 0) {
PFLOG(LOG_WARNING,
"Could not convert KOReader frontlight intensity value `%s` to an uint8_t!",
setting_value);
} else {
found_intensity = true;
PFLOG(LOG_INFO, "KOReader says frontlight intensity is at %hhu%%", fl_intensity);
}
}
// If we've found & parsed both state & intensity, we're golden
if (found_intensity && found_state) {
// And if it is actually enabled, update the return value
if (fl_state) {
intensity = fl_intensity;
}
break;
}
}
fclose(f);
free(line);
}
return intensity;
}
// Fancy frontlight toggle :)
// Based on a PoC tested in https://github.com/koreader/koreader/pull/5421#discussion_r327812380
static void
toggle_frontlight(bool state, uint8_t intensity, int ntxfd)
{
#define STEPS 20u
#define SLEEP 7u // in ms
// NOTE: The ioctl on newer devices actually blocks for noticeably longer than on older devices,
// c.f., https://github.com/koreader/koreader/blob/b40331085a565f99a95c27012b1aa3e71e3eb182/frontend/device/kobo/powerd.lua#L331-L332
// Here, we get away with this thanks to the larger amount of steps, combined with the fact that on newer devices,
// the ioctl won't block as long if it's called with the same requested intensity as the current intensity.
const struct timespec zzz = { 0L, SLEEP * 1000000L };
if (state == false) {
// Ramp-down
for (uint8_t i = 1U; i <= STEPS; i++) {
int ptr = ifloorf(intensity - ((intensity / (float) STEPS) * i));
int rc = ioctl(ntxfd, CM_FRONT_LIGHT_SET, ptr);
if (rc == -1) {
PFLOG(LOG_WARNING, "Could not set frontlight intensity to %d%% (ioctl: %m)", ptr);
}
if (i < STEPS) {
nanosleep(&zzz, NULL);
}
}
} else {
// Ramp-up
for (uint8_t i = 1U; i <= STEPS; i++) {
int ptr = iceilf(0U + ((intensity / (float) STEPS) * i));
int rc = ioctl(ntxfd, CM_FRONT_LIGHT_SET, ptr);
if (rc == -1) {
PFLOG(LOG_WARNING, "Could not set frontlight intensity to %d%% (ioctl: %m)", ptr);
}
if (i < STEPS) {
nanosleep(&zzz, NULL);
}
}
}
}
// Check if there's an auxiliary battery connected (e.g., the Sage's PowerCover).
static bool
is_aux_battery_connected(void)
{
FILE* f = fopen(CILIX_CONNECTED_SYSFS, "re");
if (f) {
char cilix_conn[8] = { 0 };
size_t size = fread(cilix_conn, sizeof(*cilix_conn), sizeof(cilix_conn) - 1U, f);
fclose(f);
f = NULL;
if (size > 0) {
// Strip trailing LF
if (cilix_conn[size - 1U] == '\n') {
cilix_conn[size - 1U] = '\0';
}
}
// Check if the PowerCover is currently connected
if (cilix_conn[0] == '1') {
return true;
}
}
return false;
}
// We'll want to regularly update a display of the plug/charge status, and whether Wi-Fi is on or not
static void
print_status(const USBMSContext* ctx)
{
// Check if we're plugged in…
bool usb_plugged = (*fxpIsUSBPlugged)(ctx->ntxfd, false);
// Get the battery charge %
uint8_t batt_perc = 0U;
FILE* f = fopen(BATT_CAP_SYSFS, "re");
if (f) {
char batt_charge[8] = { 0 };
size_t size = fread(batt_charge, sizeof(*batt_charge), sizeof(batt_charge) - 1U, f);
fclose(f);
if (size > 0) {
// Strip trailing LF
if (batt_charge[size - 1U] == '\n') {
batt_charge[size - 1U] = '\0';
}
}
if (strtoul_hhu(batt_charge, &batt_perc) < 0) {
PFLOG(LOG_WARNING, "Could not convert battery charge value `%s` to an uint8_t!", batt_charge);
}
}
// Check if there's a PowerCover
bool has_aux_battery = false;
uint8_t aux_batt_perc = 0U;
if (ctx->fbink_state.device_id == DEVICE_KOBO_SAGE) {
has_aux_battery = is_aux_battery_connected();
if (has_aux_battery) {
f = fopen(CILIX_BATT_CAP_SYSFS, "re");
if (f) {
char cilix_charge[8] = { 0 };
size_t size = fread(cilix_charge, sizeof(*cilix_charge), sizeof(cilix_charge) - 1U, f);
fclose(f);
if (size > 0) {
// Strip trailing LF
if (cilix_charge[size - 1U] == '\n') {
cilix_charge[size - 1U] = '\0';
}
}
if (strtoul_hhu(cilix_charge, &aux_batt_perc) < 0) {
PFLOG(LOG_WARNING,
"Could not convert cilix charge value `%s` to an uint8_t!",
cilix_charge);
}
}
}
}
// Check for Wi-Fi status
// (c.f., https://github.com/koreader/koreader/blob/b5d33058761625111d176123121bcc881864a64e/frontend/device/kobo/device.lua#L451-L471)
bool wifi_up = false;
char if_sysfs[PATH_MAX] = { 0 };
snprintf(if_sysfs, sizeof(if_sysfs) - 1U, "/sys/class/net/%s/carrier", getenv("INTERFACE"));
f = fopen(if_sysfs, "re");
if (f) {
char carrier[8] = { 0 };
size_t size = fread(carrier, sizeof(*carrier), sizeof(carrier) - 1U, f);
fclose(f);
if (size > 0) {
// Strip trailing LF
if (carrier[size - 1U] == '\n') {
carrier[size - 1U] = '\0';
}
}
// If there's a carrier, Wi-Fi is up.
if (carrier[0] == '1') {
wifi_up = true;
}
}
// Display the time
time_t t = time(NULL);
struct tm local_tm;
struct tm* lt = localtime_r(&t, &local_tm);
char sz_time[6] = { 0 };
strftime(sz_time, sizeof(sz_time), "%H:%M", lt);
if (has_aux_battery) {
fbink_printf(ctx->fbfd,
&ctx->ot_cfg,
&ctx->fbink_cfg,
NULL,
"%s • \uf017 %s • %s (%hhu%%) + %s (%hhu%%) • %s",
usb_plugged ? "\U000f06a5" : "\U000f06a6",
sz_time,
get_battery_icon(batt_perc),
batt_perc,
get_battery_icon(aux_batt_perc),
aux_batt_perc,
wifi_up ? "\U000f05a9" : "\U000f05aa");
} else {
fbink_printf(ctx->fbfd,
&ctx->ot_cfg,
&ctx->fbink_cfg,
NULL,
"%s • \uf017 %s • %s (%hhu%%) • %s",
usb_plugged ? "\U000f06a5" : "\U000f06a6",
sz_time,
get_battery_icon(batt_perc),
batt_perc,
wifi_up ? "\U000f05a9" : "\U000f05aa");
}
}
static void
print_icon(const char* string, USBMSContext* ctx)
{
ctx->fbink_cfg.is_halfway = true;
fbink_print_ot(ctx->fbfd, string, &ctx->icon_cfg, &ctx->fbink_cfg, NULL);
ctx->fbink_cfg.is_halfway = false;
}
static int
print_msg(const char* string, USBMSContext* ctx)
{
return fbink_print_ot(ctx->fbfd, string, &ctx->msg_cfg, &ctx->fbink_cfg, NULL);
}
static int
print_countdown(time_t left, USBMSContext* ctx)
{
if (ctx->fbink_state.device_id == DEVICE_KOBO_NIA) {
// NOTE: Device is plagued by the random EPDC hangs, but *doesn't* allow poking the EPDC's PM via sysfs,
// so, skip the whole thing to avoid crashing...
return ERRCODE(ENOSYS);
}
const char* icon = NULL;
switch (left % 3) {
case 0:
icon = "\U0000f251";
break;
case 1:
icon = "\U0000f253";
break;
case 2:
icon = "\U0000f252";
break;
default:
icon = "\U0000f254";
break;
}
// NOTE: Because this turns out to be a very good test-case for that kernel issue ;).
// Plus, we're essentially a callback running from a timerfd, which offers us perfectly controlled timing.
// And given that we'll be plugged-in most of the rest of the time,
// this is the only place where we're at a *significant* risk of triggering the hang.
// (I mean, it took me relatively massive efforts to repro the issue on my Clara 2E when I originally looked into it,
// and this made it crash after 42s on the first try...).
fbink_wakeup_epdc();
return fbink_printf(ctx->fbfd, &ctx->countdown_cfg, &ctx->fbink_cfg, NULL, "%s %lld", icon, (long long int) left);
}
static int
clear_countdown(USBMSContext* ctx)
{
return fbink_print_ot(ctx->fbfd, " ", &ctx->countdown_cfg, &ctx->fbink_cfg, NULL);
}
// Poor man's grep in /proc/modules
__attribute((nonnull(1))) static bool
is_module_loaded(const char* needle)
{
FILE* f = fopen("/proc/modules", "re");
if (f) {
char line[PIPE_BUF];
size_t len = strlen(needle);
while (fgets(line, sizeof(line), f)) {
if (strncmp(line, needle, len) == 0) {
fclose(f);
return true;
}
}
fclose(f);
}
return false;
}
// Parse an evdev event, looking for a power button press
static bool
handle_evdev(struct libevdev* dev)
{
int rc = 1;
do {
struct input_event ev;
rc = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL, &ev);
if (rc == LIBEVDEV_READ_STATUS_SYNC) {
while (rc == LIBEVDEV_READ_STATUS_SYNC) {
// NOTE: We're ignoring the sync delta events here.
rc = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_SYNC, &ev);
}
} else if (rc == LIBEVDEV_READ_STATUS_SUCCESS) {
// Check if it's a power button press (well, release, actually)
if (libevdev_event_is_code(&ev, EV_KEY, KEY_POWER) == 1 && ev.value == 0) {
return true;
}
}
} while (rc == LIBEVDEV_READ_STATUS_SYNC || rc == LIBEVDEV_READ_STATUS_SUCCESS);
if (rc != LIBEVDEV_READ_STATUS_SUCCESS && rc != -EAGAIN) {
PFLOG(LOG_ERR, "Failed to handle input events: %s", strerror(-rc));
}
return false;
}
// Parse an evdev event, looking for a SW_DOCK switch
static int
handle_usbc_evdev(struct libevdev* dev)
{
int rc = 1;
do {
struct input_event ev;
rc = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL, &ev);
if (rc == LIBEVDEV_READ_STATUS_SYNC) {
while (rc == LIBEVDEV_READ_STATUS_SYNC) {
// NOTE: We're ignoring the sync delta events here.
rc = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_SYNC, &ev);
}
} else if (rc == LIBEVDEV_READ_STATUS_SUCCESS) {
// If it's a SW_DOCK switch, return the value
if (libevdev_event_is_code(&ev, EV_SW, SW_DOCK) == 1) {
LOG(LOG_NOTICE, "Caught a USB-C plug %s event", ev.value ? "in" : "out");
return ev.value;
}
}
} while (rc == LIBEVDEV_READ_STATUS_SYNC || rc == LIBEVDEV_READ_STATUS_SUCCESS);
if (rc != LIBEVDEV_READ_STATUS_SUCCESS && rc != -EAGAIN) {
PFLOG(LOG_ERR, "Failed to handle input events: %s", strerror(-rc));
}
return -1;
}
// Parse an uevent
static int
handle_uevent(struct uevent_listener* l, struct uevent* uevp)
{
ue_reset_event(uevp);
ssize_t len = xread(l->pfd.fd, uevp->buf, sizeof(uevp->buf) - 1U);
if (len == -1) {
if (errno == ENOBUFS) {
// NOTE: Unlike ue_wait_for_event, don't recover:
// since events were most likely lost, we'll consider this fatal
PFLOG(LOG_WARNING, "uevent overrun!");
}
PFLOG(LOG_CRIT, "read: %m");
return ERR_LISTENER_RECV;
}
char* end = uevp->buf + len;
*end = '\0';
int rc = ue_parse_event_msg(uevp, (size_t) len);
if (rc == EXIT_SUCCESS) {
PFLOG(LOG_DEBUG, "uevent successfully parsed");
return EXIT_SUCCESS;
} else if (rc == ERR_PARSE_UDEV) {
PFLOG(LOG_DEBUG, "skipped %zd bytes udev uevent: `%.*s`", len, (int) len, uevp->buf);
} else if (rc == ERR_PARSE_INVALID_HDR) {
PFLOG(LOG_DEBUG, "skipped %zd bytes malformed uevent: `%.*s`", len, (int) len, uevp->buf);
} else {
PFLOG(LOG_DEBUG, "skipped %zd bytes unsupported uevent: `%.*s`", len, (int) len, uevp->buf);
}
return EXIT_FAILURE;
}
int
main(void)
{
// So far, so good ;).
int rv = EXIT_SUCCESS;
int pwd = -1;
char* abs_pwd = NULL;
bool is_CJK = false;
struct uevent_listener listener = { 0 };
listener.pfd.fd = -1;
struct libevdev* dev = NULL;
USBMSContext ctx = { 0 };
int evfd = -1;
int clockfd = -1;
int countdown_fd = -1;
struct libevdev* usbc_dev = NULL;
int usbc_fd = -1;
// Close any non-standard fds before we open any ourselves (this should be a NOP on sane launchers)
bsd_closefrom(3);
// We'll be chatting exclusively over syslog, because duh.
openlog("usbms", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_DAEMON);
// Say hello
LOG(LOG_INFO, "Initializing USBMS %s (%s)", USBMS_VERSION, USBMS_TIMESTAMP);
// Redirect stdin/stdout/stderr to /dev/null
int fd = open("/dev/null", O_RDONLY);
if (fd != -1) {
dup2(fd, fileno(stdin));
close(fd);
} else {
PFLOG(LOG_CRIT, "open(\"/dev/null\", O_RDONLY): %m");
rv = USBMS_EARLY_EXIT;
goto cleanup;
}
fd = open("/dev/null", O_RDWR);
if (fd != -1) {
dup2(fd, fileno(stdout));
dup2(fd, fileno(stderr));
close(fd);
} else {
PFLOG(LOG_CRIT, "open(\"/dev/null\", O_RDWR): %m");
rv = USBMS_EARLY_EXIT;
goto cleanup;
}
// We'll want to jump to /, and only get back to our original PWD on exit…
// c.f., man getcwd for the fchdir trick, as we can certainly spare the fd ;).
// NOTE: While using O_PATH would be nice, the flag itself is Linux 2.6.39+,
// but, more importantly, the resulting fd is only usable with fchdir since Linux 3.5+…
// And, of course, Mk. 6 devices are smack in that sweet spot: they run Linux 3.0.35,
// where O_PATH is supported, but not by fchdir ;).
pwd = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (pwd == -1) {
PFLOG(LOG_CRIT, "open(\".\"): %m");
rv = USBMS_EARLY_EXIT;
goto cleanup;
}
// We do need the pathname to load resources, though…
abs_pwd = get_current_dir_name();
if (chdir("/") == -1) {
PFLOG(LOG_CRIT, "chdir(\"/\"): %m");
rv = USBMS_EARLY_EXIT;
goto cleanup;
}
char resource_path[PATH_MAX] = { 0 };
// Make sure we have a klogd instance redirecting the kernel logs to syslog, so we get some context interleaved with our own logging.
snprintf(resource_path, sizeof(resource_path) - 1U, "%s/scripts/launch-klogd.sh", abs_pwd);
system(resource_path);
// NOTE: The font we ship only covers LGC scripts. Blacklist a few languages where we know it won't work,
// based on KOReader's own language list (c.f., frontend/ui/language.lua).
// Because English is better than the replacement character ;p.
// We do jump through a few hoops to attempt to salvage CJK support…
const char* lang = getenv("LANGUAGE");
if (lang) {
if (strncmp(lang, "he", 2U) == 0 || strncmp(lang, "ar", 2U) == 0 || strncmp(lang, "fa", 2U) == 0) {
LOG(LOG_NOTICE, "Your language (%s) is unsupported (RTL), falling back to English", lang);
setenv("LANGUAGE", "C", 1);
} else if (strncmp(lang, "bn", 2U) == 0 || strncmp(lang, "hi", 2U) == 0) {
LOG(LOG_NOTICE, "Your language (%s) is unsupported (!LGC), falling back to English", lang);
setenv("LANGUAGE", "C", 1);
} else if (strncmp(lang, "ja", 2U) == 0 || strncmp(lang, "ko", 2U) == 0 || strncmp(lang, "zh", 2U) == 0) {
LOG(LOG_NOTICE, "Your language (%s) may be badly handled (CJK)!", lang);
// If we don't actually have a translation ready, don't set the CJK flag, and fallback to English.
snprintf(
resource_path, sizeof(resource_path) - 1U, "%s/l10n/%s/LC_MESSAGES/usbms.mo", abs_pwd, lang);
if (access(resource_path, F_OK) == 0) {
is_CJK = true;