import json import time from kmk.modules import Module from usb_cdc import data class Client(Module): """ Listen the connections from host, and apply the actions depending of the json command. """ def __init__(self): self.last_name = None 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 or not data.connected: current_name = keyboard.keymap[0].name if current_name != "Disconnected": self.last_name = current_name keyboard.keymap[0].name = "Disconnected" time.sleep(1) return if self.last_name is not None: keyboard.keymap[0].name = self.last_name self.last_name = None # 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. """