-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqmk2srgb.py
executable file
·430 lines (363 loc) · 13 KB
/
qmk2srgb.py
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
#!/usr/bin/env python3
# Copyright (c) 2023 Dylan Perks.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# Converts a QMK keymap into a SignalRGB plugin.
import argparse
import glob
import jsoncomment
import os
import unicodedata
# format with:
# - keyboard name
# - vid
# - pid
# - num X
# - num Y
# - vkeys
# - vkeynames
# - vkeypositions
TEMPLATE = """export function Name() { return "$KNAME$ QMK Keyboard"; }
export function Version() { return "1.1.6"; }
export function VendorId() { return $VID$; }
export function ProductId() { return $PID$; }
export function Publisher() { return "Polyhaze (@Polyhaze) / Dylan Perks (@Perksey)"; }
export function Documentation(){ return "qmk/srgbmods-qmk-firmware"; }
export function Size() { return [$NX$, $NY$]; }
export function DefaultPosition(){return [10, 100]; }
export function DefaultScale(){return 8.0;}
/* global
shutdownMode:readonly
shutdownColor:readonly
LightingMode:readonly
forcedColor:readonly
*/
export function ControllableParameters()
{
return [
{"property":"shutdownMode", "group":"lighting", "label":"Shutdown Mode", "type":"combobox", "values":["SignalRGB", "Hardware"], "default":"SignalRGB"},
{"property":"shutdownColor", "group":"lighting", "label":"Shutdown Color", "min":"0", "max":"360", "type":"color", "default":"#000000"},
{"property":"LightingMode", "group":"lighting", "label":"Lighting Mode", "type":"combobox", "values":["Canvas", "Forced"], "default":"Canvas"},
{"property":"forcedColor", "group":"lighting", "label":"Forced Color", "min":"0", "max":"360", "type":"color", "default":"#009bde"},
];
}
//Plugin Version: Built for Protocol V1.0.4
const vKeys = [
$VK$
];
const vKeyNames = [
$VKNAMES$
];
const vKeyPositions = [
$VKPOS$
];
let LEDCount = 0;
let IsViaKeyboard = false;
const MainlineQMKFirmware = 1;
const VIAFirmware = 2;
const PluginProtocolVersion = "1.0.4";
export function LedNames() {
return vKeyNames;
}
export function LedPositions() {
return vKeyPositions;
}
export function vKeysArrayCount() {
device.log('vKeys ' + vKeys.length);
device.log('vKeyNames ' + vKeyNames.length);
device.log('vKeyPositions ' + vKeyPositions.length);
}
export function Initialize() {
requestFirmwareType();
requestQMKVersion();
requestSignalRGBProtocolVersion();
requestUniqueIdentifier();
requestTotalLeds();
effectEnable();
}
export function Render() {
sendColors();
}
export function Shutdown(SystemSuspending) {
if(SystemSuspending) {
sendColors("#000000"); // Go Dark on System Sleep/Shutdown
} else {
if (shutdownMode === "SignalRGB") {
sendColors(shutdownColor);
} else {
effectDisable();
}
}
vKeysArrayCount(); // For debugging array counts
}
function commandHandler() {
const readCounts = [];
do {
const returnpacket = device.read([0x00], 32, 10);
processCommands(returnpacket);
readCounts.push(device.getLastReadSize());
// Extra Read to throw away empty packets from Via
// Via always sends a second packet with the same Command Id.
if(IsViaKeyboard) {
device.read([0x00], 32, 10);
}
}
while(device.getLastReadSize() > 0);
}
function processCommands(data) {
switch(data[1]) {
case 0x21:
returnQMKVersion(data);
break;
case 0x22:
returnSignalRGBProtocolVersion(data);
break;
case 0x23:
returnUniqueIdentifier(data);
break;
case 0x24:
sendColors();
break;
case 0x27:
returnTotalLeds(data);
break;
case 0x28:
returnFirmwareType(data);
break;
}
}
function requestQMKVersion() //Check the version of QMK Firmware that the keyboard is running
{
device.write([0x00, 0x21], 32);
device.pause(30);
commandHandler();
}
function returnQMKVersion(data) {
const QMKVersionByte1 = data[2];
const QMKVersionByte2 = data[3];
const QMKVersionByte3 = data[4];
device.log("QMK Version: " + QMKVersionByte1 + "." + QMKVersionByte2 + "." + QMKVersionByte3);
device.log("QMK SRGB Plugin Version: "+ Version());
device.pause(30);
}
function requestSignalRGBProtocolVersion() //Grab the version of the SignalRGB Protocol the keyboard is running
{
device.write([0x00, 0x22], 32);
device.pause(30);
commandHandler();
}
function returnSignalRGBProtocolVersion(data) {
const ProtocolVersionByte1 = data[2];
const ProtocolVersionByte2 = data[3];
const ProtocolVersionByte3 = data[4];
const SignalRGBProtocolVersion = ProtocolVersionByte1 + "." + ProtocolVersionByte2 + "." + ProtocolVersionByte3;
device.log(`SignalRGB Protocol Version: ${SignalRGBProtocolVersion}`);
if(PluginProtocolVersion !== SignalRGBProtocolVersion) {
device.notify("Unsupported Protocol Version: ", `This plugin is intended for SignalRGB Protocol version ${PluginProtocolVersion}. This device is version: ${SignalRGBProtocolVersion}`, 1, "Documentation");
}
device.pause(30);
}
function requestUniqueIdentifier() //Grab the unique identifier for this keyboard model
{
if(device.write([0x00, 0x23], 32) === -1) {
device.notify("Unsupported Firmware: ", `This device is not running SignalRGB-compatible firmware. Click the Open Troubleshooting Docs button to learn more.`, 1, "Documentation");
}
device.pause(30);
commandHandler();
}
function returnUniqueIdentifier(data) {
const UniqueIdentifierByte1 = data[2];
const UniqueIdentifierByte2 = data[3];
const UniqueIdentifierByte3 = data[4];
if(!(UniqueIdentifierByte1 === 0 && UniqueIdentifierByte2 === 0 && UniqueIdentifierByte3 === 0)) {
device.log("Unique Device Identifier: " + UniqueIdentifierByte1 + UniqueIdentifierByte2 + UniqueIdentifierByte3);
}
device.pause(30);
}
function requestTotalLeds() //Calculate total number of LEDs
{
device.write([0x00, 0x27], 32);
device.pause(30);
commandHandler();
}
function returnTotalLeds(data) {
LEDCount = data[2];
device.log("Device Total LED Count: " + LEDCount);
device.pause(30);
}
function requestFirmwareType() {
device.write([0x00, 0x28], 32);
device.pause(30);
commandHandler();
}
function returnFirmwareType(data) {
const FirmwareTypeByte = data[2];
if(!(FirmwareTypeByte === MainlineQMKFirmware || FirmwareTypeByte === VIAFirmware)) {
device.notify("Unsupported Firmware: ", "Click Show Console, and then click on troubleshooting for your keyboard to find out more.", 1, "Documentation");
}
if(FirmwareTypeByte === MainlineQMKFirmware) {
IsViaKeyboard = false;
device.log("Firmware Type: Mainline");
}
if(FirmwareTypeByte === VIAFirmware) {
IsViaKeyboard = true;
device.log("Firmware Type: VIA");
}
device.pause(30);
}
function effectEnable() //Enable the SignalRGB Effect Mode
{
device.write([0x00, 0x25], 32);
device.pause(30);
}
function effectDisable() //Revert to Hardware Mode
{
device.write([0x00, 0x26], 32);
device.pause(30);
}
function createSolidColorArray(color) {
const rgbdata = new Array(vKeys.length * 3).fill(0);
for(let iIdx = 0; iIdx < vKeys.length; iIdx++) {
const iLedIdx = vKeys[iIdx] * 3;
rgbdata[iLedIdx] = color[0];
rgbdata[iLedIdx+1] = color[1];
rgbdata[iLedIdx+2] = color[2];
}
return rgbdata;
}
function grabColors(overrideColor) {
if(overrideColor) {
return createSolidColorArray(hexToRgb(overrideColor));
} else if (LightingMode === "Forced") {
return createSolidColorArray(hexToRgb(forcedColor));
}
const rgbdata = new Array(vKeys.length * 3).fill(0);
for(let iIdx = 0; iIdx < vKeys.length; iIdx++) {
const iPxX = vKeyPositions[iIdx][0];
const iPxY = vKeyPositions[iIdx][1];
const color = device.color(iPxX, iPxY);
const iLedIdx = vKeys[iIdx] * 3;
rgbdata[iLedIdx] = color[0];
rgbdata[iLedIdx+1] = color[1];
rgbdata[iLedIdx+2] = color[2];
}
return rgbdata;
}
function sendColors(overrideColor) {
const rgbdata = grabColors(overrideColor);
const LedsPerPacket = 9;
let BytesSent = 0;
let BytesLeft = rgbdata.length;
while(BytesLeft > 0) {
const BytesToSend = Math.min(LedsPerPacket * 3, BytesLeft);
StreamLightingData(Math.floor(BytesSent / 3), rgbdata.splice(0, BytesToSend));
BytesLeft -= BytesToSend;
BytesSent += BytesToSend;
}
}
function StreamLightingData(StartLedIdx, RGBData) {
const packet = [0x00, 0x24, StartLedIdx, Math.floor(RGBData.length / 3)].concat(RGBData);
device.write(packet, 33);
}
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
const colors = [];
colors[0] = parseInt(result[1], 16);
colors[1] = parseInt(result[2], 16);
colors[2] = parseInt(result[3], 16);
return colors;
}
export function Validate(endpoint) {
return endpoint.interface === 1;
}
export function Image() {
return "";
}
"""
parser = argparse.ArgumentParser()
parser.add_argument("inputs", help="QMK info.json files (globs)", nargs="+")
parser.add_argument("--outdir", help="Output Directory for JS files", default=".")
parser.add_argument(
"--matrix_sizing",
help="Instead of being accurate to the original info.json (often generating very large sizes), the first "
"coordinate for a given key matrix coordinate will be used for the entire column or row.",
action="store_true",
default=False,
)
args = parser.parse_args()
for i_glob in args.inputs:
for i_file in glob.glob(i_glob, recursive=True):
try:
i_json = None
with open(i_file, "r") as f:
i_json = jsoncomment.JsonComment().loads(f.read())
k_name = f"{i_json['manufacturer']} {i_json['keyboard_name']}"
vid = i_json["usb"]["vid"]
pid = i_json["usb"]["pid"]
xs = list(
set(
sorted(
x["x"] if not args.matrix_sizing or "matrix" not in x else x["matrix"][1]
for x in i_json["rgb_matrix"]["layout"]
)
)
)
ys = list(
set(
sorted(
x["y"] if not args.matrix_sizing or "matrix" not in x else x["matrix"][0]
for x in i_json["rgb_matrix"]["layout"]
)
)
)
vkeys = ", ".join(str(x) for x in range(0, len(i_json["rgb_matrix"]["layout"])))
vkeynames = []
vkeypositions = []
unnamed = 0
matxs = {}
matys = {}
for led in i_json["rgb_matrix"]["layout"]:
lbl = None
ledx = xs.index(led["x"] if not args.matrix_sizing or "matrix" not in led else led["matrix"][1])
ledy = ys.index(led["y"] if not args.matrix_sizing or "matrix" not in led else led["matrix"][0])
if "matrix" in led and "layouts" in i_json:
ledx = matxs.setdefault(led["matrix"][0], ledx) if args.matrix_sizing else ledx
ledy = matys.setdefault(led["matrix"][1], ledy) if args.matrix_sizing else ledy
key = next(
(x for x in list(i_json["layouts"].values())[0]["layout"] if x["matrix"] == led["matrix"]), None
)
if key is not None and "label" in key:
lbl = key["label"]
if not lbl.isascii():
lbl = unicodedata.name(lbl)
if "\\" in lbl:
lbl = lbl.replace("\\", "\\\\")
if '"' in lbl:
lbl = lbl.replace('"', '\\"')
if lbl is None:
unnamed += 1
lbl = f"Light {unnamed}"
vkeynames.append(lbl)
vkeypositions.append([ledx, ledy])
vkeynames = ", ".join(f'"{x}"' for x in vkeynames)
vkeypositions = ", ".join(str(x) for x in vkeypositions)
o_file = os.path.join(
args.outdir, f"{''.join(x for x in k_name if x.isalnum() or x == ' ').lower().replace(' ', '_')}.js"
)
with open(o_file, "w") as f:
f.write(
TEMPLATE.replace("$KNAME$", k_name)
.replace("$VID$", vid)
.replace("$PID$", pid)
.replace("$NX$", str(len(xs)))
.replace("$NY$", str(len(ys)))
.replace("$VK$", vkeys)
.replace("$VKNAMES$", vkeynames)
.replace("$VKPOS$", vkeypositions)
)
print(f"Successfully created {o_file}")
except Exception as e:
print(f"Skipping {i_file} due to exception: {repr(e)}")