-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqmk-light.cpp
More file actions
629 lines (560 loc) · 18.9 KB
/
Copy pathqmk-light.cpp
File metadata and controls
629 lines (560 loc) · 18.9 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
// Compile with: c++ -std=c++17 -O2 waybar-via-helper.cpp -lhidapi-hidraw -o via-brightness-helper
#include <cstddef>
extern "C" {
struct hid_device_;
using hid_device = hid_device_;
struct hid_device_info {
char* path;
unsigned short vendor_id;
unsigned short product_id;
wchar_t* serial_number;
unsigned short release_number;
wchar_t* manufacturer_string;
wchar_t* product_string;
unsigned short usage_page;
unsigned short usage;
int interface_number;
struct hid_device_info* next;
};
int hid_init(void);
int hid_exit(void);
hid_device_info* hid_enumerate(unsigned short vendor_id, unsigned short product_id);
void hid_free_enumeration(hid_device_info* devs);
hid_device* hid_open_path(const char* path);
int hid_write(hid_device* device, const unsigned char* data, size_t length);
int hid_read_timeout(hid_device* device, unsigned char* data, size_t length, int milliseconds);
void hid_close(hid_device* device);
}
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
namespace {
constexpr uint16_t kViaUsagePage = 0xFF60;
constexpr uint16_t kViaUsage = 0x61;
constexpr size_t kRawReportSize = 32;
constexpr uint8_t kCmdSetValue = 0x07;
constexpr uint8_t kCmdGetValue = 0x08;
constexpr uint8_t kCmdUnhandled = 0xFF;
constexpr uint8_t kBrightnessId = 0x01;
constexpr uint8_t kEffectId = 0x02;
constexpr uint8_t kEffectSpeedId = 0x03;
constexpr uint8_t kColorId = 0x04;
constexpr int kReadTimeoutMs = 500;
const std::vector<uint8_t> kChannelsByPriority = {3, 2, 1, 5};
struct DeviceInfo {
std::string path;
uint16_t vendor_id;
uint16_t product_id;
std::string serial;
std::string manufacturer;
std::string product;
};
struct Options {
bool list_devices = false;
bool first_device = false;
bool quiet = false;
std::optional<std::string> device_selector;
bool get_brightness = false;
std::optional<std::string> set_brightness;
bool list_effects = false;
bool get_effect = false;
std::optional<int> set_effect;
bool get_effect_speed = false;
std::optional<int> set_effect_speed;
bool get_color = false;
std::optional<std::pair<int, int>> set_color;
};
std::string ToNarrow(const wchar_t* wstr) {
if (wstr == nullptr) {
return "";
}
std::wstring ws(wstr);
return std::string(ws.begin(), ws.end());
}
std::string ToHex4(uint16_t value) {
std::ostringstream oss;
oss << std::hex;
oss.width(4);
oss.fill('0');
oss << static_cast<unsigned int>(value);
return oss.str();
}
void PrintUsage(const char* argv0) {
std::cerr
<< "Usage:\n"
<< " " << argv0 << " --list\n"
<< " " << argv0 << " [--first-device | --device <index|path>] "
<< "[--get-brightness | --set-brightness <num|+num|-num> | "
<< "--list-effects | --get-effect | --set-effect <num> | "
<< "--get-effect-speed | --set-effect-speed <num> | "
<< "--get-color | --set-color <hue,sat>]\n\n"
<< "Options:\n"
<< " --first-device Use first compatible device\n"
<< " --list List compatible devices\n"
<< " -q, --quiet Suppress error messages\n"
<< " --device <index|path> Target a specific device\n"
<< " --get-brightness Print brightness in percent\n"
<< " --set-brightness <num|+num|-num> Set absolute or relative brightness\n"
<< " --list-effects List standard RGB effect modes\n"
<< " --get-effect Print current effect ID\n"
<< " --set-effect <num> Set effect by ID\n"
<< " --get-effect-speed Print current effect speed\n"
<< " --set-effect-speed <num> Set effect speed (0-255)\n"
<< " --get-color Print current color (hue, saturation)\n"
<< " --set-color <hue,sat> Set color (hue 0-255, saturation 0-255)\n";
}
std::optional<int> ParseInt(const std::string& value) {
if (value.empty()) {
return std::nullopt;
}
char* end = nullptr;
long parsed = std::strtol(value.c_str(), &end, 10);
if (end == nullptr || *end != '\0') {
return std::nullopt;
}
if (parsed < std::numeric_limits<int>::min() || parsed > std::numeric_limits<int>::max()) {
return std::nullopt;
}
return static_cast<int>(parsed);
}
bool ParseArgs(int argc, char** argv, Options* options) {
for (int i = 1; i < argc; ++i) {
std::string arg(argv[i]);
if (arg == "--list") {
options->list_devices = true;
} else if (arg == "--first-device") {
options->first_device = true;
} else if (arg == "-q" || arg == "--quiet") {
options->quiet = true;
} else if (arg == "--device") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --device\n";
return false;
}
options->device_selector = argv[++i];
} else if (arg == "--get-brightness") {
options->get_brightness = true;
} else if (arg == "--set-brightness") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --set-brightness\n";
return false;
}
options->set_brightness = argv[++i];
} else if (arg == "--list-effects") {
options->list_effects = true;
} else if (arg == "--get-effect") {
options->get_effect = true;
} else if (arg == "--set-effect") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --set-effect\n";
return false;
}
auto val = ParseInt(argv[++i]);
if (!val.has_value()) {
std::cerr << "Invalid value for --set-effect\n";
return false;
}
options->set_effect = val;
} else if (arg == "--get-effect-speed") {
options->get_effect_speed = true;
} else if (arg == "--set-effect-speed") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --set-effect-speed\n";
return false;
}
auto val = ParseInt(argv[++i]);
if (!val.has_value()) {
std::cerr << "Invalid value for --set-effect-speed\n";
return false;
}
options->set_effect_speed = val;
} else if (arg == "--get-color") {
options->get_color = true;
} else if (arg == "--set-color") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --set-color\n";
return false;
}
std::string val = argv[++i];
size_t pos = val.find(',');
if (pos == std::string::npos) {
std::cerr << "Invalid format for --set-color, expected hue,sat (e.g. 128,255)\n";
return false;
}
auto h = ParseInt(val.substr(0, pos));
auto s = ParseInt(val.substr(pos + 1));
if (!h.has_value() || !s.has_value()) {
std::cerr << "Invalid values for --set-color\n";
return false;
}
options->set_color = {*h, *s};
} else if (arg == "-h" || arg == "--help") {
PrintUsage(argv[0]);
std::exit(0);
} else {
std::cerr << "Unknown argument: " << arg << "\n";
return false;
}
}
if (options->first_device && options->device_selector.has_value()) {
std::cerr << "Use either --first-device or --device, not both\n";
return false;
}
int ops = 0;
if (options->list_devices) ops++;
if (options->get_brightness) ops++;
if (options->set_brightness.has_value()) ops++;
if (options->list_effects) ops++;
if (options->get_effect) ops++;
if (options->set_effect.has_value()) ops++;
if (options->get_effect_speed) ops++;
if (options->set_effect_speed.has_value()) ops++;
if (options->get_color) ops++;
if (options->set_color.has_value()) ops++;
if (ops > 1) {
std::cerr << "Please specify only one operation at a time\n";
return false;
}
return true;
}
std::vector<DeviceInfo> EnumerateCompatibleDevices() {
std::vector<DeviceInfo> devices;
hid_device_info* head = hid_enumerate(0x0, 0x0);
for (hid_device_info* cur = head; cur != nullptr; cur = cur->next) {
if (cur->usage_page != kViaUsagePage || cur->usage != kViaUsage) {
continue;
}
DeviceInfo info;
info.path = cur->path == nullptr ? "" : cur->path;
info.vendor_id = cur->vendor_id;
info.product_id = cur->product_id;
info.serial = ToNarrow(cur->serial_number);
info.manufacturer = ToNarrow(cur->manufacturer_string);
info.product = ToNarrow(cur->product_string);
devices.push_back(std::move(info));
}
hid_free_enumeration(head);
return devices;
}
void ListDevices(const std::vector<DeviceInfo>& devices) {
for (size_t i = 0; i < devices.size(); ++i) {
const auto& d = devices[i];
std::cout << i << "\t"
<< "vid:pid=" << ToHex4(d.vendor_id) << ":" << ToHex4(d.product_id) << "\t"
<< "manufacturer=\"" << d.manufacturer << "\"\t"
<< "product=\"" << d.product << "\"\t"
<< "serial=\"" << d.serial << "\"\t"
<< "path=\"" << d.path << "\"\n";
}
}
std::optional<DeviceInfo> SelectDevice(const std::vector<DeviceInfo>& devices, const Options& opts) {
if (devices.empty()) {
return std::nullopt;
}
if (opts.first_device || !opts.device_selector.has_value()) {
return devices.front();
}
const std::string selector = *opts.device_selector;
if (auto maybe_index = ParseInt(selector); maybe_index.has_value()) {
const int index = *maybe_index;
if (index >= 0 && static_cast<size_t>(index) < devices.size()) {
return devices[static_cast<size_t>(index)];
}
}
for (const auto& dev : devices) {
if (dev.path == selector) {
return dev;
}
}
return std::nullopt;
}
std::optional<std::vector<uint8_t>> SendViaCommand(const DeviceInfo& device, const std::vector<uint8_t>& command) {
hid_device* handle = hid_open_path(device.path.c_str());
if (handle == nullptr) {
return std::nullopt;
}
std::vector<uint8_t> request(1 + kRawReportSize, 0);
const size_t copy_size = std::min(command.size(), kRawReportSize);
std::copy(command.begin(), command.begin() + static_cast<std::ptrdiff_t>(copy_size), request.begin() + 1);
if (hid_write(handle, request.data(), request.size()) < 0) {
hid_close(handle);
return std::nullopt;
}
std::vector<uint8_t> response(kRawReportSize, 0);
int bytes_read = hid_read_timeout(handle, response.data(), response.size(), kReadTimeoutMs);
hid_close(handle);
if (bytes_read <= 0) {
return std::nullopt;
}
return response;
}
std::optional<uint8_t> DetectChannel(const DeviceInfo& device) {
for (uint8_t channel : kChannelsByPriority) {
auto response = SendViaCommand(device, {kCmdGetValue, channel, kBrightnessId});
if (response.has_value() && !response->empty() && (*response)[0] != kCmdUnhandled) {
return channel;
}
}
return std::nullopt;
}
std::optional<int> GetProperty(const DeviceInfo& device, uint8_t channel, uint8_t property_id) {
auto response = SendViaCommand(device, {kCmdGetValue, channel, property_id});
if (!response.has_value() || response->size() < 4 || (*response)[0] == kCmdUnhandled) {
return std::nullopt;
}
return static_cast<int>((*response)[3]);
}
bool SetProperty(const DeviceInfo& device, uint8_t channel, uint8_t property_id, int value) {
value = std::clamp(value, 0, 255);
auto response = SendViaCommand(device, {kCmdSetValue, channel, property_id, static_cast<uint8_t>(value)});
return response.has_value();
}
std::optional<int> GetBrightness(const DeviceInfo& device, uint8_t channel) {
auto raw = GetProperty(device, channel, kBrightnessId);
if (!raw.has_value()) return std::nullopt;
return static_cast<int>(std::lround(*raw * 100.0 / 255.0));
}
bool SetBrightness(const DeviceInfo& device, uint8_t channel, int percent) {
percent = std::clamp(percent, 0, 100);
const int raw = static_cast<int>(std::lround(percent * 255.0 / 100.0));
return SetProperty(device, channel, kBrightnessId, raw);
}
std::optional<std::pair<int, int>> GetColor(const DeviceInfo& device, uint8_t channel) {
auto response = SendViaCommand(device, {kCmdGetValue, channel, kColorId});
if (!response.has_value() || response->size() < 5 || (*response)[0] == kCmdUnhandled) {
return std::nullopt;
}
return std::make_pair(static_cast<int>((*response)[3]), static_cast<int>((*response)[4]));
}
bool SetColor(const DeviceInfo& device, uint8_t channel, int hue, int sat) {
hue = std::clamp(hue, 0, 255);
sat = std::clamp(sat, 0, 255);
auto response = SendViaCommand(device, {kCmdSetValue, channel, kColorId, static_cast<uint8_t>(hue), static_cast<uint8_t>(sat)});
return response.has_value();
}
void ListEffects() {
std::cout << "Standard QMK RGB Effects (Note: Available effects vary by firmware):\n"
<< " 1: Solid Color\n"
<< " 2: Alphas Mods\n"
<< " 3: Gradient Up Down\n"
<< " 4: Gradient Left Right\n"
<< " 5: Breathing\n"
<< " 6: Band Sat\n"
<< " 7: Band Val\n"
<< " 8: Band Pin\n"
<< " 9: Band Spiral Sat\n"
<< " 10: Band Spiral Val\n"
<< " 11: Cycle All\n"
<< " 12: Cycle Left Right\n"
<< " 13: Cycle Up Down\n"
<< " 14: Rainbow Moving Chevron\n"
<< " 15: Cycle Out In\n"
<< " 16: Cycle Out In Dual\n"
<< " 17: Cycle Pinwheel\n"
<< " 18: Cycle Spiral\n"
<< " 19: Dual Beacon\n"
<< " 20: Rainbow Beacon\n"
<< " 21: Rainbow Pinwheels\n"
<< " 22: Raingdrops\n"
<< " 23: Jellybean Raindrops\n"
<< " 24: Hue Breathing\n"
<< " 25: Hue Pendulum\n"
<< " 26: Hue Wave\n"
<< " 27: Typing Heatmap\n"
<< " 28: Digital Rain\n"
<< " 29: Solid Reactive Simple\n"
<< " 30: Solid Reactive\n"
<< " 31: Solid Reactive Wide\n"
<< " 32: Solid Reactive Multiwide\n"
<< " 33: Solid Reactive Cross\n"
<< " 34: Solid Reactive Multicross\n"
<< " 35: Solid Reactive Nexus\n"
<< " 36: Solid Reactive Multinexus\n"
<< " 37: Splash\n"
<< " 38: Multisplash\n"
<< " 39: Solid Splash\n"
<< " 40: Solid Multisplash\n";
}
std::optional<int> ComputeTargetBrightness(const std::string& spec, int current) {
if (spec.empty()) {
return std::nullopt;
}
if (spec[0] == '+' || spec[0] == '-') {
auto delta = ParseInt(spec);
if (!delta.has_value()) {
return std::nullopt;
}
return current + *delta;
}
return ParseInt(spec);
}
void PrintError(const Options& opts, const std::string& message) {
if (!opts.quiet) {
std::cerr << message << "\n";
}
}
} // namespace
int main(int argc, char** argv) {
if (hid_init() != 0) {
std::cerr << "Failed to initialize hidapi\n";
return 1;
}
Options opts;
if (!ParseArgs(argc, argv, &opts)) {
PrintUsage(argv[0]);
hid_exit();
return 2;
}
auto devices = EnumerateCompatibleDevices();
if (opts.list_devices) {
ListDevices(devices);
hid_exit();
return 0;
}
if (opts.list_effects) {
ListEffects();
hid_exit();
return 0;
}
if (!opts.get_brightness && !opts.set_brightness.has_value() &&
!opts.get_effect && !opts.set_effect.has_value() &&
!opts.get_effect_speed && !opts.set_effect_speed.has_value() &&
!opts.get_color && !opts.set_color.has_value()) {
PrintError(opts, "Choose one operation: --get-brightness, --set-brightness, --list-effects, --get-effect, --set-effect, --get-effect-speed, --set-effect-speed, --get-color, or --set-color");
if (!opts.quiet) {
PrintUsage(argv[0]);
}
hid_exit();
return 2;
}
auto selected = SelectDevice(devices, opts);
if (!selected.has_value()) {
PrintError(opts, "No matching compatible device found");
hid_exit();
return 1;
}
auto channel = DetectChannel(*selected);
if (!channel.has_value()) {
PrintError(opts, "Selected device does not expose a supported lighting channel");
hid_exit();
return 1;
}
if (opts.get_brightness) {
auto value = GetBrightness(*selected, *channel);
if (!value.has_value()) {
PrintError(opts, "Failed to read brightness");
hid_exit();
return 1;
}
std::cout << *value << "\n";
hid_exit();
return 0;
}
if (opts.set_brightness.has_value()) {
auto current = GetBrightness(*selected, *channel);
if (!current.has_value()) {
PrintError(opts, "Failed to read current brightness");
hid_exit();
return 1;
}
auto target = ComputeTargetBrightness(*opts.set_brightness, *current);
if (!target.has_value()) {
PrintError(opts, std::string("Invalid --set-brightness value: ") + *opts.set_brightness);
hid_exit();
return 2;
}
if (!SetBrightness(*selected, *channel, *target)) {
PrintError(opts, "Failed to set brightness");
hid_exit();
return 1;
}
auto updated = GetBrightness(*selected, *channel);
if (updated.has_value()) {
std::cout << *updated << "\n";
}
hid_exit();
return 0;
}
if (opts.get_effect) {
auto value = GetProperty(*selected, *channel, kEffectId);
if (!value.has_value()) {
PrintError(opts, "Failed to read effect ID");
hid_exit();
return 1;
}
std::cout << *value << "\n";
hid_exit();
return 0;
}
if (opts.set_effect.has_value()) {
if (!SetProperty(*selected, *channel, kEffectId, *opts.set_effect)) {
PrintError(opts, "Failed to set effect ID");
hid_exit();
return 1;
}
auto updated = GetProperty(*selected, *channel, kEffectId);
if (updated.has_value()) {
std::cout << *updated << "\n";
}
hid_exit();
return 0;
}
if (opts.get_effect_speed) {
auto value = GetProperty(*selected, *channel, kEffectSpeedId);
if (!value.has_value()) {
PrintError(opts, "Failed to read effect speed");
hid_exit();
return 1;
}
std::cout << *value << "\n";
hid_exit();
return 0;
}
if (opts.set_effect_speed.has_value()) {
if (!SetProperty(*selected, *channel, kEffectSpeedId, *opts.set_effect_speed)) {
PrintError(opts, "Failed to set effect speed");
hid_exit();
return 1;
}
auto updated = GetProperty(*selected, *channel, kEffectSpeedId);
if (updated.has_value()) {
std::cout << *updated << "\n";
}
hid_exit();
return 0;
}
if (opts.get_color) {
auto value = GetColor(*selected, *channel);
if (!value.has_value()) {
PrintError(opts, "Failed to read color");
hid_exit();
return 1;
}
std::cout << value->first << "," << value->second << "\n";
hid_exit();
return 0;
}
if (opts.set_color.has_value()) {
if (!SetColor(*selected, *channel, opts.set_color->first, opts.set_color->second)) {
PrintError(opts, "Failed to set color");
hid_exit();
return 1;
}
auto updated = GetColor(*selected, *channel);
if (updated.has_value()) {
std::cout << updated->first << "," << updated->second << "\n";
}
hid_exit();
return 0;
}
hid_exit();
return 0;
}