aboutsummaryrefslogtreecommitdiff
path: root/serial_conn.py
diff options
context:
space:
mode:
authorSébastien Dailly <sebastien@dailly.me>2025-07-20 15:26:58 +0200
committerSébastien Dailly <sebastien@dailly.me>2025-07-20 15:26:58 +0200
commitc31148f482adf44ded7cec1d683e01d995294850 (patch)
tree42dc4032085fc1466bbdeb5bf71076436a3844ef /serial_conn.py
parentcc2c9c0bd9d646a33f0324eae024618bd2a68983 (diff)
Added some tests, and a handle commands in the json (only 'layer' for now)
Diffstat (limited to 'serial_conn.py')
-rw-r--r--serial_conn.py90
1 files changed, 90 insertions, 0 deletions
diff --git a/serial_conn.py b/serial_conn.py
new file mode 100644
index 0000000..4e885b2
--- /dev/null
+++ b/serial_conn.py
@@ -0,0 +1,90 @@
+from kmk.modules import Module
+from usb_cdc import data
+import json
+
+import json_layer
+
+class Client(Module):
+ """ Listen the connections from host, and apply the actions depending of
+ the json command.
+ """
+
+ def during_bootup(self, keyboard):
+ try:
+ # Do not set any timeout, we check before reading a string if there
+ # is any content to read, but block to be sure to read everything.
+ data.timeout = None
+ except AttributeError:
+ pass
+
+ def process_key(self, keyboard, key, is_pressed, int_coord):
+ return key
+
+ def before_hid_send(self, keyboard):
+
+ # Serial.data isn't initialized yet.
+ if not data:
+ return
+
+ if not data.connected:
+ keyboard.keymap[0].name = "Disconnected"
+ return
+
+ # Nothing to parse.
+ if data.in_waiting <= 0:
+ return
+ line = data.readline()
+ if not line:
+ return
+
+ try:
+ content = line.decode().strip()
+ if not content:
+ # If strip produced an empty string, stop here.
+ return
+ jdata = json.loads(content)
+ except ValueError as err:
+ # In circuitPython, json error are reported as ValueError.
+ # seet https://docs.circuitpython.org/en/latest/docs/library/json.html#json.load
+ print(err, line)
+ return
+
+ # Json is valid, try to read the command, and consider the input is a
+ # direct raw layer instruction if this does not work.
+
+ actions = {
+ "layer" : lambda x : keyboard.keymap[0].load(x),
+ }
+
+ try:
+ for action, args in jdata.items():
+ actions[action](args)
+ return
+ except Exception as err:
+ pass
+
+ try:
+ keyboard.keymap[0].load(jdata)
+ except Exception as err:
+ print("rawdata:", err)
+ return
+
+ def before_matrix_scan(self, keyboard):
+ """ Default implementation, do nothing.
+ """
+
+ def after_matrix_scan(self, keyboard):
+ """ Default implementation, do nothing.
+ """
+
+ def after_hid_send(self, keyboard):
+ """ Default implementation, do nothing.
+ """
+
+ def on_powersave_enable(self, keyboard):
+ """ Default implementation, do nothing.
+ """
+
+ def on_powersave_disable(self, keyboard):
+ """ Default implementation, do nothing.
+ """