FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
HeadsetControl/cli/main.cpp at master · Sapd/HeadsetControl · GitHub
Sapd
/
HeadsetControl
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
236
Star
1.9k
Code
Issues
42
Pull requests
2
Discussions
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
HeadsetControl
/
cli
/
main.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
1283 lines (1089 loc) · 49.2 KB
Breadcrumbs
HeadsetControl
/
cli
/
main.cpp
Copy path
File metadata and controls
1283 lines (1089 loc) · 49.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
**
Copyright (C) 2016-2025 Denis Arnst (Sapd) <https://github.com/Sapd>
This file is part of HeadsetControl.
HeadsetControl 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.
HeadsetControl 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 HeadsetControl. If not, see <http://www.gnu.org/licenses/>.
**
*/
#
include
"
argument_parser.hpp
"
#
include
"
capability_descriptors.hpp
"
#
include
"
dev.hpp
"
#
include
"
device.hpp
"
#
include
"
device_registry.hpp
"
#
include
"
devices/hid_device.hpp
"
#
include
"
feature_handlers.hpp
"
#
include
"
feature_utils.hpp
"
#
include
"
headsetcontrol.hpp
"
#
include
"
hid_utility.hpp
"
#
include
"
output.hpp
"
#
include
"
result_types.hpp
"
#
include
"
utility.hpp
"
#
include
"
version.h
"
#
include
<
hidapi.h
>
#
include
<
algorithm
>
#
include
<
cassert
>
#
include
<
chrono
>
#
include
<
csignal
>
#
include
<
cstdio
>
#
include
<
cstdlib
>
#
include
<
format
>
#
include
<
iostream
>
#
include
<
memory
>
#
include
<
optional
>
#
include
<
string
>
#
include
<
string_view
>
#
include
<
thread
>
#
include
<
unordered_map
>
#
include
<
vector
>
// ============================================================================
//
Namespace imports
// ============================================================================
using
headsetcontrol::DeviceRegistry;
using
headsetcontrol::HIDDevice;
using
headsetcontrol::make_battery_result;
using
headsetcontrol::make_error;
using
headsetcontrol::make_success;
//
Forward declaration for C++ device registry initialization
extern
"
C
"
void
init_cpp_devices
();
namespace
{
//
NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables)
//
Must be non-const: modified by signal handler for graceful shutdown
volatile
sig_atomic_t
g_follow_running =
false
;
//
NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
// ============================================================================
//
Output helpers
// ============================================================================
template
<
typename
... Args>
void
print
(std::format_string<Args...> fmt, Args&&... args)
{
std::cout <<
std::format
(fmt, std::forward<Args>(args)...);
}
template
<
typename
... Args>
void
println
(std::format_string<Args...> fmt, Args&&... args)
{
std::cout <<
std::format
(fmt, std::forward<Args>(args)...) <<
'
\n
'
;
}
inline
void
println
()
{
std::cout <<
'
\n
'
;
}
template
<
typename
... Args>
void
eprintln
(std::format_string<Args...> fmt, Args&&... args)
{
std::cerr <<
std::format
(fmt, std::forward<Args>(args)...) <<
'
\n
'
;
}
//
Convert platform bitmask to string for README table output
[[nodiscard]]
constexpr
const
char
*
platformsToTableString
(
uint8_t
platforms)
{
if
(platforms ==
PLATFORM_ALL
)
return
"
All
"
;
if
(platforms == (
PLATFORM_LINUX
|
PLATFORM_MACOS
))
return
"
L/M
"
;
if
(platforms == (
PLATFORM_LINUX
|
PLATFORM_WINDOWS
))
return
"
L/W
"
;
if
(platforms ==
PLATFORM_LINUX
)
return
"
L
"
;
return
"
?
"
;
}
// ============================================================================
//
Command-line options - Clean data structure
// ============================================================================
struct
Options
{
//
Device selection
uint16_t
vendor_id =
0
;
uint16_t
product_id =
0
;
//
Mode flags
bool
show_help =
false
;
bool
show_help_all =
false
;
bool
show_version =
false
;
bool
print_udev_rules =
false
;
bool
print_capabilities =
false
;
bool
dev_mode =
false
;
bool
test_device =
false
;
bool
follow_mode =
false
;
bool
request_connected =
false
;
unsigned
follow_seconds =
2
;
//
Output format
OutputType output_format =
OUTPUT_STANDARD
;
//
Feature settings
std::optional<
uint8_t
> sidetone_level;
std::optional<
uint8_t
> notification_sound;
std::optional<
bool
> lights_enabled;
std::optional<
uint8_t
> inactive_time;
std::optional<
bool
> voice_prompts_enabled;
std::optional<
bool
> rotate_to_mute_enabled;
std::optional<
uint8_t
> equalizer_preset;
std::optional<
uint8_t
> mic_mute_led_brightness;
std::optional<
uint8_t
> mic_volume;
std::optional<
bool
> volume_limiter_enabled;
std::optional<
bool
> bt_when_powered_on;
std::optional<
uint8_t
> bt_call_volume;
std::optional<
uint8_t
> noise_filter;
//
Info requests
bool
request_battery =
false
;
bool
request_chatmix =
false
;
bool
request_sidetone =
false
;
//
Complex settings
std::optional<EqualizerSettings> equalizer;
std::optional<ParametricEqualizerSettings> parametric_equalizer;
//
Helper
[[nodiscard]]
bool
hasDeviceFilter
()
const
{
return
vendor_id !=
0
|| product_id !=
0
;
}
[[nodiscard]]
bool
matchesDevice
(
uint16_t
vid,
uint16_t
pid)
const
{
return
(vendor_id ==
0
|| vendor_id == vid) && (product_id ==
0
|| product_id == pid);
}
};
// ============================================================================
//
Argument parser configuration - Declarative option definitions
// ============================================================================
std::optional<cli::ParseError>
configureParser
(cli::ArgumentParser& parser, Options& opts)
{
//
Output format choices
static
const
std::unordered_map<std::string, OutputType> output_formats = {
{
"
JSON
"
,
OUTPUT_JSON
},
{
"
YAML
"
,
OUTPUT_YAML
},
{
"
ENV
"
,
OUTPUT_ENV
},
{
"
STANDARD
"
,
OUTPUT_STANDARD
},
{
"
SHORT
"
,
OUTPUT_SHORT
}
};
parser
//
=== Device Selection ===
.
custom
(
'
d
'
,
"
device
"
, cli::ArgRequirement::Required, [&opts](std::optional<std::string_view> arg) -> std::optional<cli::ParseError> {
if
(!arg)
return
cli::ParseError {
"
requires vendor:product
"
,
"
device
"
};
auto
ids =
headsetcontrol::parse_two_ids
(*arg);
if
(!ids) {
return
cli::ParseError {
"
format: vendorid:productid
"
,
"
device
"
};
}
opts.
vendor_id
=
static_cast
<
uint16_t
>(ids->
first
);
opts.
product_id
=
static_cast
<
uint16_t
>(ids->
second
);
return
std::
nullopt
; },
"
Select device by vendor:product ID
"
)
//
=== Help & Version ===
.
flag
(
'
h
'
,
"
help
"
, opts.
show_help
,
"
Show help message
"
)
.
long_flag
(
"
help-all
"
, opts.
show_help_all
,
"
Show all options including advanced
"
)
.
long_flag
(
"
version
"
, opts.
show_version
,
"
Show version information
"
)
//
=== Feature Controls ===
.
custom
(
'
s
'
,
"
sidetone
"
, cli::ArgRequirement::Optional, [&opts](std::optional<std::string_view> arg) -> std::optional<cli::ParseError> {
if
(!arg || arg->
empty
()) {
opts.
sidetone_level
.
reset
();
opts.
request_sidetone
=
true
;
return
std::
nullopt
;
}
uint8_t
level {};
if
(
auto
error =
cli::parseInteger
(*arg, level,
uint8_t
(
0
),
uint8_t
(
128
),
"
sidetone
"
)) {
return
error;
}
opts.
sidetone_level
= level;
opts.
request_sidetone
=
false
;
return
std::
nullopt
; },
"
Get current sidetone level, or set it to LEVEL
"
,
"
LEVEL
"
)
.
flag
(
'
b
'
,
"
battery
"
, opts.
request_battery
,
"
Check battery level
"
)
.
toggle
(
'
l
'
,
"
light
"
, opts.
lights_enabled
,
"
Turn lights off (0) or on (1)
"
)
.
toggle
(
'
v
'
,
"
voice-prompt
"
, opts.
voice_prompts_enabled
,
"
Turn voice prompts off (0) or on (1)
"
)
.
value
(
'
i
'
,
"
inactive-time
"
, opts.
inactive_time
,
uint8_t
(
0
),
uint8_t
(
90
),
"
Set inactive time in minutes
"
,
"
MINUTES
"
)
.
flag
(
'
m
'
,
"
chatmix
"
, opts.
request_chatmix
,
"
Get chat-mix level
"
)
.
value
(
'
n
'
,
"
notificate
"
, opts.
notification_sound
,
uint8_t
(
0
),
uint8_t
(
255
),
"
Play notification sound
"
,
"
SOUNDID
"
)
.
toggle
(
'
r
'
,
"
rotate-to-mute
"
, opts.
rotate_to_mute_enabled
,
"
Toggle rotate to mute
"
)
.
value
(
'
p
'
,
"
equalizer-preset
"
, opts.
equalizer_preset
,
uint8_t
(
0
),
uint8_t
(
255
),
"
Set equalizer preset
"
,
"
PRESET
"
)
.
long_value
(
"
noise-filter
"
, opts.
noise_filter
,
uint8_t
(
0
),
uint8_t
(
2
),
"
Set microphone noise filter level
"
,
"
LEVEL
"
)
//
=== Equalizer (custom parsing) ===
.
custom
(
'
e
'
,
"
equalizer
"
, cli::ArgRequirement::Required, [&opts](std::optional<std::string_view> arg) -> std::optional<cli::ParseError> {
if
(!arg)
return
cli::ParseError {
"
requires equalizer values
"
,
"
equalizer
"
};
auto
values =
headsetcontrol::parse_float_data
(*arg);
if
(values.
empty
()) {
return
cli::ParseError {
"
no band values specified
"
,
"
equalizer
"
};
}
opts.
equalizer
=
EqualizerSettings
(
std::move
(values));
return
std::
nullopt
; },
"
Set equalizer curve
"
,
"
VALUES
"
)
//
=== Parametric Equalizer ===
.
long_custom
(
"
parametric-equalizer
"
, cli::ArgRequirement::Required, [&opts](std::optional<std::string_view> arg) -> std::optional<cli::ParseError> {
if
(!arg)
return
cli::ParseError {
"
requires band settings
"
,
"
parametric-equalizer
"
};
auto
peq =
headsetcontrol::parse_parametric_equalizer_settings
(*arg);
//
Note: if any band failed to parse, it won't be in the list
//
This allows partial success - valid bands are kept
opts.
parametric_equalizer
=
std::move
(peq);
return
std::
nullopt
; },
"
Set parametric EQ bands
"
,
"
BANDS
"
)
//
=== Microphone ===
.
long_value
(
"
microphone-mute-led-brightness
"
, opts.
mic_mute_led_brightness
,
uint8_t
(
0
),
uint8_t
(
3
),
"
Set mic mute LED brightness
"
,
"
LEVEL
"
)
.
long_value
(
"
microphone-volume
"
, opts.
mic_volume
,
uint8_t
(
0
),
uint8_t
(
128
),
"
Set microphone volume
"
,
"
VOLUME
"
)
//
=== Volume ===
.
long_toggle
(
"
volume-limiter
"
, opts.
volume_limiter_enabled
,
"
Toggle volume limiter
"
)
//
=== Bluetooth ===
.
long_toggle
(
"
bt-when-powered-on
"
, opts.
bt_when_powered_on
,
"
Bluetooth on at power-on
"
)
.
long_value
(
"
bt-call-volume
"
, opts.
bt_call_volume
,
uint8_t
(
0
),
uint8_t
(
255
),
"
Set bluetooth call volume
"
,
"
VOLUME
"
)
//
=== Output Format ===
.
choice
(
'
o
'
,
"
output
"
, opts.
output_format
, output_formats,
"
Output format
"
)
.
custom
(
'
c
'
,
"
short-output
"
, cli::ArgRequirement::None, [&opts](
auto
) -> std::optional<cli::ParseError> {
opts.
output_format
=
OUTPUT_SHORT
;
return
std::
nullopt
; },
"
Short output format
"
)
//
=== Follow Mode ===
.
optional_value
(
'
f
'
,
"
follow
"
, opts.
follow_mode
, opts.
follow_seconds
,
2u
,
1u
,
3600u
,
"
Re-run commands periodically
"
,
"
SECS
"
)
//
=== Advanced ===
.
flag
(
'
u
'
,
"
udev
"
, opts.
print_udev_rules
,
"
Output udev rules
"
)
.
long_flag
(
"
capabilities
"
, opts.
print_capabilities
,
"
List device capabilities
"
)
.
long_flag
(
"
caps
"
, opts.
print_capabilities
,
"
"
)
.
long_flag
(
"
connected
"
, opts.
request_connected
,
"
Check if device connected
"
)
.
long_flag
(
"
dev
"
, opts.
dev_mode
,
"
Development mode
"
)
//
=== Test Device ===
.
long_custom
(
"
test-device
"
, cli::ArgRequirement::Optional, [&opts](std::optional<std::string_view> arg) -> std::optional<cli::ParseError> {
opts.
test_device
=
true
;
if
(arg && !arg->
empty
()) {
long
val =
0
;
auto
[ptr, ec] =
std::from_chars
(arg->
data
(), arg->
data
() + arg->
size
(), val);
if
(ec == std::errc {} && ptr == arg->
data
() + arg->
size
() && val >=
0
&& val <=
255
) {
headsetcontrol::setTestProfile
(
static_cast
<
int
>(val));
}
}
return
std::
nullopt
; },
"
Use test device
"
,
"
PROFILE
"
)
//
=== Timeout ===
.
long_custom
(
"
timeout
"
, cli::ArgRequirement::Required, [](std::optional<std::string_view> arg) -> std::optional<cli::ParseError> {
if
(!arg)
return
cli::ParseError {
"
requires timeout value
"
,
"
timeout
"
};
long
val =
0
;
auto
[ptr, ec] =
std::from_chars
(arg->
data
(), arg->
data
() + arg->
size
(), val);
if
(ec != std::errc {} || ptr != arg->
data
() + arg->
size
() || val <
0
|| val >
100000
) {
return
cli::ParseError {
"
invalid timeout (0-100000)
"
,
"
timeout
"
};
}
headsetcontrol::setDeviceTimeout
(
static_cast
<
int
>(val));
return
std::
nullopt
; },
"
Set timeout in ms
"
,
"
MS
"
)
//
=== Readme Helper (exits immediately) ===
.
long_custom
(
"
readme-helper
"
, cli::ArgRequirement::None, [](
auto
) -> std::optional<cli::ParseError> {
init_cpp_devices
();
//
Print table (inline for simplicity)
std::cout <<
"
| Device | Platform |
"
;
for
(
int
j =
0
; j <
NUM_CAPABILITIES
; j++) {
std::cout <<
"
"
<<
capability_to_string
(
static_cast
<capabilities>(j)) <<
"
|
"
;
}
std::cout <<
"
\n
| --- | --- |
"
;
for
(
int
j =
0
; j <
NUM_CAPABILITIES
; j++) {
std::cout <<
"
--- |
"
;
}
std::cout <<
'
\n
'
;
for
(
const
auto
& device_ptr :
DeviceRegistry::instance
().
getAllDevices
()) {
auto
* device = device_ptr.
get
();
std::cout <<
"
|
"
<< device->
getDeviceName
() <<
"
|
"
;
uint8_t
platforms = device->
getSupportedPlatforms
();
std::cout <<
platformsToTableString
(platforms) <<
"
|
"
;
//
getCapabilities() may depend on the matched product ID, so ask
//
each variant: capabilities all of them report get an "x", ones
//
only some report get an "x*" (explained by a footnote below the
//
table in the README).
int
caps_any =
0
;
int
caps_all =
0
;
bool
first =
true
;
for
(
uint16_t
pid : device->
getProductIds
()) {
device->
setMatchedProductId
(pid);
const
int
caps = device->
getCapabilities
();
caps_any |= caps;
caps_all = first ? caps : (caps_all & caps);
first =
false
;
}
device->
setMatchedProductId
(
0
);
if
(first) {
//
device without product IDs
caps_any = caps_all = device->
getCapabilities
();
}
for
(
int
j =
0
; j <
NUM_CAPABILITIES
; j++) {
if
(caps_all &
B
(j)) {
std::cout <<
"
x |
"
;
}
else
if
(caps_any &
B
(j)) {
std::cout <<
"
x* |
"
;
}
else
{
std::cout <<
"
|
"
;
}
}
std::cout <<
'
\n
'
;
}
std::exit
(
0
); },
"
Output README table
"
);
return
std::
nullopt
;
}
// ============================================================================
//
RAII wrapper for HID connection
// ============================================================================
class
HIDConnection
{
public:
HIDConnection
() =
default
;
~HIDConnection
() {
close
(); }
HIDConnection
(
const
HIDConnection&) =
delete
;
HIDConnection&
operator
=(
const
HIDConnection&) =
delete
;
HIDConnection
(HIDConnection&& other)
noexcept
: handle_(other.handle_)
, path_(std::move(other.path_))
{
other.
handle_
=
nullptr
;
}
HIDConnection&
operator
=(HIDConnection&& other)
noexcept
{
if
(
this
!= &other) {
close
();
handle_ = other.
handle_
;
path_ =
std::move
(other.
path_
);
other.
handle_
=
nullptr
;
}
return
*
this
;
}
[[nodiscard]]
bool
isOpen
()
const
{
return
handle_ !=
nullptr
; }
[[nodiscard]]
hid_device*
get
()
const
{
return
handle_; }
bool
open
(
const
std::string& new_path)
{
if
(path_ == new_path && handle_)
return
true
;
close
();
handle_ =
hid_open_path
(new_path.
c_str
());
if
(handle_) {
path_ = new_path;
return
true
;
}
return
false
;
}
void
close
()
{
if
(handle_) {
hid_close
(handle_);
handle_ =
nullptr
;
}
path_.
clear
();
}
private:
hid_device* handle_ =
nullptr
;
std::string path_;
};
// ============================================================================
//
Device discovery
// ============================================================================
struct
DiscoveredDevice
{
HIDDevice* device =
nullptr
;
uint16_t
product_id =
0
;
HIDConnection connection;
std::vector<FeatureRequest> feature_requests;
std::wstring vendor_name;
std::wstring product_name;
[[nodiscard]]
uint16_t
vendorId
()
const
{
return
device ? device->
getVendorId
() :
0
;
}
[[nodiscard]]
bool
matchesFilter
(
const
Options& opts)
const
{
return
device && opts.
matchesDevice
(device->
getVendorId
(), product_id);
}
[[nodiscard]]
bool
hasCapability
(capabilities cap)
const
{
return
device && (device->
getCapabilities
() &
B
(cap)) !=
0
;
}
};
//
RAII wrapper for hid_enumerate result
class
HIDEnumeration
{
public:
explicit
HIDEnumeration
(
uint16_t
vid =
0
,
uint16_t
pid =
0
)
: devices_(hid_enumerate(vid, pid))
{
}
~HIDEnumeration
()
{
if
(devices_)
hid_free_enumeration
(devices_);
}
HIDEnumeration
(
const
HIDEnumeration&) =
delete
;
HIDEnumeration&
operator
=(
const
HIDEnumeration&) =
delete
;
hid_device_info*
get
()
const
{
return
devices_; }
private:
hid_device_info* devices_;
};
std::vector<DiscoveredDevice>
discoverDevices
(
const
Options& opts)
{
std::vector<DiscoveredDevice> devices;
auto
& registry =
DeviceRegistry::instance
();
if
(opts.
test_device
) {
if
(
auto
* test_dev = registry.
getDevice
(
VENDOR_TESTDEVICE
,
PRODUCT_TESTDEVICE
)) {
DiscoveredDevice dev;
dev.
device
= test_dev;
dev.
product_id
=
PRODUCT_TESTDEVICE
;
dev.
vendor_name
=
L"
HeadsetControl
"
;
dev.
product_name
=
L"
Test Device
"
;
devices.
push_back
(
std::move
(dev));
}
}
HIDEnumeration
enumeration
(opts.
vendor_id
, opts.
product_id
);
for
(
auto
* cur = enumeration.
get
(); cur; cur = cur->
next
) {
bool
duplicate =
std::any_of
(devices.
begin
(), devices.
end
(), [&](
const
DiscoveredDevice& d) {
return
d.
vendorId
() == cur->
vendor_id
&& d.
product_id
== cur->
product_id
;
});
if
(duplicate)
continue
;
auto
* device = registry.
getDevice
(cur->
vendor_id
, cur->
product_id
);
if
(!device)
continue
;
DiscoveredDevice dev;
dev.
device
= device;
dev.
product_id
= cur->
product_id
;
if
(cur->
manufacturer_string
)
dev.
vendor_name
= cur->
manufacturer_string
;
if
(cur->
product_string
)
dev.
product_name
= cur->
product_string
;
devices.
push_back
(
std::move
(dev));
}
return
devices;
}
// ============================================================================
//
Feature handling
// ============================================================================
hid_device*
connectForCapability
(HIDConnection& conn,
const
HIDDevice* device,
uint16_t
product_id, capabilities cap)
{
auto
detail = device->
getCapabilityDetail
(cap);
auto
hid_path =
headsetcontrol::get_hid_path
(device->
getVendorId
(), product_id, detail.
interface_id
, detail.
usagepage
, detail.
usageid
);
if
(!hid_path)
return
nullptr
;
return
conn.
open
(*hid_path) ? conn.
get
() :
nullptr
;
}
//
Convert FeatureOutput to FeatureResult for output formatting
FeatureResult
convertToFeatureResult
(
const
headsetcontrol::FeatureOutput& output)
{
FeatureResult result;
result.
status
=
FEATURE_SUCCESS
;
result.
value
= output.
value
;
result.
message
= output.
message
;
//
Handle battery special case with extended info
if
(output.
battery
) {
const
auto
& b = *output.
battery
;
result.
value
= b.
level_percent
;
result.
status2
=
static_cast
<
int
>(b.
status
);
//
Copy extended battery info
if
(b.
voltage_mv
.
has_value
())
result.
battery_voltage_mv
= b.
voltage_mv
;
if
(b.
time_to_full_min
.
has_value
())
result.
battery_time_to_full_min
= b.
time_to_full_min
;
if
(b.
time_to_empty_min
.
has_value
())
result.
battery_time_to_empty_min
= b.
time_to_empty_min
;
}
//
Handle chatmix special case
if
(output.
chatmix
.
has_value
()) {
result.
value
= output.
chatmix
->
level
;
}
//
Handle sidetone special case
if
(output.
sidetone
) {
result.
value
= output.
sidetone
->
current_level
;
result.
sidetone_device_level
= output.
sidetone
->
device_level
;
result.
sidetone_level_name
= output.
sidetone
->
level_name
;
}
return
result;
}
//
Handle a feature request via the handler registry
FeatureResult
handleFeature
(DiscoveredDevice& dev, capabilities cap,
const
FeatureParam& param)
{
//
Validate parameter
if
(
auto
error =
headsetcontrol::validateFeatureParam
(cap, param)) {
return
make_error
(-
1
, *error);
}
//
Check device support
if
(!dev.
hasCapability
(cap)) {
const
auto
& desc =
headsetcontrol::getCapabilityDescriptor
(cap);
return
make_error
(-
1
,
std::format
(
"
This headset doesn't support {}
"
, desc.
name
));
}
bool
is_test = (dev.
product_id
==
PRODUCT_TESTDEVICE
);
hid_device* handle =
nullptr
;
//
Connect to device (unless test device)
if
(!is_test) {
handle =
connectForCapability
(dev.
connection
, dev.
device
, dev.
product_id
, cap);
if
(!handle) {
return
make_error
(-
1
,
"
Could not open device
"
);
}
}
//
Execute via handler registry (no more giant switch!)
auto
result =
headsetcontrol::FeatureHandlerRegistry::instance
().
execute
(
cap, dev.
device
, handle, param);
if
(result.
hasError
()) {
return
make_error
(-
1
, result.
error
().
message
);
}
return
convertToFeatureResult
(result.
value
());
}
// ============================================================================
//
Help output
// ============================================================================
namespace
help
{
//
ANSI terminal formatting
namespace
ansi
{
constexpr
std::string_view bold =
"
\033
[1m
"
;
constexpr
std::string_view dim =
"
\033
[2m
"
;
constexpr
std::string_view green =
"
\033
[32m
"
;
constexpr
std::string_view reset =
"
\033
[0m
"
;
}
//
namespace ansi
//
Get value hint from capability descriptor (single source of truth)
[[nodiscard]]
inline
std::string
getValueHint
(capabilities cap)
{
const
auto
& desc =
headsetcontrol::getCapabilityDescriptor
(cap);
return
std::string
(desc.
value_hint
);
}
//
Option definition for help display
struct
Option
{
char
short_opt =
'
\0
'
;
std::string_view long_opt;
std::string arg;
//
Owns string data (for dynamic value hints from descriptors)
std::string_view description;
std::optional<capabilities> required_cap = std::
nullopt
;
//
Show only if device has this
bool
advanced_only =
false
;
//
Show only in --help-all
};
//
Section with its options
struct
Section
{
std::string_view title;
std::vector<Option> options;
//
Fluent builder for adding options
template
<
typename
ArgT>
Section&
add
(
char
short_opt, std::string_view long_opt, ArgT&& arg,
std::string_view desc, std::optional<capabilities> cap = std::
nullopt
,
bool
advanced =
false
)
{
options.
emplace_back
(short_opt, long_opt,
std::string
(std::forward<ArgT>(arg)), desc, cap, advanced);
return
*
this
;
}
template
<
typename
ArgT>
Section&
add
(std::string_view long_opt, ArgT&& arg, std::string_view desc,
std::optional<capabilities> cap = std::
nullopt
,
bool
advanced =
false
)
{
return
add
(
'
\0
'
, long_opt, std::forward<ArgT>(arg), desc, cap, advanced);
}
};
//
Help generator class
class
HelpGenerator
{
public:
HelpGenerator
(std::string_view program, HIDDevice* dev,
bool
all)
: program_name_(program)
, device_(dev)
, show_all_(all)
, caps_(dev ? dev->
getCapabilities
() : 0)
{
}
void
generate
()
{
printHeader
();
printUsage
();
for
(
const
auto
& section :
buildSections
()) {
printSection
(section);
}
printExamples
();
printFooter
();
}
private:
std::string_view program_name_;
HIDDevice* device_;
bool
show_all_;
int
caps_;
static
constexpr
int
kColumnWidth
=
36
;
[[nodiscard]]
bool
hasCapability
(capabilities cap)
const
{
return
(caps_ &
B
(cap)) !=
0
;
}
[[nodiscard]]
bool
shouldShow
(
const
Option& opt)
const
{
if
(opt.
advanced_only
&& !show_all_)
return
false
;
if
(opt.
required_cap
&& !show_all_ && !
hasCapability
(*opt.
required_cap
))
return
false
;
return
true
;
}
[[nodiscard]]
bool
sectionHasVisibleOptions
(
const
Section& section)
const
{
return
std::ranges::any_of
(section.
options
, [
this
](
const
Option& opt) {
return
shouldShow
(opt);
});
}
void
printHeader
()
const
{
println
(
"
{}HeadsetControl{} - Control USB gaming headsets on Linux/macOS/Windows
"
,
ansi::bold, ansi::reset);
println
(
"
Version {} | https://github.com/Sapd/HeadsetControl
"
,
VERSION
);
if
(device_) {
println
(
"
\n
Detected: {}{}{}
"
, ansi::green, device_->
getDeviceName
(), ansi::reset);
}
}
void
printUsage
()
const
{
println
(
"
\n
{}USAGE{}
"
, ansi::bold, ansi::reset);
println
(
"
{} [OPTIONS]
"
, program_name_);
println
(
"
{} -b # Check battery
"
, program_name_);
println
(
"
{} -s 64 -l 1 # Set sidetone + lights on
"
, program_name_);
}
void
printOption
(
const
Option& opt)
const
{
std::string left;
if
(opt.
short_opt
!=
'
\0
'
) {
left =
std::format
(
"
-{}
"
, opt.
short_opt
);
if
(!opt.
long_opt
.
empty
()) {
left +=
std::format
(
"
, --{}
"
, opt.
long_opt
);
}
}
else
if
(!opt.
long_opt
.
empty
()) {
left =
std::format
(
"
--{}
"
, opt.
long_opt
);
}
else
{
return
;
//
No option name
}
if
(!opt.
arg
.
empty
()) {
left +=
std::format
(
"
{}
"
, opt.
arg
);
}
//
Pad or add spacing
int
padding =
kColumnWidth
-
static_cast
<
int
>(left.
size
());
if
(padding >
0
) {
left.
append
(padding,
'
'
);
}
else
{
left +=
"
"
;
}
println
(
"
{}{}
"
, left, opt.
description
);
}
void
printSection
(
const
Section& section)
const
{
if
(!
sectionHasVisibleOptions
(section))
return
;
println
(
"
\n
{}{}{}
"
, ansi::bold, section.
title
, ansi::reset);
for
(
const
auto
& opt : section.
options
) {
if
(
shouldShow
(opt)) {
printOption
(opt);
}
}
//
Special handling for parametric EQ types
if
(section.
title
==
"
EQUALIZER
"
&& (show_all_ ||
hasCapability
(
CAP_PARAMETRIC_EQUALIZER
))) {
printParametricEqTypes
();
}
}
void
printParametricEqTypes
()
const
{
if
(!show_all_ && !
hasCapability
(
CAP_PARAMETRIC_EQUALIZER
))
return
;
println
(
"
Format: FREQ,GAIN,Q,TYPE;...
"
);
auto
peq_info = device_ ? device_->
getParametricEqualizerInfo
() : std::
nullopt
;
std::string types;
for
(
int
i =
0
; i <
NUM_EQ_FILTER_TYPES
; i++) {
bool
include = show_all_ || (peq_info &&
has_capability
(peq_info->
filter_types
,
static_cast
<capabilities>(i)));
if
(include) {
if
(!types.
empty
())
types +=
"
,
"
;
types +=
equalizer_filter_type_to_string
(
static_cast
<EqualizerFilterType>(i));
}
}
if
(!types.
empty
()) {
println
(
"
Types: {}
"
, types);
}
}
void
printExamples
()
const
{
println
(
"
\n
{}EXAMPLES{}
"
, ansi::bold, ansi::reset);
println
(
"
{} -b -o json # Battery status as JSON
"
, program_name_);
println
(
"
{} -s 0 -l 0 # Disable sidetone and lights
"
, program_name_);
println
(
"
{} -e 0,2,4,2,0,-2 # Custom 6-band EQ curve
"
, program_name_);
println
(
"
{} -f 5 -b # Poll battery every 5 seconds
"
, program_name_);
if
(show_all_) {
println
(
"
{} -d 1038:12ad -s 50 # Target specific device
"
, program_name_);
}
}
void
printFooter
()
const
{
if
(!show_all_) {
println
(
"
\n
{}Use --help-all to see all available options{}
"
, ansi::dim, ansi::reset);
}
}
[[nodiscard]]
std::vector<Section>
buildSections
()
const
{
std::vector<Section> sections;
//
Device selection - always shown
sections.
push_back
({
"
DEVICE SELECTION
"
, {} });
sections.
back
().
add
(
'
d
'
,
"
device
"
,
"
VID:PID
"
,
"
Select device (e.g., 1038:12ad)
"
);
//
Status
sections.
push_back
({
"
STATUS
"
, {} });
sections.
back
()
.
add
(
'
b
'
,
"
battery
"
,
"
"
,
"
Show battery level and status
"
,
CAP_BATTERY_STATUS
)
.
add
(
'
m
'
,
"
chatmix
"
,
"
"
,
"
Show current chat-mix balance
"
,
CAP_CHATMIX_STATUS
)
.
add
(
"
connected
"
,
"
"
,
"
Check if headset is connected
"
, std::
nullopt
,
true
);
//
Audio - value hints from capability descriptors
sections.
push_back
({
"
AUDIO
"
, {} });
sections.
back
()
.
add
(
'
s
'
,
"
sidetone
"
,
getValueHint
(
CAP_SIDETONE
),
"
Get current level or set mic feedback (0-128)
"
,
CAP_SIDETONE
)
.
add
(
"
volume-limiter
"
,
getValueHint
(
CAP_VOLUME_LIMITER
),
"
Enable/disable volume limiter
"
,
CAP_VOLUME_LIMITER
);
//
Equalizer
sections.
push_back
({
"
EQUALIZER
"
, {} });
sections.
back
()
.
add
(
'
e
'
,
"
equalizer
"
,
"
V1,V2,...
"
,
"
Set EQ curve (comma-separated dB values)
"
,
CAP_EQUALIZER
);
//
Dynamic preset range based on device
if
(device_ && device_->
getEqualizerPresetsCount
() >
0
) {
sections.
back
().
add
(
'
p
'
,
"
equalizer-preset
"
,
std::format
(
"
0-{}
"
, device_->
getEqualizerPresetsCount
() -
1
),
"
Select built-in EQ preset
"
,
CAP_EQUALIZER_PRESET
);
}
else
{
sections.
back
().
add
(
'
p
'
,
"
equalizer-preset
"
,
"
N
"
,
"
Select built-in EQ preset
"
,
CAP_EQUALIZER_PRESET
);
}
sections.
back
().
add
(
"
parametric-equalizer
"
,
"
BANDS
"
,
"
Set parametric EQ bands
"
,
CAP_PARAMETRIC_EQUALIZER
);
//
Microphone - value hints from capability descriptors
sections.
push_back
({
"
MICROPHONE
"
, {} });
sections.
back
()
.
add
(
'
r
'
,
"
rotate-to-mute
"
,
getValueHint
(
CAP_ROTATE_TO_MUTE
),
"
Mute when boom arm raised
"
,
CAP_ROTATE_TO_MUTE
)
.
add
(
"
microphone-mute-led-brightness
"
,
getValueHint
(
CAP_MICROPHONE_MUTE_LED_BRIGHTNESS
),
"
Mute LED brightness
"
,
CAP_MICROPHONE_MUTE_LED_BRIGHTNESS
)
.
add
(
"
microphone-volume
"
,
getValueHint
(
CAP_MICROPHONE_VOLUME
),
"
Microphone gain level
"
,
CAP_MICROPHONE_VOLUME
)
.
add
(
"
noise-filter
"
,
getValueHint
(
CAP_NOISE_FILTER
),
"
Microphone noise filter level (0=off, 1=low, 2=high)
"
,
CAP_NOISE_FILTER
);
//
Lights & Audio Cues - value hints from capability descriptors
sections.
push_back
({
"
LIGHTS & AUDIO CUES
"
, {} });
sections.
back
()
.
add
(
'
l
'
,
"
light
"
,
getValueHint
(
CAP_LIGHTS
),
"
RGB/LED lights off/on
"
,
CAP_LIGHTS
)
.
add
(
'
v
'
,
"
voice-prompt
"
,
getValueHint
(
CAP_VOICE_PROMPTS
),
"
Voice prompts off/on
"
,
CAP_VOICE_PROMPTS
)
.
add
(
'
n
'
,
"
notificate
"
,
getValueHint
(
CAP_NOTIFICATION_SOUND
),
"
Play notification sound
"
,
CAP_NOTIFICATION_SOUND
);
//
Power & Bluetooth - value hints from capability descriptors
sections.
push_back
({
"
POWER & BLUETOOTH
"
, {} });
sections.
back
()
.
add
(
'
i
'
,
"
inactive-time
"
,
getValueHint
(
CAP_INACTIVE_TIME
),
"
Auto-off after N minutes (0=never)
"
,
CAP_INACTIVE_TIME
)
.
add
(
"
bt-when-powered-on
"
,
getValueHint
(
CAP_BT_WHEN_POWERED_ON
),
"
Enable Bluetooth at power-on
"
,
CAP_BT_WHEN_POWERED_ON
)
.
add
(
"
bt-call-volume
"
,
getValueHint
(
CAP_BT_CALL_VOLUME
),
"
Bluetooth call volume
"
,
CAP_BT_CALL_VOLUME
);
//
Output - always shown
sections.
push_back
({
"
OUTPUT
"
, {} });
sections.
back
()
.
add
(
'
o
'
,
"
output
"
,
"
FORMAT
"
,
"
json, yaml, env, standard
"
)
.
add
(
"
capabilities, --caps
"
,
"
"
,
"
List device capabilities
"
);
//
Advanced - only in --help-all
sections.
push_back
({
"
ADVANCED
"
, {} });
sections.
back
()
.
add
(
'
f
'
,
"
follow
"
,
"
[SECS]
"
,
"
Repeat every N seconds (default: 2)
"
, std::
nullopt
,
true
)
.
add
(
"
timeout
"
,
"
MS
"
,
"
HID read timeout (default: 5000)
"
, std::
nullopt
,
true
)
.
add
(
'
u
'
,
"
"
,
"
"
,
"
Generate udev rules for Linux
"
, std::
nullopt
,
true
)
.
add
(
"
test-device
"
,
"
[N]
"
,
"
Use mock device (for testing)
"
, std::
nullopt
,
true
);
//
Help - always shown
sections.
push_back
({
"
HELP
"
, {} });
sections.
back
()
.
add
(
'
h
'
,
"
help
"
,
"
"
,
"
Show help for detected device
"
)
.
add
(
"
help-all
"
,
"
"
,
"
Show all options
"
);
return
sections;
}
};
}
//
namespace help
void
printHelp
(std::string_view program_name, HIDDevice* device,
bool
show_all)
{
help::HelpGenerator
(program_name, device, show_all).
generate
();
}
// ============================================================================
//
Udev rules output
// ============================================================================
void
printUdevRules
()
{
println
(
"
ACTION!=
\"
add|change
\"
, GOTO=
\"
headset_end
\"
"
);
println
();
for
(
const
auto
& device_ptr :
DeviceRegistry::instance
().
getAllDevices
()) {
auto
* device = device_ptr.
get
();
println
(
"
# {}
"
, device->
getDeviceName
());
for
(
uint16_t
pid : device->
getProductIds
()) {
println
(
"
KERNEL==
\"
hidraw*
\"
, SUBSYSTEM==
\"
hidraw
\"
,
"
"
ATTRS{{idVendor}}==
\"
{:04x}
\"
, ATTRS{{idProduct}}==
\"
{:04x}
\"
, TAG+=
\"
uaccess
\"
"
,
device->
getVendorId
(), pid);
}
println
();
}
println
(
"
LABEL=
\"
headset_end
\"
"
);
}
// ============================================================================
//
Feature request initialization
// ============================================================================
/*
*
* @brief Storage for feature request parameters
*
* This struct holds copies of feature parameters that need to persist
* for the duration of feature request processing. Using this struct
* instead of static local variables ensures proper behavior in follow mode
* and avoids const_cast issues with optional values.
*/
struct
FeatureParamStorage
{
int
sidetone_val =
0
;
int
lights_val =
0
;
int
notification_val =
0
;
int
inactive_time_val =
0
;
int
voice_prompts_val =
0
;
int
rotate_to_mute_val =
0
;
int
equalizer_preset_val =
0
;
int
mic_led_val =
0
;
int
mic_vol_val =
0
;
int
volume_limiter_val =
0
;
int
bt_power_val =
0
;
int
bt_call_vol_val =
0
;
int
battery_req =
0
;
int
chatmix_req =
0
;
int
noise_filter_val =
0
;
//
Store copies of complex settings to avoid const_cast
EqualizerSettings equalizer_settings;
ParametricEqualizerSettings parametric_eq_settings;
void
updateFrom
(
const
Options& opts)
{
if
(opts.
sidetone_level
.
has_value
())
sidetone_val = *opts.
sidetone_level
;
if
(opts.
lights_enabled
.
has_value
())
lights_val = *opts.
lights_enabled
?
1
:
0
;
if
(opts.
notification_sound
.
has_value
())
notification_val = *opts.
notification_sound
;
if
(opts.
inactive_time
.
has_value
())
inactive_time_val = *opts.
inactive_time
;
if
(opts.
voice_prompts_enabled
.
has_value
())
voice_prompts_val = *opts.
voice_prompts_enabled
?
1
:
0
;
if
(opts.
rotate_to_mute_enabled
.
has_value
())
rotate_to_mute_val = *opts.
rotate_to_mute_enabled
?
1
:
0
;
if
(opts.
equalizer_preset
.
has_value
())
equalizer_preset_val = *opts.
equalizer_preset
;
if
(opts.
mic_mute_led_brightness
.
has_value
())
mic_led_val = *opts.
mic_mute_led_brightness
;
if
(opts.
mic_volume
.
has_value
())
mic_vol_val = *opts.
mic_volume
;
if
(opts.
volume_limiter_enabled
.
has_value
())
volume_limiter_val = *opts.
volume_limiter_enabled
?
1
:
0
;
if
(opts.
bt_when_powered_on
.
has_value
())
bt_power_val = *opts.
bt_when_powered_on
?
1
:
0
;
if
(opts.
bt_call_volume
.
has_value
())
bt_call_vol_val = *opts.
bt_call_volume
;
if
(opts.
noise_filter
.
has_value
())
noise_filter_val = *opts.
noise_filter
;
battery_req = opts.
request_battery
?
1
:
0
;
chatmix_req = opts.
request_chatmix
?
1
:
0
;
//
Copy complex settings (avoids const_cast)
if
(opts.
equalizer
.
has_value
())
equalizer_settings = *opts.
equalizer
;
if
(opts.
parametric_equalizer
.
has_value
())
parametric_eq_settings = *opts.
parametric_equalizer
;
}
};
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL