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. """