Compare commits

..

2 Commits

Author SHA1 Message Date
Jesse Vincent ad6f7bb0ce
remove some debugging
3 years ago
Jesse Vincent 7d5f3fd5c8
Add temp debugging info
3 years ago

1
.gitignore vendored

@ -13,4 +13,3 @@
/results/ /results/
generated-testcase.cpp generated-testcase.cpp
.arduino .arduino
/bin/arduino-cli

@ -5,7 +5,7 @@ Flexible firmware for Arduino-powered keyboards.
This package contains the "core" of Kaleidoscope and a number of [example firmware "Sketches"](https://github.com/keyboardio/Kaleidoscope/tree/master/examples). This package contains the "core" of Kaleidoscope and a number of [example firmware "Sketches"](https://github.com/keyboardio/Kaleidoscope/tree/master/examples).
If you're just getting started with the Keyboardio Model 01, the [introductory docs are here](https://github.com/keyboardio/Kaleidoscope/wiki/Keyboardio-Model-01-Introduction) and the source for the basic firmware package is here: https://github.com/keyboardio/Model01-Firmware. It's probably a good idea to start there, learn how to modify your keymap and maybe turn some modules on or off, and then come back to the full repository when you have more complex changes in mind. (The firmware for all other devices is inside examples/Devices in this Kaleidoscope repo.) If you're just getting started with the Keyboardio Model 01, the [introductory docs are here](https://github.com/keyboardio/Kaleidoscope/wiki/Keyboardio-Model-01-Introduction) and the source for the basic firmware package is here: https://github.com/keyboardio/Model01-Firmware. It's probably a good idea to start there, learn how to modify your keymap and maybe turn some modules on or off, and then come back to the full repository when you have more complex changes in mind.
# Getting Started # Getting Started

@ -1,63 +0,0 @@
#!/usr/bin/env bash
# focus-send - Trivial Focus testing tool
# Copyright (C) 2018-2022 Keyboard.io, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
set -e
OS=$(uname -s)
# igncr absorbs CR from Focus CRLF line endings
# -echo is needed because raw doesn't turn it off on Linux
STTY_ARGS="9600 raw igncr -echo"
case ${OS} in
Linux)
DEVICE="${DEVICE:-/dev/ttyACM0}"
;;
Darwin)
# bash on macOS has a bug that randomly drops serial input
if [ -n "$BASH_VERSION" ] && [ -x /bin/dash ]; then
# Prevent loop in case someone exported it
export -n BASH_VERSION
exec /bin/dash "$0" "$@"
fi
DEVICE="${DEVICE:-/dev/cu.usbmodemCkbio01E}"
;;
*)
echo "Error Unknown OS : ${OS}" >&2
exit 1
;;
esac
# Redirect prior to running stty, because macOS sometimes resets termios
# state upon last close of a terminal device.
exec < "${DEVICE}"
# shellcheck disable=SC2086 # intentional word splitting
stty $STTY_ARGS
read_reply () {
while read -r line; do
if [ "${line}" = "." ]; then
break
fi
echo "${line}"
done
}
# Flush any invalid commands out of input buffer.
# This could happen after a failed upload.
echo ' ' > "${DEVICE}"
read_reply > /dev/null
echo "$@" >"${DEVICE}"
read_reply

@ -0,0 +1,45 @@
#!/usr/bin/env bash
# focus-test - Trivial Focus testing tool
# Copyright (C) 2018 Keyboard.io, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
set -e
OS=$(uname -s)
case ${OS} in
Linux)
DEVICE="${DEVICE:-/dev/ttyACM0}"
stty -F "${DEVICE}" 9600 raw -echo
;;
Darwin)
DEVICE="${DEVICE:-/dev/cu.usbmodemCkbio01E}"
stty -f "${DEVICE}" 9600 raw -echo
;;
*)
echo "Error Unknown OS : ${OS}" >&2
exit 1
;;
esac
exec 3<"${DEVICE}"
echo "$@" >"${DEVICE}"
while read -r line <&3; do
line="$(echo -n "${line}" | tr -d '\r')"
if [ "${line}" == "." ]; then
break
fi
echo "${line}"
done

@ -273,13 +273,8 @@ class FocusExampleCommand : public Plugin {
return ::Focus.sendName(F("FocusExampleCommand")); return ::Focus.sendName(F("FocusExampleCommand"));
} }
EventHandlerResult onFocusEvent(const char *input) { EventHandlerResult onFocusEvent(const char *command) {
const char *cmd = PSTR("example"); if (strcmp_P(command, PSTR("example")) != 0)
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd);
if (!::Focus.inputMatchesCommand(input, cmd))
return EventHandlerResult::OK; return EventHandlerResult::OK;
::Focus.send(F("This is an example response. Hello world!")); ::Focus.send(F("This is an example response. Hello world!"));
@ -353,8 +348,8 @@ class ExamplePlugin : public Plugin {
public: public:
ExamplePlugin(); ExamplePlugin();
EventHandlerResult onFocusEvent(const char *input) { EventHandlerResult onFocusEvent(const char *command) {
if (!::Focus.inputMatchesCommand(input, PSTR("example.toggle"))) if (strcmp_P(command, PSTR("example.toggle")) != 0)
return EventHandlerResult::OK; return EventHandlerResult::OK;
example_toggle_ = !example_toggle_; example_toggle_ = !example_toggle_;
@ -413,8 +408,8 @@ class ExampleOptionalCommand : public Plugin {
public: public:
ExampleOptionalCommand() {} ExampleOptionalCommand() {}
EventHandlerResult onFocusEvent(const char *input) { EventHandlerResult onFocusEvent(const char *command) {
if (!::Focus.inputMatchesCommand(input, PSTR("optional"))) if (strcmp_P(command, PSTR("optional")) != 0)
return EventHandlerResult::OK; return EventHandlerResult::OK;
::Focus.send(Layer.getLayerState()); ::Focus.send(Layer.getLayerState());
@ -798,7 +793,7 @@ void macroNewSentence(KeyEvent &event) {
`kaleidoscope-builder` has been removed. `kaleidoscope-builder` has been removed.
We replaced it with a new Makefile based build system that uses `arduino-cli` instead of of the full Arduino IDE. This means that you can now check out development copies of Kaliedoscope into any directory, using the `KALEIDOSCOPE_DIR` environment variable to point to your installation. We replaced it with a new Makefile based build system that uses `arduino-cli` instead of of the full Arduino IDE. This means that you can now check out development copies of Kaliedoscope into any directory, using the `KALEIDOSCOPE_DIR` environment variable to point to your installation.
### OneShot meta keys ### OneShot meta keys

@ -175,7 +175,7 @@ struct KeypadProps : kaleidoscope::device::ATmega32U4KeyboardProps {
}; };
typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner; typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner;
typedef kaleidoscope::driver::bootloader::avr::Caterina Bootloader; typedef kaleidoscope::driver::bootloader::avr::Caterina BootLoader;
static constexpr const char *short_name = "imaginary-keypad"; static constexpr const char *short_name = "imaginary-keypad";
}; };

@ -14,5 +14,3 @@ SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2300", SYMLINK+="
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2301", SYMLINK+="model01", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat" SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2301", SYMLINK+="model01", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2302", SYMLINK+="Atreus2", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat" SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2302", SYMLINK+="Atreus2", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2303", SYMLINK+="Atreus2", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat" SUBSYSTEMS=="usb", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="2303", SYMLINK+="Atreus2", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="3496", ATTRS{idProduct}=="0005", SYMLINK+="model100", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="3496", ATTRS{idProduct}=="0006", SYMLINK+="model100", ENV{ID_MM_DEVICE_IGNORE}:="1", ENV{ID_MM_CANDIDATE}:="0", TAG+="uaccess", TAG+="seat"

@ -164,7 +164,7 @@ endif
compile: kaleidoscope-hardware-configured compile: kaleidoscope-hardware-configured
-$(QUIET) install -d "${OUTPUT_PATH}" $(QUIET) install -d "${OUTPUT_PATH}"
$(QUIET) $(ARDUINO_CLI) compile --fqbn "${FQBN}" ${ARDUINO_VERBOSE} ${ccache_wrapper_property} ${local_cflags_property} \ $(QUIET) $(ARDUINO_CLI) compile --fqbn "${FQBN}" ${ARDUINO_VERBOSE} ${ccache_wrapper_property} ${local_cflags_property} \
${_arduino_local_libraries_prop} ${_ARDUINO_CLI_COMPILE_CUSTOM_FLAGS} \ ${_arduino_local_libraries_prop} ${_ARDUINO_CLI_COMPILE_CUSTOM_FLAGS} \
--library "${KALEIDOSCOPE_DIR}" \ --library "${KALEIDOSCOPE_DIR}" \
@ -191,9 +191,10 @@ endif
#TODO (arduino team) I'd love to do this with their json output #TODO (arduino team) I'd love to do this with their json output
#but it's short some of the data we kind of need #but it's short some of the data we kind of need
flashing_instructions = $(call _arduino_prop,build.flashing_instructions) flashing_instructions = $(call _arduino_prop,build.flashing_instructions)
_device_port = $(shell $(ARDUINO_CLI) board list --format=text | grep $(FQBN) |cut -d' ' -f 1)
flash: ${HEX_FILE_PATH} flash: ${HEX_FILE_PATH}
ifneq ($(flashing_instructions),) ifneq ($(flashing_instructions),)
$(info $(shell printf $(flashing_instructions))) $(info $(shell printf $(flashing_instructions)))
@ -203,12 +204,14 @@ endif
$(info ) $(info )
$(info When you're ready to proceed, press 'Enter'.) $(info When you're ready to proceed, press 'Enter'.)
$(info ) $(info )
$(info Your FQBN is $(FQBN))
$(info I think the device port is: )
$(info '$(_device_port)')
@$(shell read _) @$(shell read _)
# If we have a device serial port available, try to trigger a Kaliedoscope reset # If we have a device serial port available, try to trigger a Kaliedoscope reset
-$(QUIET) export DEVICE=$(shell $(ARDUINO_CLI) board list --format=text | grep $(FQBN) |cut -d' ' -f 1) && \ ifneq ($(_device_port),)
[ -e "$$DEVICE" ] && \ $(QUIET) echo "device.reset" > $(_device_port)
$(KALEIDOSCOPE_DIR)/bin/focus-send "device.reset" && \ endif
sleep 2
$(QUIET) $(ARDUINO_CLI) upload --fqbn $(FQBN) \ $(QUIET) $(ARDUINO_CLI) upload --fqbn $(FQBN) \
$(shell $(ARDUINO_CLI) board list --format=text | grep $(FQBN) |cut -d' ' -f 1 | xargs -n 1 echo "--port" ) \ $(shell $(ARDUINO_CLI) board list --format=text | grep $(FQBN) |cut -d' ' -f 1 | xargs -n 1 echo "--port" ) \
--input-dir "${OUTPUT_PATH}" \ --input-dir "${OUTPUT_PATH}" \

@ -1,6 +1,6 @@
/* -*- mode: c++ -*- /* -*- mode: c++ -*-
* Atreus -- Chrysalis-enabled Sketch for the Keyboardio Atreus * Atreus -- Chrysalis-enabled Sketch for the Keyboardio Atreus
* Copyright (C) 2018-2022 Keyboard.io, Inc * Copyright (C) 2018, 2019 Keyboard.io, Inc
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@ -24,16 +24,13 @@
#include "Kaleidoscope.h" #include "Kaleidoscope.h"
#include "Kaleidoscope-EEPROM-Settings.h" #include "Kaleidoscope-EEPROM-Settings.h"
#include "Kaleidoscope-EEPROM-Keymap.h" #include "Kaleidoscope-EEPROM-Keymap.h"
#include "Kaleidoscope-Escape-OneShot.h"
#include "Kaleidoscope-FirmwareVersion.h"
#include "Kaleidoscope-FocusSerial.h" #include "Kaleidoscope-FocusSerial.h"
#include "Kaleidoscope-Macros.h" #include "Kaleidoscope-Macros.h"
#include "Kaleidoscope-MouseKeys.h" #include "Kaleidoscope-MouseKeys.h"
#include "Kaleidoscope-OneShot.h" #include "Kaleidoscope-OneShot.h"
#include "Kaleidoscope-Qukeys.h" #include "Kaleidoscope-Qukeys.h"
#include "Kaleidoscope-SpaceCadet.h" #include "Kaleidoscope-SpaceCadet.h"
#include "Kaleidoscope-DynamicMacros.h"
#include "Kaleidoscope-LayerNames.h"
#define MO(n) ShiftToLayer(n) #define MO(n) ShiftToLayer(n)
#define TG(n) LockLayer(n) #define TG(n) LockLayer(n)
@ -103,7 +100,6 @@ KEYMAPS(
// clang-format on // clang-format on
KALEIDOSCOPE_INIT_PLUGINS( KALEIDOSCOPE_INIT_PLUGINS(
EscapeOneShot,
EEPROMSettings, EEPROMSettings,
EEPROMKeymap, EEPROMKeymap,
Focus, Focus,
@ -113,11 +109,7 @@ KALEIDOSCOPE_INIT_PLUGINS(
SpaceCadet, SpaceCadet,
OneShot, OneShot,
Macros, Macros,
DynamicMacros, MouseKeys);
MouseKeys,
EscapeOneShotConfig,
FirmwareVersion,
LayerNames);
const macro_t *macroAction(uint8_t macro_id, KeyEvent &event) { const macro_t *macroAction(uint8_t macro_id, KeyEvent &event) {
if (keyToggledOn(event.state)) { if (keyToggledOn(event.state)) {
@ -143,13 +135,7 @@ const macro_t *macroAction(uint8_t macro_id, KeyEvent &event) {
void setup() { void setup() {
Kaleidoscope.setup(); Kaleidoscope.setup();
SpaceCadet.disable(); SpaceCadet.disable();
EEPROMKeymap.setup(9); EEPROMKeymap.setup(10);
DynamicMacros.reserve_storage(48);
LayerNames.reserve_storage(63);
Layer.move(EEPROMSettings.default_layer());
} }
void loop() { void loop() {

@ -1,8 +1,6 @@
# This makefile for a Kaleidoscope sketch pulls in all the targets # This makefile for a Kaleidoscope sketch pulls in all the targets
# required to build the example # required to build the example
# Compile without deprecated code to save space
LOCAL_CFLAGS ?= -DNDEPRECATED -DONESHOT_WITHOUT_METASTICKY

@ -1,522 +1,106 @@
// -*- mode: c++ -*- /* -*- mode: c++ -*-
// Copyright 2016 Keyboardio, inc. <jesse@keyboard.io> * Kaleidoscope - A Kaleidoscope example
// See "LICENSE" for license details * Copyright (C) 2016-2019 Keyboard.io, Inc.
*
#ifndef BUILD_INFORMATION * This program is free software: you can redistribute it and/or modify it under
#define BUILD_INFORMATION "locally built on " __DATE__ " at " __TIME__ * the terms of the GNU General Public License as published by the Free Software
#endif * Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
/** * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* These #include directives pull in the Kaleidoscope firmware core, * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* as well as the Kaleidoscope plugins we use in the Model 01's firmware * details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#define DEBUG_SERIAL false
// The Kaleidoscope core
#include "Kaleidoscope.h" #include "Kaleidoscope.h"
// Support for storing the keymap in EEPROM
#include "Kaleidoscope-EEPROM-Settings.h"
#include "Kaleidoscope-EEPROM-Keymap.h"
// Support for communicating with the host via a simple Serial protocol
#include "Kaleidoscope-FocusSerial.h"
// Support for querying the firmware version via Focus
#include "Kaleidoscope-FirmwareVersion.h"
// Support for keys that move the mouse
#include "Kaleidoscope-MouseKeys.h" #include "Kaleidoscope-MouseKeys.h"
// Support for macros & dynamic macros
#include "Kaleidoscope-Macros.h" #include "Kaleidoscope-Macros.h"
#include "Kaleidoscope-DynamicMacros.h"
// Support for controlling the keyboard's LEDs
#include "Kaleidoscope-LEDControl.h" #include "Kaleidoscope-LEDControl.h"
// Support for "Numpad" mode, which is mostly just the Numpad specific LED mode
#include "Kaleidoscope-NumPad.h" #include "Kaleidoscope-NumPad.h"
#include "Kaleidoscope-HardwareTestMode.h"
#include "Kaleidoscope-MagicCombo.h"
// Support for the "Boot greeting" effect, which pulses the 'LED' button for 10s
// when the keyboard is connected to a computer (or that computer is powered on)
#include "Kaleidoscope-LEDEffect-BootGreeting.h"
// Support for LED modes that set all LEDs to a single color
#include "Kaleidoscope-LEDEffect-SolidColor.h" #include "Kaleidoscope-LEDEffect-SolidColor.h"
// Support for an LED mode that makes all the LEDs 'breathe'
#include "Kaleidoscope-LEDEffect-Breathe.h" #include "Kaleidoscope-LEDEffect-Breathe.h"
// Support for an LED mode that makes a red pixel chase a blue pixel across the keyboard
#include "Kaleidoscope-LEDEffect-Chase.h" #include "Kaleidoscope-LEDEffect-Chase.h"
// Support for LED modes that pulse the keyboard's LED in a rainbow pattern
#include "Kaleidoscope-LEDEffect-Rainbow.h" #include "Kaleidoscope-LEDEffect-Rainbow.h"
// Support for shared palettes for other plugins, like Colormap below #define NUMPAD_KEYMAP 2
#include "Kaleidoscope-LED-Palette-Theme.h"
// clang-format off
// Support for an LED mode that lets one configure per-layer color maps #define GENERIC_FN2 KEYMAP_STACKED ( \
#include "Kaleidoscope-Colormap.h" ___, Key_F1, Key_F2, Key_F3, Key_F4, Key_F5, XXX, \
Key_Tab, Key_mouseBtnM, Key_mouseUp, ___, Key_mouseWarpNW, Key_mouseWarpNE, Consumer_ScanNextTrack, \
// Support for Keyboardio's internal keyboard testing mode Key_Home, Key_mouseL, Key_mouseDn, Key_mouseR, Key_mouseWarpSW, Key_mouseWarpSE, \
#include "Kaleidoscope-HardwareTestMode.h" Key_End, Key_Z, Key_X, Key_C, Key_V, Key_mouseWarpEnd, ___, \
Key_LeftControl, Key_mouseBtnL, Key_LeftGui, Key_LeftShift, \
// Support for host power management (suspend & wakeup) ___, \
#include "Kaleidoscope-HostPowerManagement.h" \
XXX, Key_F6, Key_F7, Key_F8, Key_F9, ___, ___, \
// Support for magic combos (key chords that trigger an action) Key_Delete, Consumer_PlaySlashPause, Key_LeftCurlyBracket, Key_RightCurlyBracket, Key_LeftBracket, Key_RightBracket, System_Sleep, \
#include "Kaleidoscope-MagicCombo.h" Key_LeftArrow, Key_DownArrow, Key_UpArrow, Key_RightArrow, Key_F11, Key_F12, \
___, Consumer_VolumeDecrement, Consumer_VolumeIncrement, Key_BacklightDown, Key_BacklightUp, Key_Backslash, Key_Pipe, \
// Support for secondary actions (one action when tapped, another when held) Key_RightShift, Key_RightAlt, Key_mouseBtnR, Key_RightControl, \
#include "Kaleidoscope-Qukeys.h" ___\
)
// Support for USB quirks, like changing the key state report protocol
#include "Kaleidoscope-USB-Quirks.h" #define NUMPAD KEYMAP (\
___, ___, ___, ___, ___, ___, ___, ___, ___, Key_Keypad7, Key_Keypad8, Key_Keypad9, Key_KeypadSubtract, ___, \
/** This 'enum' is a list of all the macros used by the Model 01's firmware ___, ___, ___, ___, ___, ___, ___, ___, ___, Key_Keypad4, Key_Keypad5, Key_Keypad6, Key_KeypadAdd, ___, \
* The names aren't particularly important. What is important is that each ___, ___, ___, ___, ___, ___, ___, Key_Keypad1, Key_Keypad2, Key_Keypad3, Key_Equals, Key_Quote, \
* is unique. ___, ___, ___, ___, ___, ___, ___, ___, ___, Key_Keypad0, Key_KeypadDot, Key_KeypadMultiply, Key_KeypadDivide, Key_Enter, \
* Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift, Key_RightShift, Key_RightAlt, Key_Spacebar, Key_RightControl, \
* These are the names of your macros. They'll be used in two places. Key_Keymap1_Momentary, Key_Keymap1_Momentary \
* The first is in your keymap definitions. There, you'll use the syntax )
* `M(MACRO_NAME)` to mark a specific keymap position as triggering `MACRO_NAME`
* #define QWERTY KEYMAP ( \
* The second usage is in the 'switch' statement in the `macroAction` function. ___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext, ___, Key_6, Key_7, Key_8, Key_9, Key_0, Key_KeypadNumLock, \
* That switch statement actually runs the code associated with a macro when Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab, Key_Enter, Key_Y, Key_U, Key_I, Key_O, Key_P, Key_Equals, \
* a macro key is pressed. Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G, Key_H, Key_J, Key_K, Key_L, Key_Semicolon, Key_Quote, \
*/ Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape, ___, Key_N, Key_M, Key_Comma, Key_Period, Key_Slash, Key_Minus, \
Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift, Key_RightShift, Key_RightAlt, Key_Spacebar, Key_RightControl, \
enum { MACRO_VERSION_INFO, Key_KeymapNext_Momentary, Key_KeymapNext_Momentary \
MACRO_ANY )
};
/** The Model 01's key layouts are defined as 'keymaps'. By default, there are three
* keymaps: The standard QWERTY keymap, the "Function layer" keymap and the "Numpad"
* keymap.
*
* Each keymap is defined as a list using the 'KEYMAP_STACKED' macro, built
* of first the left hand's layout, followed by the right hand's layout.
*
* Keymaps typically consist mostly of `Key_` definitions. There are many, many keys
* defined as part of the USB HID Keyboard specification. You can find the names
* (if not yet the explanations) for all the standard `Key_` defintions offered by
* Kaleidoscope in these files:
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_keyboard.h
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_consumerctl.h
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_sysctl.h
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_keymaps.h
*
* Additional things that should be documented here include
* using ___ to let keypresses fall through to the previously active layer
* using XXX to mark a keyswitch as 'blocked' on this layer
* using ShiftToLayer() and LockLayer() keys to change the active keymap.
* keeping NUM and FN consistent and accessible on all layers
*
* The PROG key is special, since it is how you indicate to the board that you
* want to flash the firmware. However, it can be remapped to a regular key.
* When the keyboard boots, it first looks to see whether the PROG key is held
* down; if it is, it simply awaits further flashing instructions. If it is
* not, it continues loading the rest of the firmware and the keyboard
* functions normally, with whatever binding you have set to PROG. More detail
* here: https://community.keyboard.io/t/how-the-prog-key-gets-you-into-the-bootloader/506/8
*
* The "keymaps" data structure is a list of the keymaps compiled into the firmware.
* The order of keymaps in the list is important, as the ShiftToLayer(#) and LockLayer(#)
* macros switch to key layers based on this list.
*
*
* A key defined as 'ShiftToLayer(FUNCTION)' will switch to FUNCTION while held.
* Similarly, a key defined as 'LockLayer(NUMPAD)' will switch to NUMPAD when tapped.
*/
/**
* Layers are "0-indexed" -- That is the first one is layer 0. The second one is layer 1.
* The third one is layer 2.
* This 'enum' lets us use names like QWERTY, FUNCTION, and NUMPAD in place of
* the numbers 0, 1 and 2.
*
*/
enum { PRIMARY,
NUMPAD,
FUNCTION }; // layers
/**
* To change your keyboard's layout from QWERTY to DVORAK or COLEMAK, comment out the line
*
* #define PRIMARY_KEYMAP_QWERTY
*
* by changing it to
*
* // #define PRIMARY_KEYMAP_QWERTY
*
* Then uncomment the line corresponding to the layout you want to use.
*
*/
#define PRIMARY_KEYMAP_QWERTY
// #define PRIMARY_KEYMAP_DVORAK
// #define PRIMARY_KEYMAP_COLEMAK
// #define PRIMARY_KEYMAP_CUSTOM
/* This comment temporarily turns off astyle's indent enforcement
* so we can make the keymaps actually resemble the physical key layout better
*/
// *INDENT-OFF*
KEYMAPS( KEYMAPS(
QWERTY,
#if defined(PRIMARY_KEYMAP_QWERTY) GENERIC_FN2,
[PRIMARY] = KEYMAP_STACKED(___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext, Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab, Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G, Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape, Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift, ShiftToLayer(FUNCTION), NUMPAD
)
M(MACRO_ANY), // clang-format on
Key_6,
Key_7, static kaleidoscope::plugin::LEDSolidColor solidRed(60, 0, 0);
Key_8, static kaleidoscope::plugin::LEDSolidColor solidOrange(60, 20, 0);
Key_9, static kaleidoscope::plugin::LEDSolidColor solidYellow(40, 35, 0);
Key_0, static kaleidoscope::plugin::LEDSolidColor solidGreen(0, 100, 0);
LockLayer(NUMPAD), static kaleidoscope::plugin::LEDSolidColor solidBlue(0, 15, 100);
Key_Enter, static kaleidoscope::plugin::LEDSolidColor solidIndigo(0, 0, 100);
Key_Y, static kaleidoscope::plugin::LEDSolidColor solidViolet(70, 0, 60);
Key_U,
Key_I,
Key_O,
Key_P,
Key_Equals,
Key_H,
Key_J,
Key_K,
Key_L,
Key_Semicolon,
Key_Quote,
Key_RightAlt,
Key_N,
Key_M,
Key_Comma,
Key_Period,
Key_Slash,
Key_Minus,
Key_RightShift,
Key_LeftAlt,
Key_Spacebar,
Key_RightControl,
ShiftToLayer(FUNCTION)),
#elif defined(PRIMARY_KEYMAP_DVORAK)
[PRIMARY] = KEYMAP_STACKED(___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext, Key_Backtick, Key_Quote, Key_Comma, Key_Period, Key_P, Key_Y, Key_Tab, Key_PageUp, Key_A, Key_O, Key_E, Key_U, Key_I, Key_PageDown, Key_Semicolon, Key_Q, Key_J, Key_K, Key_X, Key_Escape, Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift, ShiftToLayer(FUNCTION),
M(MACRO_ANY),
Key_6,
Key_7,
Key_8,
Key_9,
Key_0,
LockLayer(NUMPAD),
Key_Enter,
Key_F,
Key_G,
Key_C,
Key_R,
Key_L,
Key_Slash,
Key_D,
Key_H,
Key_T,
Key_N,
Key_S,
Key_Minus,
Key_RightAlt,
Key_B,
Key_M,
Key_W,
Key_V,
Key_Z,
Key_Equals,
Key_RightShift,
Key_LeftAlt,
Key_Spacebar,
Key_RightControl,
ShiftToLayer(FUNCTION)),
#elif defined(PRIMARY_KEYMAP_COLEMAK)
[PRIMARY] = KEYMAP_STACKED(___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext, Key_Backtick, Key_Q, Key_W, Key_F, Key_P, Key_G, Key_Tab, Key_PageUp, Key_A, Key_R, Key_S, Key_T, Key_D, Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape, Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift, ShiftToLayer(FUNCTION),
M(MACRO_ANY),
Key_6,
Key_7,
Key_8,
Key_9,
Key_0,
LockLayer(NUMPAD),
Key_Enter,
Key_J,
Key_L,
Key_U,
Key_Y,
Key_Semicolon,
Key_Equals,
Key_H,
Key_N,
Key_E,
Key_I,
Key_O,
Key_Quote,
Key_RightAlt,
Key_K,
Key_M,
Key_Comma,
Key_Period,
Key_Slash,
Key_Minus,
Key_RightShift,
Key_LeftAlt,
Key_Spacebar,
Key_RightControl,
ShiftToLayer(FUNCTION)),
#elif defined(PRIMARY_KEYMAP_CUSTOM)
// Edit this keymap to make a custom layout
[PRIMARY] = KEYMAP_STACKED(___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext, Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab, Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G, Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape, Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift, ShiftToLayer(FUNCTION),
M(MACRO_ANY),
Key_6,
Key_7,
Key_8,
Key_9,
Key_0,
LockLayer(NUMPAD),
Key_Enter,
Key_Y,
Key_U,
Key_I,
Key_O,
Key_P,
Key_Equals,
Key_H,
Key_J,
Key_K,
Key_L,
Key_Semicolon,
Key_Quote,
Key_RightAlt,
Key_N,
Key_M,
Key_Comma,
Key_Period,
Key_Slash,
Key_Minus,
Key_RightShift,
Key_LeftAlt,
Key_Spacebar,
Key_RightControl,
ShiftToLayer(FUNCTION)),
#else
#error "No default keymap defined. You should make sure that you have a line like '#define PRIMARY_KEYMAP_QWERTY' in your sketch"
#endif
[NUMPAD] = KEYMAP_STACKED(___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
M(MACRO_VERSION_INFO),
___,
Key_7,
Key_8,
Key_9,
Key_KeypadSubtract,
___,
___,
___,
Key_4,
Key_5,
Key_6,
Key_KeypadAdd,
___,
___,
Key_1,
Key_2,
Key_3,
Key_Equals,
___,
___,
___,
Key_0,
Key_Period,
Key_KeypadMultiply,
Key_KeypadDivide,
Key_Enter,
___,
___,
___,
___,
___),
[FUNCTION] = KEYMAP_STACKED(___, Key_F1, Key_F2, Key_F3, Key_F4, Key_F5, Key_CapsLock, Key_Tab, ___, Key_mouseUp, ___, Key_mouseBtnR, Key_mouseWarpEnd, Key_mouseWarpNE, Key_Home, Key_mouseL, Key_mouseDn, Key_mouseR, Key_mouseBtnL, Key_mouseWarpNW, Key_End, Key_PrintScreen, Key_Insert, ___, Key_mouseBtnM, Key_mouseWarpSW, Key_mouseWarpSE, ___, Key_Delete, ___, ___, ___,
Consumer_ScanPreviousTrack,
Key_F6,
Key_F7,
Key_F8,
Key_F9,
Key_F10,
Key_F11,
Consumer_PlaySlashPause,
Consumer_ScanNextTrack,
Key_LeftCurlyBracket,
Key_RightCurlyBracket,
Key_LeftBracket,
Key_RightBracket,
Key_F12,
Key_LeftArrow,
Key_DownArrow,
Key_UpArrow,
Key_RightArrow,
___,
___,
Key_PcApplication,
Consumer_Mute,
Consumer_VolumeDecrement,
Consumer_VolumeIncrement,
___,
Key_Backslash,
Key_Pipe,
___,
___,
Key_Enter,
___,
___)) // KEYMAPS(
/* Re-enable astyle's indent enforcement */
// *INDENT-ON*
/** versionInfoMacro handles the 'firmware version info' macro
* When a key bound to the macro is pressed, this macro
* prints out the firmware build information as virtual keystrokes
*/
static void versionInfoMacro(uint8_t key_state) {
if (keyToggledOn(key_state)) {
Macros.type(PSTR("Keyboardio Model 01 - Kaleidoscope "));
Macros.type(PSTR(BUILD_INFORMATION));
}
}
/** anyKeyMacro is used to provide the functionality of the 'Any' key.
*
* When the 'any key' macro is toggled on, a random alphanumeric key is
* selected. While the key is held, the function generates a synthetic
* keypress event repeating that randomly selected key.
*
*/
static void anyKeyMacro(KeyEvent &event) {
if (keyToggledOn(event.state)) {
event.key.setKeyCode(Key_A.getKeyCode() + (uint8_t)(millis() % 36));
event.key.setFlags(0);
}
}
/** macroAction dispatches keymap events that are tied to a macro
to that macro. It takes two uint8_t parameters.
The first is the macro being called (the entry in the 'enum' earlier in this file).
The second is the state of the keyswitch. You can use the keyswitch state to figure out
if the key has just been toggled on, is currently pressed or if it's just been released.
The 'switch' statement should have a 'case' for each entry of the macro enum.
Each 'case' statement should call out to a function to handle the macro in question.
*/
const macro_t *macroAction(uint8_t macro_id, KeyEvent &event) { const macro_t *macroAction(uint8_t macro_id, KeyEvent &event) {
switch (macro_id) { if (macro_id == 1 && keyToggledOn(event.state)) {
Kaleidoscope.serialPort().print("Keyboard.IO keyboard driver v0.00");
case MACRO_VERSION_INFO: return MACRO(I(25),
versionInfoMacro(event.state); D(LeftShift),
break; T(M),
U(LeftShift),
case MACRO_ANY: T(O),
anyKeyMacro(event); T(D),
break; T(E),
T(L),
T(Spacebar),
W(100),
T(0),
T(1));
} }
return MACRO_NONE; return MACRO_NONE;
} }
// These 'solid' color effect definitions define a rainbow of
// LED color modes calibrated to draw 500mA or less on the
// Keyboardio Model 01.
static kaleidoscope::plugin::LEDSolidColor solidRed(160, 0, 0);
static kaleidoscope::plugin::LEDSolidColor solidOrange(140, 70, 0);
static kaleidoscope::plugin::LEDSolidColor solidYellow(130, 100, 0);
static kaleidoscope::plugin::LEDSolidColor solidGreen(0, 160, 0);
static kaleidoscope::plugin::LEDSolidColor solidBlue(0, 70, 130);
static kaleidoscope::plugin::LEDSolidColor solidIndigo(0, 0, 170);
static kaleidoscope::plugin::LEDSolidColor solidViolet(130, 0, 120);
/** toggleLedsOnSuspendResume toggles the LEDs off when the host goes to sleep,
* and turns them back on when it wakes up.
*/
void toggleLedsOnSuspendResume(kaleidoscope::plugin::HostPowerManagement::Event event) {
switch (event) {
case kaleidoscope::plugin::HostPowerManagement::Suspend:
LEDControl.disable();
break;
case kaleidoscope::plugin::HostPowerManagement::Resume:
LEDControl.enable();
break;
case kaleidoscope::plugin::HostPowerManagement::Sleep:
break;
}
}
/** hostPowerManagementEventHandler dispatches power management events (suspend,
* resume, and sleep) to other functions that perform action based on these
* events.
*/
void hostPowerManagementEventHandler(kaleidoscope::plugin::HostPowerManagement::Event event) {
toggleLedsOnSuspendResume(event);
}
/** This 'enum' is a list of all the magic combos used by the Model 01's
* firmware The names aren't particularly important. What is important is that
* each is unique.
*
* These are the names of your magic combos. They will be used by the
* `USE_MAGIC_COMBOS` call below.
*/
enum {
// Toggle between Boot (6-key rollover; for BIOSes and early boot) and NKRO
// mode.
COMBO_TOGGLE_NKRO_MODE,
// Enter test mode
COMBO_ENTER_TEST_MODE
};
/** Wrappers, to be used by MagicCombo. **/
/**
* This simply toggles the keyboard protocol via USBQuirks, and wraps it within
* a function with an unused argument, to match what MagicCombo expects.
*/
static void toggleKeyboardProtocol(uint8_t combo_index) {
USBQuirks.toggleKeyboardProtocol();
}
/** /**
* This enters the hardware test mode * This enters the hardware test mode
*/ */
@ -528,168 +112,35 @@ static void enterHardwareTestMode(uint8_t combo_index) {
/** Magic combo list, a list of key combo and action pairs the firmware should /** Magic combo list, a list of key combo and action pairs the firmware should
* recognise. * recognise.
*/ */
USE_MAGIC_COMBOS({.action = toggleKeyboardProtocol, USE_MAGIC_COMBOS({.action = enterHardwareTestMode,
// Left Fn + Esc + Shift
.keys = {R3C6, R2C6, R3C7}},
{.action = enterHardwareTestMode,
// Left Fn + Prog + LED // Left Fn + Prog + LED
.keys = {R3C6, R0C0, R0C6}}); .keys = {R3C6, R0C0, R0C6}});
// First, tell Kaleidoscope which plugins you want to use. KALEIDOSCOPE_INIT_PLUGINS(HardwareTestMode,
// The order can be important. For example, LED effects are LEDControl,
// added in the order they're listed here. LEDOff,
KALEIDOSCOPE_INIT_PLUGINS( solidRed,
// The EEPROMSettings & EEPROMKeymap plugins make it possible to have an solidOrange,
// editable keymap in EEPROM. solidYellow,
EEPROMSettings, solidGreen,
EEPROMKeymap, solidBlue,
solidIndigo,
// Focus allows bi-directional communication with the host, and is the solidViolet,
// interface through which the keymap in EEPROM can be edited. LEDBreatheEffect,
Focus, LEDRainbowEffect,
LEDChaseEffect,
// FocusSettingsCommand adds a few Focus commands, intended to aid in NumPad,
// changing some settings of the keyboard, such as the default layer (via the Macros,
// `settings.defaultLayer` command) MouseKeys,
FocusSettingsCommand, MagicCombo);
// FocusEEPROMCommand adds a set of Focus commands, which are very helpful in
// both debugging, and in backing up one's EEPROM contents.
FocusEEPROMCommand,
// The boot greeting effect pulses the LED button for 10 seconds after the
// keyboard is first connected
BootGreetingEffect,
// The hardware test mode, which can be invoked by tapping Prog, LED and the
// left Fn button at the same time.
HardwareTestMode,
// LEDControl provides support for other LED modes
LEDControl,
// We start with the LED effect that turns off all the LEDs.
LEDOff,
// The rainbow effect changes the color of all of the keyboard's keys at the same time
// running through all the colors of the rainbow.
LEDRainbowEffect,
// The rainbow wave effect lights up your keyboard with all the colors of a rainbow
// and slowly moves the rainbow across your keyboard
LEDRainbowWaveEffect,
// The chase effect follows the adventure of a blue pixel which chases a red pixel across
// your keyboard. Spoiler: the blue pixel never catches the red pixel
LEDChaseEffect,
// These static effects turn your keyboard's LEDs a variety of colors
solidRed,
solidOrange,
solidYellow,
solidGreen,
solidBlue,
solidIndigo,
solidViolet,
// The breathe effect slowly pulses all of the LEDs on your keyboard
LEDBreatheEffect,
// The LED Palette Theme plugin provides a shared palette for other plugins,
// like Colormap below
LEDPaletteTheme,
// The Colormap effect makes it possible to set up per-layer colormaps
ColormapEffect,
// The numpad plugin is responsible for lighting up the 'numpad' mode
// with a custom LED effect
NumPad,
// The macros plugin adds support for macros, DynamicMacros does the same for
// Chrysalis-editable, dynamic ones.
Macros,
DynamicMacros,
// The MouseKeys plugin lets you add keys to your keymap which move the mouse.
MouseKeys,
// Qukeys lets you add secondary actions to keys, such that they do their
// original action on tap, but another action (usually a modifier or a layer
// shift action) when held.
Qukeys,
// The HostPowerManagement plugin allows us to turn LEDs off when then host
// goes to sleep, and resume them when it wakes up.
HostPowerManagement,
// The MagicCombo plugin lets you use key combinations to trigger custom
// actions - a bit like Macros, but triggered by pressing multiple keys at the
// same time.
MagicCombo,
// The USBQuirks plugin lets you do some things with USB that we aren't
// comfortable - or able - to do automatically, but can be useful
// nevertheless. Such as toggling the key report protocol between Boot (used
// by BIOSes) and Report (NKRO).
USBQuirks,
// The FirmwareVersion plugin lets Chrysalis query the version of the firmware
// programmatically.
FirmwareVersion);
/** The 'setup' function is one of the two standard Arduino sketch functions.
* It's called when your keyboard first powers up. This is where you set up
* Kaleidoscope and any plugins.
*/
void setup() { void setup() {
// First, call Kaleidoscope's internal setup function
Kaleidoscope.setup(); Kaleidoscope.setup();
// While we hope to improve this in the future, the NumPad plugin NumPad.numPadLayer = NUMPAD_KEYMAP;
// needs to be explicitly told which keymap layer is your numpad layer
NumPad.numPadLayer = NUMPAD;
// We set the brightness of the rainbow effects to 150 (on a scale of 0-255)
// This draws more than 500mA, but looks much nicer than a dimmer effect
LEDRainbowEffect.brightness(150);
LEDRainbowWaveEffect.brightness(150);
// Set the action key the test mode should listen for to Left Fn
HardwareTestMode.setActionKey(R3C6);
// We want to make sure that the firmware starts with LED effects off
// This avoids over-taxing devices that don't have a lot of power to share
// with USB devices
LEDOff.activate(); LEDOff.activate();
// To make the keymap editable without flashing new firmware, we store
// additional layers in EEPROM. For now, we reserve space for five layers. If
// one wants to use these layers, just set the default layer to one in EEPROM,
// by using the `settings.defaultLayer` Focus command, or by using the
// `keymap.onlyCustom` command to use EEPROM layers only.
EEPROMKeymap.setup(5);
// We need to tell the Colormap plugin how many layers we want to have custom
// maps for. To make things simple, we set it to five layers, which is how
// many editable layers we have (see above).
ColormapEffect.max_layers(5);
// For Dynamic Macros, we need to reserve storage space for the editable
// macros.
DynamicMacros.reserve_storage(128);
// If there's a default layer set in EEPROM, we should set that as the default
// here.
Layer.move(EEPROMSettings.default_layer());
} }
/** loop is the second of the standard Arduino sketch functions.
* As you might expect, it runs in a loop, never exiting.
*
* For Kaleidoscope-based keyboard firmware, you usually just want to
* call Kaleidoscope.loop(); and not do anything custom here.
*/
void loop() { void loop() {
Kaleidoscope.loop(); Kaleidoscope.loop();

@ -3,4 +3,4 @@
"fqbn": "keyboardio:avr:model01", "fqbn": "keyboardio:avr:model01",
"port": "" "port": ""
} }
} }

@ -1,12 +1,18 @@
// -*- mode: c++ -*- // -*- mode: c++ -*-
// Copyright 2016-2022 Keyboardio, inc. <jesse@keyboard.io> // Copyright 2016 Keyboardio, inc. <jesse@keyboard.io>
// See "LICENSE" for license details // See "LICENSE" for license details
#ifndef BUILD_INFORMATION
#define BUILD_INFORMATION "locally built on " __DATE__ " at " __TIME__
#endif
/** /**
* These #include directives pull in the Kaleidoscope firmware core, * These #include directives pull in the Kaleidoscope firmware core,
* as well as the Kaleidoscope plugins we use in the Model 100's firmware * as well as the Kaleidoscope plugins we use in the Model 100's firmware
*/ */
// The Kaleidoscope core // The Kaleidoscope core
#include "Kaleidoscope.h" #include "Kaleidoscope.h"
@ -17,11 +23,8 @@
// Support for communicating with the host via a simple Serial protocol // Support for communicating with the host via a simple Serial protocol
#include "Kaleidoscope-FocusSerial.h" #include "Kaleidoscope-FocusSerial.h"
// Support for querying the firmware version via Focus
#include "Kaleidoscope-FirmwareVersion.h"
// Support for keys that move the mouse // Support for keys that move the mouse
// #include "Kaleidoscope-MouseKeys.h" #include "Kaleidoscope-MouseKeys.h"
// Support for macros // Support for macros
#include "Kaleidoscope-Macros.h" #include "Kaleidoscope-Macros.h"
@ -30,7 +33,7 @@
#include "Kaleidoscope-LEDControl.h" #include "Kaleidoscope-LEDControl.h"
// Support for "Numpad" mode, which is mostly just the Numpad specific LED mode // Support for "Numpad" mode, which is mostly just the Numpad specific LED mode
// #include "Kaleidoscope-NumPad.h" #include "Kaleidoscope-NumPad.h"
// Support for the "Boot greeting" effect, which pulses the 'LED' button for 10s // Support for the "Boot greeting" effect, which pulses the 'LED' button for 10s
// when the keyboard is connected to a computer (or that computer is powered on) // when the keyboard is connected to a computer (or that computer is powered on)
@ -60,12 +63,6 @@
// Support for an LED mode that lets one configure per-layer color maps // Support for an LED mode that lets one configure per-layer color maps
#include "Kaleidoscope-Colormap.h" #include "Kaleidoscope-Colormap.h"
// Support for turning the LEDs off after a certain amount of time
#include "Kaleidoscope-IdleLEDs.h"
// Support for setting and saving the default LED mode
#include "Kaleidoscope-DefaultLEDModeConfig.h"
// Support for Keyboardio's internal keyboard testing mode // Support for Keyboardio's internal keyboard testing mode
#include "Kaleidoscope-HardwareTestMode.h" #include "Kaleidoscope-HardwareTestMode.h"
@ -78,25 +75,6 @@
// Support for USB quirks, like changing the key state report protocol // Support for USB quirks, like changing the key state report protocol
#include "Kaleidoscope-USB-Quirks.h" #include "Kaleidoscope-USB-Quirks.h"
// Support for secondary actions on keys
#include "Kaleidoscope-Qukeys.h"
// Support for one-shot modifiers and layer keys
#include "Kaleidoscope-OneShot.h"
#include "Kaleidoscope-Escape-OneShot.h"
// Support for dynamic, Chrysalis-editable macros
#include "Kaleidoscope-DynamicMacros.h"
// Support for SpaceCadet keys
#include "Kaleidoscope-SpaceCadet.h"
// Support for editable layer names
#include "Kaleidoscope-LayerNames.h"
// Support for the GeminiPR Stenography protocol
// #include "Kaleidoscope-Steno.h"
/** This 'enum' is a list of all the macros used by the Model 100's firmware /** This 'enum' is a list of all the macros used by the Model 100's firmware
* The names aren't particularly important. What is important is that each * The names aren't particularly important. What is important is that each
* is unique. * is unique.
@ -127,10 +105,10 @@ enum {
* defined as part of the USB HID Keyboard specification. You can find the names * defined as part of the USB HID Keyboard specification. You can find the names
* (if not yet the explanations) for all the standard `Key_` defintions offered by * (if not yet the explanations) for all the standard `Key_` defintions offered by
* Kaleidoscope in these files: * Kaleidoscope in these files:
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs/keyboard.h * https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_keyboard.h
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs/consumerctl.h * https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_consumerctl.h
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs/sysctl.h * https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_sysctl.h
* https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs/keymaps.h * https://github.com/keyboardio/Kaleidoscope/blob/master/src/kaleidoscope/key_defs_keymaps.h
* *
* Additional things that should be documented here include * Additional things that should be documented here include
* using ___ to let keypresses fall through to the previously active layer * using ___ to let keypresses fall through to the previously active layer
@ -166,9 +144,8 @@ enum {
enum { enum {
PRIMARY, PRIMARY,
// NUMPAD, NUMPAD,
FUNCTION, FUNCTION,
ETC,
}; // layers }; // layers
@ -185,10 +162,10 @@ enum {
* *
*/ */
// #define PRIMARY_KEYMAP_QWERTY #define PRIMARY_KEYMAP_QWERTY
// #define PRIMARY_KEYMAP_DVORAK // #define PRIMARY_KEYMAP_DVORAK
// #define PRIMARY_KEYMAP_COLEMAK // #define PRIMARY_KEYMAP_COLEMAK
#define PRIMARY_KEYMAP_CUSTOM // #define PRIMARY_KEYMAP_CUSTOM
/* This comment temporarily turns off astyle's indent enforcement /* This comment temporarily turns off astyle's indent enforcement
@ -198,37 +175,82 @@ enum {
KEYMAPS( KEYMAPS(
#if defined (PRIMARY_KEYMAP_QWERTY)
[PRIMARY] = KEYMAP_STACKED [PRIMARY] = KEYMAP_STACKED
(___, ___, ___, ___, ___, ___, Key_LEDEffectNext, (___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext,
___, Key_Q, Key_W, Key_D, Key_F, Key_K, Key_Tab, Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab,
___, Key_A, Key_S, Key_E, Key_T, Key_G, Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G,
Key_Backtick, Key_Z, Key_X, Key_C, Key_V, Key_B, LCTRL(LALT(Key_LeftGui)), Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape,
GUI_T(Tab), ALT_T(Backspace), CTL_T(Escape), Key_LeftShift, Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift,
ShiftToLayer(FUNCTION), ShiftToLayer(FUNCTION),
M(MACRO_ANY), ___, Key_LeftArrow, Key_DownArrow, Key_UpArrow, Key_RightArrow, ___, M(MACRO_ANY), Key_6, Key_7, Key_8, Key_9, Key_0, LockLayer(NUMPAD),
Consumer_VolumeIncrement, Key_J, Key_U, Key_R, Key_L, Key_Semicolon, Key_Backslash, Key_Enter, Key_Y, Key_U, Key_I, Key_O, Key_P, Key_Equals,
Key_Y, Key_N, Key_I, Key_O, Key_H, Key_Quote, Key_H, Key_J, Key_K, Key_L, Key_Semicolon, Key_Quote,
Consumer_VolumeDecrement, Key_P, Key_M, Key_Comma, Key_Period, Key_Slash, ___, Key_RightAlt, Key_N, Key_M, Key_Comma, Key_Period, Key_Slash, Key_Minus,
Key_RightShift, ALT_T(Enter), Key_Spacebar, GUI_T(Tab), Key_RightShift, Key_LeftAlt, Key_Spacebar, Key_RightControl,
ShiftToLayer(FUNCTION)), ShiftToLayer(FUNCTION)),
[FUNCTION] = KEYMAP_STACKED #elif defined (PRIMARY_KEYMAP_DVORAK)
(___, Key_F1, Key_F2, Key_F3, Key_F4, Key_F5, ___,
___, LSHIFT(Key_1), LSHIFT(Key_2), LSHIFT(Key_LeftBracket), LSHIFT(Key_RightBracket), LSHIFT(Key_Backslash), ___,
LSHIFT(Key_7), LSHIFT(Key_3), LSHIFT(Key_4), LSHIFT(Key_9), LSHIFT(Key_0), Key_Backslash,
LSHIFT(Key_Backtick), LSHIFT(Key_5), LSHIFT(Key_6), Key_LeftBracket, Key_RightBracket, LSHIFT(Key_8), ___,
___, Key_Delete, ___, ___,
___,
___, Key_F6, Key_F7, Key_F8, Key_F9, Key_F10, Key_F11, [PRIMARY] = KEYMAP_STACKED
___, Key_Equals, Key_7, Key_8, Key_9, LSHIFT(Key_Equals), Key_F12, (___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext,
Key_Minus, Key_4, Key_5, Key_6, Key_Quote, ___, Key_Backtick, Key_Quote, Key_Comma, Key_Period, Key_P, Key_Y, Key_Tab,
___, LSHIFT(Key_Minus), Key_1, Key_2, Key_3, LSHIFT(Key_Quote), ___, Key_PageUp, Key_A, Key_O, Key_E, Key_U, Key_I,
___, ___, Key_Enter, Key_0, Key_PageDown, Key_Semicolon, Key_Q, Key_J, Key_K, Key_X, Key_Escape,
___), Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift,
ShiftToLayer(FUNCTION),
M(MACRO_ANY), Key_6, Key_7, Key_8, Key_9, Key_0, LockLayer(NUMPAD),
Key_Enter, Key_F, Key_G, Key_C, Key_R, Key_L, Key_Slash,
Key_D, Key_H, Key_T, Key_N, Key_S, Key_Minus,
Key_RightAlt, Key_B, Key_M, Key_W, Key_V, Key_Z, Key_Equals,
Key_RightShift, Key_LeftAlt, Key_Spacebar, Key_RightControl,
ShiftToLayer(FUNCTION)),
#elif defined (PRIMARY_KEYMAP_COLEMAK)
[ETC] = KEYMAP_STACKED [PRIMARY] = KEYMAP_STACKED
(___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext,
Key_Backtick, Key_Q, Key_W, Key_F, Key_P, Key_G, Key_Tab,
Key_PageUp, Key_A, Key_R, Key_S, Key_T, Key_D,
Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape,
Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift,
ShiftToLayer(FUNCTION),
M(MACRO_ANY), Key_6, Key_7, Key_8, Key_9, Key_0, LockLayer(NUMPAD),
Key_Enter, Key_J, Key_L, Key_U, Key_Y, Key_Semicolon, Key_Equals,
Key_H, Key_N, Key_E, Key_I, Key_O, Key_Quote,
Key_RightAlt, Key_K, Key_M, Key_Comma, Key_Period, Key_Slash, Key_Minus,
Key_RightShift, Key_LeftAlt, Key_Spacebar, Key_RightControl,
ShiftToLayer(FUNCTION)),
#elif defined (PRIMARY_KEYMAP_CUSTOM)
// Edit this keymap to make a custom layout
[PRIMARY] = KEYMAP_STACKED
(___, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext,
Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab,
Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G,
Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape,
Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift,
ShiftToLayer(FUNCTION),
M(MACRO_ANY), Key_6, Key_7, Key_8, Key_9, Key_0, LockLayer(NUMPAD),
Key_Enter, Key_Y, Key_U, Key_I, Key_O, Key_P, Key_Equals,
Key_H, Key_J, Key_K, Key_L, Key_Semicolon, Key_Quote,
Key_RightAlt, Key_N, Key_M, Key_Comma, Key_Period, Key_Slash, Key_Minus,
Key_RightShift, Key_LeftAlt, Key_Spacebar, Key_RightControl,
ShiftToLayer(FUNCTION)),
#else
#error "No default keymap defined. You should make sure that you have a line like '#define PRIMARY_KEYMAP_QWERTY' in your sketch"
#endif
[NUMPAD] = KEYMAP_STACKED
(___, ___, ___, ___, ___, ___, ___, (___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___, ___,
@ -236,13 +258,27 @@ KEYMAPS(
___, ___, ___, ___, ___, ___, ___, ___,
___, ___,
___, ___, ___, ___, ___, ___, ___, M(MACRO_VERSION_INFO), ___, Key_7, Key_8, Key_9, Key_KeypadSubtract, ___,
___, ___, Key_F7, Key_F8, Key_F9, Key_Home, ___, ___, ___, Key_4, Key_5, Key_6, Key_KeypadAdd, ___,
___, Key_F4, Key_F5, Key_F6, Key_End, ___, ___, Key_1, Key_2, Key_3, Key_Equals, ___,
___, ___, Key_F1, Key_F2, Key_F3, Key_Insert, ___, ___, ___, Key_0, Key_Period, Key_KeypadMultiply, Key_KeypadDivide, Key_Enter,
___, ___, ___, ___, ___, ___, ___, ___,
___) ___),
[FUNCTION] = KEYMAP_STACKED
(___, Key_F1, Key_F2, Key_F3, Key_F4, Key_F5, Key_CapsLock,
Key_Tab, ___, Key_mouseUp, ___, Key_mouseBtnR, Key_mouseWarpEnd, Key_mouseWarpNE,
Key_Home, Key_mouseL, Key_mouseDn, Key_mouseR, Key_mouseBtnL, Key_mouseWarpNW,
Key_End, Key_PrintScreen, Key_Insert, ___, Key_mouseBtnM, Key_mouseWarpSW, Key_mouseWarpSE,
___, Key_Delete, ___, ___,
___,
Consumer_ScanPreviousTrack, Key_F6, Key_F7, Key_F8, Key_F9, Key_F10, Key_F11,
Consumer_PlaySlashPause, Consumer_ScanNextTrack, Key_LeftCurlyBracket, Key_RightCurlyBracket, Key_LeftBracket, Key_RightBracket, Key_F12,
Key_LeftArrow, Key_DownArrow, Key_UpArrow, Key_RightArrow, ___, ___,
Key_PcApplication, Consumer_Mute, Consumer_VolumeDecrement, Consumer_VolumeIncrement, ___, Key_Backslash, Key_Pipe,
___, ___, Key_Enter, ___,
___)
) // KEYMAPS( ) // KEYMAPS(
/* Re-enable astyle's indent enforcement */ /* Re-enable astyle's indent enforcement */
@ -255,8 +291,8 @@ KEYMAPS(
static void versionInfoMacro(uint8_t key_state) { static void versionInfoMacro(uint8_t key_state) {
if (keyToggledOn(key_state)) { if (keyToggledOn(key_state)) {
Macros.type(PSTR("Keyboardio Model 100 - Firmware version ")); Macros.type(PSTR("Keyboardio Model 100 - Kaleidoscope "));
Macros.type(PSTR(KALEIDOSCOPE_FIRMWARE_VERSION)); Macros.type(PSTR(BUILD_INFORMATION));
} }
} }
@ -365,17 +401,6 @@ static void toggleKeyboardProtocol(uint8_t combo_index) {
USBQuirks.toggleKeyboardProtocol(); USBQuirks.toggleKeyboardProtocol();
} }
/**
* Toggles between using the built-in keymap, and the EEPROM-stored one.
*/
static void toggleKeymapSource(uint8_t combo_index) {
if (Layer.getKey == Layer.getKeyFromPROGMEM) {
Layer.getKey = EEPROMKeymap.getKey;
} else {
Layer.getKey = Layer.getKeyFromPROGMEM;
}
}
/** /**
* This enters the hardware test mode * This enters the hardware test mode
*/ */
@ -392,10 +417,7 @@ USE_MAGIC_COMBOS({.action = toggleKeyboardProtocol,
.keys = {R3C6, R2C6, R3C7}}, .keys = {R3C6, R2C6, R3C7}},
{.action = enterHardwareTestMode, {.action = enterHardwareTestMode,
// Left Fn + Prog + LED // Left Fn + Prog + LED
.keys = {R3C6, R0C0, R0C6}}, .keys = {R3C6, R0C0, R0C6}});
{.action = toggleKeymapSource,
// Left Fn + Prog + Shift
.keys = {R3C6, R0C0, R3C7}});
// First, tell Kaleidoscope which plugins you want to use. // First, tell Kaleidoscope which plugins you want to use.
// The order can be important. For example, LED effects are // The order can be important. For example, LED effects are
@ -406,12 +428,6 @@ KALEIDOSCOPE_INIT_PLUGINS(
EEPROMSettings, EEPROMSettings,
EEPROMKeymap, EEPROMKeymap,
// SpaceCadet can turn your shifts into parens on tap, while keeping them as
// Shifts when held. SpaceCadetConfig lets Chrysalis configure some aspects of
// the plugin.
// SpaceCadet,
// SpaceCadetConfig,
// Focus allows bi-directional communication with the host, and is the // Focus allows bi-directional communication with the host, and is the
// interface through which the keymap in EEPROM can be edited. // interface through which the keymap in EEPROM can be edited.
Focus, Focus,
@ -479,13 +495,13 @@ KALEIDOSCOPE_INIT_PLUGINS(
// The numpad plugin is responsible for lighting up the 'numpad' mode // The numpad plugin is responsible for lighting up the 'numpad' mode
// with a custom LED effect // with a custom LED effect
// NumPad, NumPad,
// The macros plugin adds support for macros // The macros plugin adds support for macros
Macros, Macros,
// The MouseKeys plugin lets you add keys to your keymap which move the mouse. // The MouseKeys plugin lets you add keys to your keymap which move the mouse.
// MouseKeys, MouseKeys,
// The HostPowerManagement plugin allows us to turn LEDs off when then host // The HostPowerManagement plugin allows us to turn LEDs off when then host
// goes to sleep, and resume them when it wakes up. // goes to sleep, and resume them when it wakes up.
@ -500,42 +516,7 @@ KALEIDOSCOPE_INIT_PLUGINS(
// comfortable - or able - to do automatically, but can be useful // comfortable - or able - to do automatically, but can be useful
// nevertheless. Such as toggling the key report protocol between Boot (used // nevertheless. Such as toggling the key report protocol between Boot (used
// by BIOSes) and Report (NKRO). // by BIOSes) and Report (NKRO).
USBQuirks, USBQuirks);
// The Qukeys plugin enables the "Secondary action" functionality in
// Chrysalis. Keys with secondary actions will have their primary action
// performed when tapped, but the secondary action when held.
Qukeys,
// Enables the "Sticky" behavior for modifiers, and the "Layer shift when
// held" functionality for layer keys.
OneShot,
EscapeOneShot,
EscapeOneShotConfig,
// Turns LEDs off after a configurable amount of idle time.
IdleLEDs,
PersistentIdleLEDs,
// Enables dynamic, Chrysalis-editable macros.
DynamicMacros,
// The FirmwareVersion plugin lets Chrysalis query the version of the firmware
// programmatically.
FirmwareVersion,
// The LayerNames plugin allows Chrysalis to display - and edit - custom layer
// names, to be shown instead of the default indexes.
LayerNames,
// Enables setting, saving (via Chrysalis), and restoring (on boot) the
// default LED mode.
DefaultLEDModeConfig
// Enables the GeminiPR Stenography protocol. Unused by default, but with the
// plugin enabled, it becomes configurable - and then usable - via Chrysalis.
//GeminiPR
);
/** The 'setup' function is one of the two standard Arduino sketch functions. /** The 'setup' function is one of the two standard Arduino sketch functions.
* It's called when your keyboard first powers up. This is where you set up * It's called when your keyboard first powers up. This is where you set up
@ -545,13 +526,9 @@ void setup() {
// First, call Kaleidoscope's internal setup function // First, call Kaleidoscope's internal setup function
Kaleidoscope.setup(); Kaleidoscope.setup();
// Set the hue of the boot greeting effect to something that will result in a
// nice green color.
BootGreetingEffect.hue = 85;
// While we hope to improve this in the future, the NumPad plugin // While we hope to improve this in the future, the NumPad plugin
// needs to be explicitly told which keymap layer is your numpad layer // needs to be explicitly told which keymap layer is your numpad layer
// NumPad.numPadLayer = NUMPAD; NumPad.numPadLayer = NUMPAD;
// We configure the AlphaSquare effect to use RED letters // We configure the AlphaSquare effect to use RED letters
AlphaSquare.color = CRGB(255, 0, 0); AlphaSquare.color = CRGB(255, 0, 0);
@ -569,41 +546,22 @@ void setup() {
// https://github.com/keyboardio/Kaleidoscope/blob/master/docs/plugins/LED-Stalker.md // https://github.com/keyboardio/Kaleidoscope/blob/master/docs/plugins/LED-Stalker.md
StalkerEffect.variant = STALKER(BlazingTrail); StalkerEffect.variant = STALKER(BlazingTrail);
// We want to make sure that the firmware starts with LED effects off
// This avoids over-taxing devices that don't have a lot of power to share
// with USB devices
LEDOff.activate();
// To make the keymap editable without flashing new firmware, we store // To make the keymap editable without flashing new firmware, we store
// additional layers in EEPROM. For now, we reserve space for eight layers. If // additional layers in EEPROM. For now, we reserve space for five layers. If
// one wants to use these layers, just set the default layer to one in EEPROM, // one wants to use these layers, just set the default layer to one in EEPROM,
// by using the `settings.defaultLayer` Focus command, or by using the // by using the `settings.defaultLayer` Focus command, or by using the
// `keymap.onlyCustom` command to use EEPROM layers only. // `keymap.onlyCustom` command to use EEPROM layers only.
EEPROMKeymap.setup(8); EEPROMKeymap.setup(5);
// We need to tell the Colormap plugin how many layers we want to have custom // We need to tell the Colormap plugin how many layers we want to have custom
// maps for. To make things simple, we set it to eight layers, which is how // maps for. To make things simple, we set it to five layers, which is how
// many editable layers we have (see above). // many editable layers we have (see above).
ColormapEffect.max_layers(8); ColormapEffect.max_layers(5);
// For Dynamic Macros, we need to reserve storage space for the editable
// macros. A kilobyte is a reasonable default.
DynamicMacros.reserve_storage(1024);
// If there's a default layer set in EEPROM, we should set that as the default
// here.
Layer.move(EEPROMSettings.default_layer());
// To avoid any surprises, SpaceCadet is turned off by default. However, it
// can be permanently enabled via Chrysalis, so we should only disable it if
// no configuration exists.
// SpaceCadetConfig.disableSpaceCadetIfUnconfigured();
// SpaceCadet.disable();
// Editable layer names are stored in EEPROM too, and we reserve 16 bytes per
// layer for them. We need one extra byte per layer for bookkeeping, so we
// reserve 17 / layer in total.
LayerNames.reserve_storage(17 * 8);
// Unless configured otherwise with Chrysalis, we want to make sure that the
// firmware starts with LED effects off. This avoids over-taxing devices that
// don't have a lot of power to share with USB devices
DefaultLEDModeConfig.activateLEDModeIfUnconfigured(&LEDOff);
} }
/** loop is the second of the standard Arduino sketch functions. /** loop is the second of the standard Arduino sketch functions.

@ -40,20 +40,11 @@ KEYMAPS(
) )
// clang-format on // clang-format on
// Override CycleTimeReport's reporting function:
void kaleidoscope::plugin::CycleTimeReport::report(uint16_t mean_cycle_time) {
Serial.print(F("average loop time = "));
Serial.println(mean_cycle_time, DEC);
}
KALEIDOSCOPE_INIT_PLUGINS(CycleTimeReport); KALEIDOSCOPE_INIT_PLUGINS(CycleTimeReport);
void setup() { void setup() {
Kaleidoscope.serialPort().begin(9600); Kaleidoscope.serialPort().begin(9600);
Kaleidoscope.setup(); Kaleidoscope.setup();
// Change the report interval to 2 seconds:
CycleTimeReport.setReportInterval(2000);
} }
void loop() { void loop() {

@ -44,13 +44,13 @@ class FocusTestCommand : public Plugin {
public: public:
FocusTestCommand() {} FocusTestCommand() {}
EventHandlerResult onFocusEvent(const char *input) { EventHandlerResult onFocusEvent(const char *command) {
const char *cmd = PSTR("test"); const char *cmd = PSTR("test");
if (::Focus.inputMatchesHelp(input)) if (::Focus.handleHelp(command, cmd))
return ::Focus.printHelp(cmd); return EventHandlerResult::OK;
if (::Focus.inputMatchesCommand(input, cmd)) { if (strcmp_P(command, cmd) == 0) {
::Focus.send(F("ok!")); ::Focus.send(F("ok!"));
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
@ -63,9 +63,8 @@ class FocusHelpCommand : public Plugin {
public: public:
FocusHelpCommand() {} FocusHelpCommand() {}
EventHandlerResult onFocusEvent(const char *input) { EventHandlerResult onFocusEvent(const char *command) {
if (::Focus.inputMatchesHelp(input)) ::Focus.handleHelp(command, PSTR("help"));
return ::Focus.printHelp(PSTR("help"));
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }

@ -17,7 +17,7 @@
#include <Kaleidoscope.h> #include <Kaleidoscope.h>
#include <Kaleidoscope-Leader.h> #include <Kaleidoscope-Leader.h>
#include <Kaleidoscope-MacroSupport.h> #include <Kaleidoscope-Macros.h>
#include <Kaleidoscope-Ranges.h> #include <Kaleidoscope-Ranges.h>
#include "kaleidoscope/KeyEventTracker.h" #include "kaleidoscope/KeyEventTracker.h"
@ -176,7 +176,7 @@ void leaderTestPrefix(uint8_t seq_index) {
uint8_t prefix_arg = LeaderPrefix.arg(); uint8_t prefix_arg = LeaderPrefix.arg();
// Use a Macros helper function to tap the `X` key repeatedly. // Use a Macros helper function to tap the `X` key repeatedly.
while (prefix_arg-- > 0) while (prefix_arg-- > 0)
MacroSupport.tap(Key_X); Macros.tap(Key_X);
} }
static const kaleidoscope::plugin::Leader::dictionary_t leader_dictionary[] PROGMEM = static const kaleidoscope::plugin::Leader::dictionary_t leader_dictionary[] PROGMEM =

@ -1,69 +0,0 @@
// -*- mode: c++ -*-
/* This example demonstrates the Model 01 / Model 100 butterfly logo key as a
* tmux prefix key. When the key is held, Ctrl-B is pressed prior to the key
* you pressed.
*
* This example also demonstrates the purpose of using an entire layer for this
* plugin: the h/j/k/l keys in the TMUX layer are swapped for arrow keys to
* make switching between panes easier.
*/
#include <Kaleidoscope.h>
#include <Kaleidoscope-PrefixLayer.h>
enum {
PRIMARY,
TMUX,
}; // layers
/* Used in setup() below. */
static const kaleidoscope::plugin::PrefixLayer::Entry prefix_layers[] PROGMEM = {
kaleidoscope::plugin::PrefixLayer::Entry(TMUX, LCTRL(Key_B)),
};
// clang-format off
KEYMAPS(
[PRIMARY] = KEYMAP_STACKED
(XXX, Key_1, Key_2, Key_3, Key_4, Key_5, XXX,
Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab,
Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G,
Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape,
Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift,
XXX,
XXX, Key_6, Key_7, Key_8, Key_9, Key_0, XXX,
Key_Enter, Key_Y, Key_U, Key_I, Key_O, Key_P, Key_Equals,
Key_H, Key_J, Key_K, Key_L, Key_Semicolon, Key_Quote,
ShiftToLayer(TMUX), Key_N, Key_M, Key_Comma, Key_Period, Key_Slash, Key_Minus,
Key_RightShift, Key_RightAlt, Key_Spacebar, Key_RightControl,
XXX),
[TMUX] = KEYMAP_STACKED
(___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___,
___,
___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___, ___, ___, ___,
Key_LeftArrow, Key_DownArrow, Key_UpArrow, Key_RightArrow, ___, ___,
___, ___, ___, ___, ___, ___, ___,
___, ___, ___, ___,
___),
)
// clang-format on
KALEIDOSCOPE_INIT_PLUGINS(PrefixLayer);
void setup() {
Kaleidoscope.setup();
/* Configure the previously-defined prefix layers. */
PrefixLayer.setPrefixLayers(prefix_layers);
}
void loop() {
Kaleidoscope.loop();
}

@ -1,6 +0,0 @@
{
"cpu": {
"fqbn": "keyboardio:avr:model01",
"port": ""
}
}

@ -59,7 +59,7 @@ void setup() {
SPACECADET_MAP_END, SPACECADET_MAP_END,
}; };
//Set the map. //Set the map.
SpaceCadet.setMap(spacecadetmap); SpaceCadet.map = spacecadetmap;
} }
void loop() { void loop() {

@ -1,6 +1,6 @@
/* -*- mode: c++ -*- /* -*- mode: c++ -*-
* Kaleidoscope-EEPROM-Colormap -- Per-layer colormap effect * Kaleidoscope-EEPROM-Colormap -- Per-layer colormap effect
* Copyright (C) 2017-2022 Keyboard.io, Inc * Copyright (C) 2017, 2018 Keyboard.io, Inc
* *
* This program is free software: you can redistribute it and/or modify it under it under * This program is free software: you can redistribute it and/or modify it under it under
* the terms of the GNU General Public License as published by the Free Software * the terms of the GNU General Public License as published by the Free Software
@ -17,7 +17,6 @@
#include <Kaleidoscope.h> #include <Kaleidoscope.h>
#include <Kaleidoscope-EEPROM-Settings.h> #include <Kaleidoscope-EEPROM-Settings.h>
#include <Kaleidoscope-EEPROM-Keymap.h>
#include <Kaleidoscope-Colormap.h> #include <Kaleidoscope-Colormap.h>
#include <Kaleidoscope-FocusSerial.h> #include <Kaleidoscope-FocusSerial.h>
#include <Kaleidoscope-LED-Palette-Theme.h> #include <Kaleidoscope-LED-Palette-Theme.h>
@ -26,10 +25,10 @@
// clang-format off // clang-format off
KEYMAPS( KEYMAPS(
[0] = KEYMAP_STACKED [0] = KEYMAP_STACKED
(Key_NoKey, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext, (Key_LEDEffectNext, Key_1, Key_2, Key_3, Key_4, Key_5, Key_LEDEffectNext,
Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab, Key_Backtick, Key_Q, Key_W, Key_E, Key_R, Key_T, Key_Tab,
Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G, Key_PageUp, Key_A, Key_S, Key_D, Key_F, Key_G,
Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape, Key_PageDown, Key_Z, Key_X, Key_C, Key_V, Key_B, Key_Escape,
Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift, Key_LeftControl, Key_Backspace, Key_LeftGui, Key_LeftShift,
Key_NoKey, Key_NoKey,
@ -43,90 +42,17 @@ KEYMAPS(
Key_NoKey), Key_NoKey),
) )
// Colors names of the EGA palette, for convenient use in colormaps. Should
// match the palette definition below. Optional, one can just use the indexes
// directly, too.
enum {
BLACK,
BLUE,
GREEN,
CYAN,
RED,
MAGENTA,
BROWN,
LIGHT_GRAY,
DARK_GRAY,
BRIGHT_BLUE,
BRIGHT_GREEN,
BRIGHT_CYAN,
BRIGHT_RED,
BRIGHT_MAGENTA,
YELLOW,
WHITE
};
// Define an EGA palette. Conveniently, that's exactly 16 colors, just like the
// limit of LEDPaletteTheme.
PALETTE(
CRGB(0x00, 0x00, 0x00), // [0x0] black
CRGB(0x00, 0x00, 0xaa), // [0x1] blue
CRGB(0x00, 0xaa, 0x00), // [0x2] green
CRGB(0x00, 0xaa, 0xaa), // [0x3] cyan
CRGB(0xaa, 0x00, 0x00), // [0x4] red
CRGB(0xaa, 0x00, 0xaa), // [0x5] magenta
CRGB(0xaa, 0x55, 0x00), // [0x6] brown
CRGB(0xaa, 0xaa, 0xaa), // [0x7] light gray
CRGB(0x55, 0x55, 0x55), // [0x8] dark gray
CRGB(0x55, 0x55, 0xff), // [0x9] bright blue
CRGB(0x55, 0xff, 0x55), // [0xa] bright green
CRGB(0x55, 0xff, 0xff), // [0xb] bright cyan
CRGB(0xff, 0x55, 0x55), // [0xc] bright red
CRGB(0xff, 0x55, 0xff), // [0xd] bright magenta
CRGB(0xff, 0xff, 0x55), // [0xe] yellow
CRGB(0xff, 0xff, 0xff) // [0xf] white
)
COLORMAPS(
[0] = COLORMAP_STACKED
(BLACK, GREEN, GREEN, GREEN, GREEN, GREEN, BLUE,
MAGENTA, CYAN, CYAN, CYAN, CYAN, CYAN, RED,
BROWN, CYAN, CYAN, CYAN, CYAN, CYAN,
BROWN, CYAN, CYAN, CYAN, CYAN, CYAN, RED,
LIGHT_GRAY, RED, LIGHT_GRAY, LIGHT_GRAY,
BLACK,
BLACK, BRIGHT_GREEN, BRIGHT_GREEN, BRIGHT_GREEN, BRIGHT_GREEN, BRIGHT_GREEN, BLACK,
BRIGHT_RED, BRIGHT_CYAN, BRIGHT_CYAN, BRIGHT_CYAN, BRIGHT_CYAN, BRIGHT_CYAN, YELLOW,
BRIGHT_CYAN, BRIGHT_CYAN, BRIGHT_CYAN, BRIGHT_CYAN, BRIGHT_RED, BRIGHT_RED,
BLACK, BRIGHT_CYAN, BRIGHT_CYAN, BRIGHT_RED, BRIGHT_RED, BRIGHT_RED, BRIGHT_RED,
DARK_GRAY, BRIGHT_RED, DARK_GRAY, DARK_GRAY,
BLACK)
)
// clang-format on // clang-format on
KALEIDOSCOPE_INIT_PLUGINS(EEPROMSettings, KALEIDOSCOPE_INIT_PLUGINS(EEPROMSettings,
EEPROMKeymap,
LEDControl,
LEDPaletteTheme, LEDPaletteTheme,
LEDOff,
ColormapEffect, ColormapEffect,
DefaultColormap, Focus);
Focus,
FocusEEPROMCommand,
FocusSettingsCommand);
void setup() { void setup() {
Kaleidoscope.setup(); Kaleidoscope.setup();
EEPROMKeymap.setup(1);
ColormapEffect.max_layers(1); ColormapEffect.max_layers(1);
ColormapEffect.activate(); ColormapEffect.activate();
DefaultColormap.setup();
} }
void loop() { void loop() {

@ -27,7 +27,7 @@ class TestLEDMode : public kaleidoscope::plugin::LEDMode {
public: public:
TestLEDMode() {} TestLEDMode() {}
kaleidoscope::EventHandlerResult onFocusEvent(const char *input); kaleidoscope::EventHandlerResult onFocusEvent(const char *command);
protected: protected:
void setup() final; void setup() final;
@ -48,8 +48,8 @@ void TestLEDMode::update(void) {
} }
kaleidoscope::EventHandlerResult kaleidoscope::EventHandlerResult
TestLEDMode::onFocusEvent(const char *input) { TestLEDMode::onFocusEvent(const char *command) {
return LEDPaletteTheme.themeFocusEvent(input, PSTR("testLedMode.map"), map_base_, 1); return LEDPaletteTheme.themeFocusEvent(command, PSTR("testLedMode.map"), map_base_, 1);
} }
} // namespace example } // namespace example

@ -29,6 +29,25 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
// =============================================================================
// AutoShift static class variables
// Configuration settings that can be saved to persistent storage.
AutoShift::Settings AutoShift::settings_ = {
.enabled = true,
.timeout = 175,
.enabled_categories = AutoShift::Categories::printableKeys(),
};
// The event tracker ensures that the `onKeyswitchEvent()` handler will follow
// the rules in order to avoid interference with other plugins and prevent
// processing the same event more than once.
KeyEventTracker AutoShift::event_tracker_;
// If there's a delayed keypress from AutoShift, this stored event will contain
// a valid `KeyAddr`. The default constructor produces an event addr of
// `KeyAddr::none()`, so the plugin will start in an inactive state.
KeyEvent pending_event_;
// ============================================================================= // =============================================================================
// AutoShift functions // AutoShift functions

@ -134,17 +134,17 @@ class AutoShift : public Plugin {
// Configuration functions // Configuration functions
/// Returns `true` if AutoShift is active, `false` otherwise /// Returns `true` if AutoShift is active, `false` otherwise
bool enabled() { static bool enabled() {
return settings_.enabled; return settings_.enabled;
} }
/// Activates the AutoShift plugin (held keys will trigger auto-shift) /// Activates the AutoShift plugin (held keys will trigger auto-shift)
void enable() { static void enable() {
settings_.enabled = true; settings_.enabled = true;
} }
/// Deactivates the AutoShift plugin (held keys will not trigger auto-shift) /// Deactivates the AutoShift plugin (held keys will not trigger auto-shift)
void disable(); static void disable();
/// Turns AutoShift on if it's off, and vice versa /// Turns AutoShift on if it's off, and vice versa
void toggle() { static void toggle() {
if (settings_.enabled) { if (settings_.enabled) {
disable(); disable();
} else { } else {
@ -153,16 +153,16 @@ class AutoShift : public Plugin {
} }
/// Returns the hold time required to trigger auto-shift (in ms) /// Returns the hold time required to trigger auto-shift (in ms)
uint16_t timeout() { static uint16_t timeout() {
return settings_.timeout; return settings_.timeout;
} }
/// Sets the hold time required to trigger auto-shift (in ms) /// Sets the hold time required to trigger auto-shift (in ms)
void setTimeout(uint16_t new_timeout) { static void setTimeout(uint16_t new_timeout) {
settings_.timeout = new_timeout; settings_.timeout = new_timeout;
} }
/// Returns the set of categories currently eligible for auto-shift /// Returns the set of categories currently eligible for auto-shift
Categories enabledCategories() { static Categories enabledCategories() {
return settings_.enabled_categories; return settings_.enabled_categories;
} }
/// Adds `category` to the set eligible for auto-shift /// Adds `category` to the set eligible for auto-shift
@ -175,19 +175,19 @@ class AutoShift : public Plugin {
/// - `AutoShift::Categories::functionKeys()` /// - `AutoShift::Categories::functionKeys()`
/// - `AutoShift::Categories::printableKeys()` /// - `AutoShift::Categories::printableKeys()`
/// - `AutoShift::Categories::allKeys()` /// - `AutoShift::Categories::allKeys()`
void enable(Categories category) { static void enable(Categories category) {
settings_.enabled_categories.add(category); settings_.enabled_categories.add(category);
} }
/// Removes a `Key` category from the set eligible for auto-shift /// Removes a `Key` category from the set eligible for auto-shift
void disable(Categories category) { static void disable(Categories category) {
settings_.enabled_categories.remove(category); settings_.enabled_categories.remove(category);
} }
/// Replaces the list of `Key` categories eligible for auto-shift /// Replaces the list of `Key` categories eligible for auto-shift
void setEnabled(Categories categories) { static void setEnabled(Categories categories) {
settings_.enabled_categories = categories; settings_.enabled_categories = categories;
} }
/// Returns `true` if the given category is eligible for auto-shift /// Returns `true` if the given category is eligible for auto-shift
bool isEnabled(Categories category) { static bool isEnabled(Categories category) {
return settings_.enabled_categories.contains(category); return settings_.enabled_categories.contains(category);
} }
@ -225,7 +225,7 @@ class AutoShift : public Plugin {
/// ///
/// This function can be overridden by the user sketch to configure which keys /// This function can be overridden by the user sketch to configure which keys
/// can trigger auto-shift. /// can trigger auto-shift.
bool isAutoShiftable(Key key); static bool isAutoShiftable(Key key);
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Event handlers // Event handlers
@ -237,19 +237,19 @@ class AutoShift : public Plugin {
/// A container for AutoShift configuration settings /// A container for AutoShift configuration settings
struct Settings { struct Settings {
/// The overall state of the plugin (on/off) /// The overall state of the plugin (on/off)
bool enabled = true; bool enabled;
/// The length of time (ms) a key must be held to trigger auto-shift /// The length of time (ms) a key must be held to trigger auto-shift
uint16_t timeout = 175; uint16_t timeout;
/// The set of `Key` categories eligible to be auto-shifted /// The set of `Key` categories eligible to be auto-shifted
Categories enabled_categories = AutoShift::Categories::printableKeys(); Categories enabled_categories;
}; };
Settings settings_; static Settings settings_;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Key event queue state variables // Key event queue state variables
// A device for processing only new events // A device for processing only new events
KeyEventTracker event_tracker_; static KeyEventTracker event_tracker_;
// The maximum number of events in the queue at a time. // The maximum number of events in the queue at a time.
static constexpr uint8_t queue_capacity_{4}; static constexpr uint8_t queue_capacity_{4};
@ -257,17 +257,12 @@ class AutoShift : public Plugin {
// The event queue stores a series of press and release events. // The event queue stores a series of press and release events.
KeyAddrEventQueue<queue_capacity_> queue_; KeyAddrEventQueue<queue_capacity_> queue_;
// If there's a delayed keypress from AutoShift, this stored event will
// contain a valid `KeyAddr`. The default constructor produces an event addr
// of `KeyAddr::none()`, so the plugin will start in an inactive state.
KeyEvent pending_event_;
void flushQueue(); void flushQueue();
void flushEvent(bool is_long_press = false); void flushEvent(bool is_long_press = false);
bool checkForRelease() const; bool checkForRelease() const;
/// The default function for `isAutoShiftable()` /// The default function for `isAutoShiftable()`
bool enabledForKey(Key key); static bool enabledForKey(Key key);
}; };
// ============================================================================= // =============================================================================
@ -275,11 +270,11 @@ class AutoShift : public Plugin {
class AutoShiftConfig : public Plugin { class AutoShiftConfig : public Plugin {
public: public:
EventHandlerResult onSetup(); EventHandlerResult onSetup();
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
private: private:
// The base address in persistent storage for configuration data // The base address in persistent storage for configuration data
uint16_t settings_base_; static uint16_t settings_base_;
}; };
} // namespace plugin } // namespace plugin

@ -17,10 +17,10 @@
#include "kaleidoscope/plugin/AutoShift.h" // IWYU pragma: associated #include "kaleidoscope/plugin/AutoShift.h" // IWYU pragma: associated
#include <Arduino.h> // for PSTR #include <Arduino.h> // for PSTR, strcmp_P, strncmp_P
#include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings #include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint8_t, uint16_t #include <stdint.h> // for uint16_t, uint8_t
#include "kaleidoscope/Runtime.h" // for Runtime, Runtime_ #include "kaleidoscope/Runtime.h" // for Runtime, Runtime_
#include "kaleidoscope/device/device.h" // for VirtualProps::Storage, Base<>::Storage #include "kaleidoscope/device/device.h" // for VirtualProps::Storage, Base<>::Storage
@ -32,40 +32,42 @@ namespace plugin {
// ============================================================================= // =============================================================================
// AutoShift configurator // AutoShift configurator
uint16_t AutoShiftConfig::settings_base_;
EventHandlerResult AutoShiftConfig::onSetup() { EventHandlerResult AutoShiftConfig::onSetup() {
settings_base_ = ::EEPROMSettings.requestSlice(sizeof(AutoShift::Settings)); settings_base_ = ::EEPROMSettings.requestSlice(sizeof(AutoShift::settings_));
if (Runtime.storage().isSliceUninitialized( if (Runtime.storage().isSliceUninitialized(
settings_base_, settings_base_,
sizeof(AutoShift::Settings))) { sizeof(AutoShift::settings_))) {
// If our slice is uninitialized, set sensible defaults. // If our slice is uninitialized, set sensible defaults.
Runtime.storage().put(settings_base_, ::AutoShift.settings_); Runtime.storage().put(settings_base_, AutoShift::settings_);
Runtime.storage().commit(); Runtime.storage().commit();
} }
Runtime.storage().get(settings_base_, ::AutoShift.settings_); Runtime.storage().get(settings_base_, AutoShift::settings_);
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
EventHandlerResult AutoShiftConfig::onFocusEvent(const char *input) { EventHandlerResult AutoShiftConfig::onFocusEvent(const char *command) {
enum { enum {
ENABLED, ENABLED,
TIMEOUT, TIMEOUT,
CATEGORIES, CATEGORIES,
} subCommand; } subCommand;
const char *cmd_enabled = PSTR("autoshift.enabled"); if (::Focus.handleHelp(command, PSTR("autoshift.enabled\n"
const char *cmd_timeout = PSTR("autoshift.timeout"); "autoshift.timeout\n"
const char *cmd_categories = PSTR("autoshift.categories"); "autoshift.categories")))
return EventHandlerResult::OK;
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd_enabled, cmd_timeout, cmd_categories);
if (::Focus.inputMatchesCommand(input, cmd_enabled)) if (strncmp_P(command, PSTR("autoshift."), 10) != 0)
return EventHandlerResult::OK;
if (strcmp_P(command + 10, PSTR("enabled")) == 0)
subCommand = ENABLED; subCommand = ENABLED;
else if (::Focus.inputMatchesCommand(input, cmd_timeout)) else if (strcmp_P(command + 10, PSTR("timeout")) == 0)
subCommand = TIMEOUT; subCommand = TIMEOUT;
else if (::Focus.inputMatchesCommand(input, cmd_categories)) else if (strcmp_P(command + 10, PSTR("categories")) == 0)
subCommand = CATEGORIES; subCommand = CATEGORIES;
else else
return EventHandlerResult::OK; return EventHandlerResult::OK;
@ -110,7 +112,7 @@ EventHandlerResult AutoShiftConfig::onFocusEvent(const char *input) {
break; break;
} }
Runtime.storage().put(settings_base_, ::AutoShift.settings_); Runtime.storage().put(settings_base_, AutoShift::settings_);
Runtime.storage().commit(); Runtime.storage().commit();
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }

@ -35,6 +35,14 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
// =============================================================================
// CharShift class variables
CharShift::KeyPair const *CharShift::progmem_keypairs_{nullptr};
uint8_t CharShift::num_keypairs_{0};
bool CharShift::reverse_shift_state_{false};
// ============================================================================= // =============================================================================
// Event handlers // Event handlers

@ -77,42 +77,42 @@ class CharShift : public Plugin {
/// Generally, it will be called via the `KEYPAIRS()` preprocessor macro, not /// Generally, it will be called via the `KEYPAIRS()` preprocessor macro, not
/// directly by user code. /// directly by user code.
template<uint8_t _num_keypairs> template<uint8_t _num_keypairs>
void setProgmemKeyPairs(KeyPair const (&keypairs)[_num_keypairs]) { static void setProgmemKeyPairs(KeyPair const (&keypairs)[_num_keypairs]) {
progmem_keypairs_ = keypairs; progmem_keypairs_ = keypairs;
num_keypairs_ = _num_keypairs; num_keypairs_ = _num_keypairs;
} }
private: private:
// A pointer to an array of `KeyPair` objects in PROGMEM // A pointer to an array of `KeyPair` objects in PROGMEM
KeyPair const *progmem_keypairs_ = nullptr; static KeyPair const *progmem_keypairs_;
// The size of the PROGMEM array of `KeyPair` objects // The size of the PROGMEM array of `KeyPair` objects
uint8_t num_keypairs_ = 0; static uint8_t num_keypairs_;
// If a `shift` key needs to be suppressed in `beforeReportingState()` // If a `shift` key needs to be suppressed in `beforeReportingState()`
bool reverse_shift_state_ = false; static bool reverse_shift_state_;
/// Test for keys that should be handled by CharShift /// Test for keys that should be handled by CharShift
bool isCharShiftKey(Key key); static bool isCharShiftKey(Key key);
/// Look up the `KeyPair` specified by the given keymap entry /// Look up the `KeyPair` specified by the given keymap entry
KeyPair decodeCharShiftKey(Key key); static KeyPair decodeCharShiftKey(Key key);
/// Get the total number of KeyPairs defined /// Get the total number of KeyPairs defined
/// ///
/// This function can be overridden in order to store the `KeyPair` array in /// This function can be overridden in order to store the `KeyPair` array in
/// EEPROM instead of PROGMEM. /// EEPROM instead of PROGMEM.
uint8_t numKeyPairs(); static uint8_t numKeyPairs();
/// Get the `KeyPair` at the specified index from the defined `KeyPair` array /// Get the `KeyPair` at the specified index from the defined `KeyPair` array
/// ///
/// This function can be overridden in order to store the `KeyPair` array in /// This function can be overridden in order to store the `KeyPair` array in
/// EEPROM instead of PROGMEM. /// EEPROM instead of PROGMEM.
KeyPair readKeyPair(uint8_t n); static KeyPair readKeyPair(uint8_t n);
// Default for `keypairsCount()`: size of the PROGMEM array // Default for `keypairsCount()`: size of the PROGMEM array
uint8_t numProgmemKeyPairs(); static uint8_t numProgmemKeyPairs();
// Default for `readKeypair(i)`: fetch the value from PROGMEM // Default for `readKeypair(i)`: fetch the value from PROGMEM
KeyPair readKeyPairFromProgmem(uint8_t n); static KeyPair readKeyPairFromProgmem(uint8_t n);
}; };
} // namespace plugin } // namespace plugin

@ -11,60 +11,30 @@ plugin, which also provides palette editing capabilities.
[plugin:focusserial]: Kaleidoscope-FocusSerial.md [plugin:focusserial]: Kaleidoscope-FocusSerial.md
[plugin:l-p-t]: Kaleidoscope-LED-Palette-Theme.md [plugin:l-p-t]: Kaleidoscope-LED-Palette-Theme.md
It is also possible to set up a default palette and colormap, using the
`DefaultColormap` plugin, also provided by this package. See below for its
documentation.
## Using the extension ## Using the extension
To use the extension, include the header, tell it the number of layers you have, To use the extension, include the header, tell it the number of layers you have,
register the `Focus` hooks, and it will do the rest. We'll also set up a default register the `Focus` hooks, and it will do the rest.
for both the palette, and the colormap.
```c++ ```c++
#include <Kaleidoscope.h> #include <Kaleidoscope.h>
#include <Kaleidoscope-EEPROM-Settings.h> #include <Kaleidoscope-EEPROM-Settings.h>
#include <Kaleidoscope-LEDControl.h>
#include <Kaleidoscope-Colormap.h> #include <Kaleidoscope-Colormap.h>
#include <Kaleidoscope-FocusSerial.h> #include <Kaleidoscope-FocusSerial.h>
#include <Kaleidoscope-LED-Palette-Theme.h> #include <Kaleidoscope-LED-Palette-Theme.h>
KALEIDOSCOPE_INIT_PLUGINS(EEPROMSettings, KALEIDOSCOPE_INIT_PLUGINS(EEPROMSettings,
LEDControl,
LEDPaletteTheme, LEDPaletteTheme,
ColormapEffect, ColormapEffect,
DefaultColormap,
Focus); Focus);
PALETTE( void setup(void) {
/* A list of 16 cRGB colors... */
)
COLORMAPS(
[0] = COLORMAP(
// List of palette indexes for each key, using the same layout
// as the `KEYMAP` macro does for keys.
),
[1] = COLORMAP_STACKED(
// List of palette indexes for each key, using the same layout
// as the `KEYMAP_STACKED` macro does for keys.
)
)
void setup() {
Kaleidoscope.setup(); Kaleidoscope.setup();
ColormapEffect.max_layers(1); ColormapEffect.max_layers(1);
DefaultColormap.setup();
} }
``` ```
The `PALETTE` and `COLORMAPS` macros are only used for the `DefaultColormap`
plugin, `ColormapEffect` itself makes no use of them. The `PALETTE` must always
contain a full 16-color palette. `COLORMAPS` can define colormaps for as many
layers as one wishes, but the `DefaultColormap` plugin will only copy over as
many as `ColormapEffect` is configured to support.
## Plugin methods ## Plugin methods
The extension provides an `ColormapEffect` singleton object, with a single method: The extension provides an `ColormapEffect` singleton object, with a single method:
@ -74,19 +44,6 @@ The extension provides an `ColormapEffect` singleton object, with a single metho
> Tells the extension to reserve space in EEPROM for up to `max` layers. Can > Tells the extension to reserve space in EEPROM for up to `max` layers. Can
> only be called once, any subsequent call will be a no-op. > only be called once, any subsequent call will be a no-op.
Also provided is an optional `DefaultColormap` plugin, with two methods:
### `.setup()`
> Intended to be called from the `setup()` method of the sketch, it checks if
> the `ColormapEffect` plugin is initialized, and if not, then copies the
> palette and the colormap over from the firmware to EEPROM.
### `.install()`
> Same as `.setup()` above, but without the initialized check. Intended to be
> used when one wants to restore the colormap to factory settings.
## Focus commands ## Focus commands
### `colormap.map` ### `colormap.map`
@ -98,14 +55,6 @@ Also provided is an optional `DefaultColormap` plugin, with two methods:
> ignore anything past the last key on the last layer (as set by the > ignore anything past the last key on the last layer (as set by the
> `.max_layers()` method). > `.max_layers()` method).
If the `DefaultColormap` plugin is also in use, an additional focus command is
made available:
### `colormap.install`
> Copies the default colormap and palette built into the firmware into EEPROM,
> effectively performing a factory reset for both.
## Dependencies ## Dependencies
* [Kaleidoscope-EEPROM-Settings](Kaleidoscope-EEPROM-Settings.md) * [Kaleidoscope-EEPROM-Settings](Kaleidoscope-EEPROM-Settings.md)

@ -1,6 +1,6 @@
/* -*- mode: c++ -*- /* -*- mode: c++ -*-
* Kaleidoscope-Colormap -- Per-layer colormap effect * Kaleidoscope-Colormap -- Per-layer colormap effect
* Copyright (C) 2016-2022 Keyboard.io, Inc * Copyright (C) 2016, 2017 Keyboard.io, Inc
* *
* This program is free software: you can redistribute it and/or modify it under it under * This program is free software: you can redistribute it and/or modify it under it under
* the terms of the GNU General Public License as published by the Free Software * the terms of the GNU General Public License as published by the Free Software
@ -17,5 +17,4 @@
#pragma once #pragma once
#include "kaleidoscope/plugin/Colormap.h" // IWYU pragma: export #include "kaleidoscope/plugin/Colormap.h" // IWYU pragma: export
#include "kaleidoscope/plugin/DefaultColormap.h" // IWYU pragma: export

@ -1,6 +1,6 @@
/* -*- mode: c++ -*- /* -*- mode: c++ -*-
* Kaleidoscope-Colormap -- Per-layer colormap effect * Kaleidoscope-Colormap -- Per-layer colormap effect
* Copyright (C) 2016-2022 Keyboard.io, Inc * Copyright (C) 2016, 2017, 2018, 2021 Keyboard.io, Inc
* *
* This program is free software: you can redistribute it and/or modify it under it under * This program is free software: you can redistribute it and/or modify it under it under
* the terms of the GNU General Public License as published by the Free Software * the terms of the GNU General Public License as published by the Free Software
@ -47,18 +47,7 @@ EventHandlerResult ColormapEffect::onNameQuery() {
return ::Focus.sendName(F("ColormapEffect")); return ::Focus.sendName(F("ColormapEffect"));
} }
bool ColormapEffect::isUninitialized() { void ColormapEffect::TransientLEDMode::onActivate(void) {
return ::LEDPaletteTheme.isThemeUninitialized(map_base_, max_layers_);
}
void ColormapEffect::updateColorIndexAtPosition(uint8_t layer, uint16_t position, uint8_t palette_index) {
if (layer >= max_layers_) return;
uint16_t index = Runtime.device().led_count * layer + position;
::LEDPaletteTheme.updateColorIndexAtPosition(map_base_, index, palette_index);
}
void ColormapEffect::TransientLEDMode::onActivate() {
if (!Runtime.has_leds) if (!Runtime.has_leds)
return; return;
@ -78,8 +67,8 @@ EventHandlerResult ColormapEffect::onLayerChange() {
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
EventHandlerResult ColormapEffect::onFocusEvent(const char *input) { EventHandlerResult ColormapEffect::onFocusEvent(const char *command) {
return ::LEDPaletteTheme.themeFocusEvent(input, PSTR("colormap.map"), map_base_, max_layers_); return ::LEDPaletteTheme.themeFocusEvent(command, PSTR("colormap.map"), map_base_, max_layers_);
} }
} // namespace plugin } // namespace plugin

@ -1,6 +1,6 @@
/* -*- mode: c++ -*- /* -*- mode: c++ -*-
* Kaleidoscope-Colormap -- Per-layer colormap effect * Kaleidoscope-Colormap -- Per-layer colormap effect
* Copyright (C) 2016-2022 Keyboard.io, Inc * Copyright (C) 2016, 2017, 2018, 2021 Keyboard.io, Inc
* *
* This program is free software: you can redistribute it and/or modify it under it under * This program is free software: you can redistribute it and/or modify it under it under
* the terms of the GNU General Public License as published by the Free Software * the terms of the GNU General Public License as published by the Free Software
@ -32,14 +32,13 @@ class ColormapEffect : public Plugin,
public LEDModeInterface, public LEDModeInterface,
public AccessTransientLEDMode { public AccessTransientLEDMode {
public: public:
ColormapEffect(void) {}
void max_layers(uint8_t max_); void max_layers(uint8_t max_);
EventHandlerResult onLayerChange(); EventHandlerResult onLayerChange();
EventHandlerResult onNameQuery(); EventHandlerResult onNameQuery();
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
static bool isUninitialized();
static void updateColorIndexAtPosition(uint8_t layer, uint16_t position, uint8_t palette_index);
// This class' instance has dynamic lifetime // This class' instance has dynamic lifetime
// //
@ -55,7 +54,7 @@ class ColormapEffect : public Plugin,
protected: protected:
friend class ColormapEffect; friend class ColormapEffect;
void onActivate() final; void onActivate(void) final;
void refreshAt(KeyAddr key_addr) final; void refreshAt(KeyAddr key_addr) final;
private: private:

@ -1,94 +0,0 @@
/* -*- mode: c++ -*-
* Kaleidoscope-Colormap -- Per-layer colormap effect
* Copyright (C) 2022 Keyboard.io, Inc
*
* This program is free software: you can redistribute it and/or modify it under it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "kaleidoscope/plugin/Colormap.h" // for Colormap
#include "kaleidoscope/plugin/DefaultColormap.h"
#include <Arduino.h> // for F, PSTR, __FlashStringHelper
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <Kaleidoscope-LEDControl.h> // for LEDControl
#include <Kaleidoscope-LED-Palette-Theme.h> // for LEDPaletteTheme
#include <stdint.h> // for uint8_t, uint16_t
#include "kaleidoscope/KeyAddr.h" // for KeyAddr
#include "kaleidoscope/Runtime.h" // for Runtime, Runtime_
namespace kaleidoscope {
namespace plugin {
namespace defaultcolormap {
__attribute__((weak)) extern const cRGB palette[] = {};
__attribute__((weak)) extern bool palette_defined = false;
__attribute__((weak)) extern const uint8_t colormaps[][kaleidoscope_internal::device.matrix_rows * kaleidoscope_internal::device.matrix_columns] = {};
__attribute__((weak)) extern uint8_t colormap_layers = 0;
} // namespace defaultcolormap
void DefaultColormap::setup() {
// If the colormap is already initialized, return early.
if (!::ColormapEffect.isUninitialized())
return;
install();
}
void DefaultColormap::install() {
if (!defaultcolormap::palette_defined) return;
for (uint8_t i = 0; i < 16; i++) {
cRGB color;
color.r = pgm_read_byte(&(defaultcolormap::palette[i].r));
color.g = pgm_read_byte(&(defaultcolormap::palette[i].g));
color.b = pgm_read_byte(&(defaultcolormap::palette[i].b));
::LEDPaletteTheme.updatePaletteColor(i, color);
}
if (defaultcolormap::colormap_layers == 0) return;
for (uint8_t layer = 0; layer < defaultcolormap::colormap_layers; layer++) {
for (int8_t i = 0; i < Runtime.device().numKeys(); i++) {
const int8_t post = Runtime.device().ledDriver().getLedIndex(i);
const uint8_t idx = pgm_read_byte(&(defaultcolormap::colormaps[layer][i]));
::ColormapEffect.updateColorIndexAtPosition(layer, post, idx);
}
}
Runtime.storage().commit();
::LEDControl.refreshAll();
}
EventHandlerResult DefaultColormap::onFocusEvent(const char *input) {
if (!Runtime.has_leds)
return EventHandlerResult::OK;
const char *cmd = PSTR("colormap.install");
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd);
if (!::Focus.inputMatchesCommand(input, cmd))
return EventHandlerResult::OK;
install();
return EventHandlerResult::EVENT_CONSUMED;
}
} // namespace plugin
} // namespace kaleidoscope
kaleidoscope::plugin::DefaultColormap DefaultColormap;

@ -1,96 +0,0 @@
/* -*- mode: c++ -*-
* Kaleidoscope-Colormap -- Per-layer colormap effect
* Copyright (C) 2022 Keyboard.io, Inc
*
* This program is free software: you can redistribute it and/or modify it under it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <Arduino.h> // for PROGMEM
#include <stdint.h> // for uint8_t
#include "kaleidoscope_internal/device.h" // for device
#include "kaleidoscope/device/device.h" // for cRGB
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult
#include "kaleidoscope/plugin.h" // for Plugin
namespace kaleidoscope {
namespace plugin {
// clang-format off
#define COLORMAPS(layers...) \
namespace kaleidoscope { \
namespace plugin { \
namespace defaultcolormap { \
const uint8_t colormaps[][kaleidoscope_internal::device.matrix_rows * kaleidoscope_internal::device.matrix_columns] PROGMEM = { \
layers \
}; \
uint8_t colormap_layers = \
sizeof(colormaps) / sizeof(*colormaps); \
} /* defaultcolormap */ \
} /* plugin */ \
} /* kaleidoscope */
#define __IDENTITY__(X) X
#ifdef PER_KEY_DATA_STACKED
#define COLORMAP_STACKED(...) \
{ \
MAP_LIST(__IDENTITY__, PER_KEY_DATA_STACKED(0, __VA_ARGS__)) \
}
#endif
#ifdef PER_KEY_DATA
#define COLORMAP(...) \
{ \
MAP_LIST(__IDENTITY__, PER_KEY_DATA(0, __VA_ARGS__)) \
}
#endif
#define PALETTE(p0, p1, p2, p3, p4, p5, p6, p7, \
p8, p9, pa, pb, pc, pd, pe, pf) \
namespace kaleidoscope { \
namespace plugin { \
namespace defaultcolormap { \
const cRGB palette[] PROGMEM = { \
p0, p1, p2, p3, p4, p5, p6, p7, \
p8, p9, pa, pb, pc, pd, pe, pf \
}; \
bool palette_defined = true; \
} /* defaultcolormap */ \
} /* plugin */ \
} /* kaleidoscope */
// clang-format on
namespace defaultcolormap {
extern bool palette_defined;
extern const cRGB palette[];
extern const uint8_t colormaps[][kaleidoscope_internal::device.matrix_rows * kaleidoscope_internal::device.matrix_columns];
extern uint8_t colormap_layers;
} // namespace defaultcolormap
class DefaultColormap : public Plugin {
public:
static void setup();
static void install();
EventHandlerResult onFocusEvent(const char *input);
};
} // namespace plugin
} // namespace kaleidoscope
extern kaleidoscope::plugin::DefaultColormap DefaultColormap;

@ -34,7 +34,7 @@ void cycleAction(Key previous_key, uint8_t cycle_count) {
KALEIDOSCOPE_INIT_PLUGINS(Cycle); KALEIDOSCOPE_INIT_PLUGINS(Cycle);
void setup() { void setup(void) {
Kaleidoscope.setup(); Kaleidoscope.setup();
} }
``` ```

@ -31,6 +31,11 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
// --- state ---
Key Cycle::last_non_cycle_key_;
KeyAddr Cycle::cycle_key_addr_{KeyAddr::invalid_state};
uint8_t Cycle::current_modifier_flags_;
uint8_t Cycle::cycle_count_;
// --- helpers --- // --- helpers ---

@ -38,18 +38,20 @@ namespace kaleidoscope {
namespace plugin { namespace plugin {
class Cycle : public kaleidoscope::Plugin { class Cycle : public kaleidoscope::Plugin {
public: public:
void replace(Key key); Cycle(void) {}
void replace(uint8_t cycle_size, const Key cycle_steps[]);
static void replace(Key key);
static void replace(uint8_t cycle_size, const Key cycle_steps[]);
EventHandlerResult onNameQuery(); EventHandlerResult onNameQuery();
EventHandlerResult onKeyEvent(KeyEvent &event); EventHandlerResult onKeyEvent(KeyEvent &event);
private: private:
uint8_t toModFlag(uint8_t keyCode); static uint8_t toModFlag(uint8_t keyCode);
Key last_non_cycle_key_; static Key last_non_cycle_key_;
KeyAddr cycle_key_addr_{KeyAddr::invalid_state}; static KeyAddr cycle_key_addr_;
uint8_t cycle_count_; static uint8_t cycle_count_;
uint8_t current_modifier_flags_; static uint8_t current_modifier_flags_;
}; };
} // namespace plugin } // namespace plugin

@ -16,7 +16,7 @@ the box, without any further configuration:
KALEIDOSCOPE_INIT_PLUGINS(CycleTimeReport); KALEIDOSCOPE_INIT_PLUGINS(CycleTimeReport);
void setup () { void setup (void) {
Kaleidoscope.serialPort().begin(9600); Kaleidoscope.serialPort().begin(9600);
Kaleidoscope.setup (); Kaleidoscope.setup ();
} }
@ -25,23 +25,25 @@ void setup () {
## Plugin methods ## Plugin methods
The plugin provides a single object, `CycleTimeReport`, with the following The plugin provides a single object, `CycleTimeReport`, with the following
methods: property. All times are in milliseconds.
### `.setReportInterval(interval)` ### `.average_loop_time`
> Sets the length of time between reports to `interval` milliseconds. The > A read-only by contract value, the average time of main loop lengths between
> default is `1000`, so it will report once per second. > two reports.
### `.report(mean_cycle_time)` ## Overrideable methods
> Reports the average (mean) cycle time since the previous report. This method ### `cycleTimeReport()`
> is called automatically, once per report interval (see above). By default, it
> does so over `Serial`. > Reports the average loop time. By default, it does so over `Serial`, every
> time when the report period is up.
> >
> It can be overridden, to change how the report looks, or to make the report > It can be overridden, to change how the report looks, or to make the report
> toggleable, among other things. > toggleable, among other things.
> >
> It takes no arguments, and returns nothing. > It takes no arguments, and returns nothing, but has access to
> `CycleTimeReport.average_loop_time` above.
## Further reading ## Further reading

@ -26,40 +26,43 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
uint16_t CycleTimeReport::last_report_time_;
uint32_t CycleTimeReport::loop_start_time_;
uint32_t CycleTimeReport::average_loop_time;
EventHandlerResult CycleTimeReport::onSetup() {
last_report_time_ = Runtime.millisAtCycleStart();
return EventHandlerResult::OK;
}
EventHandlerResult CycleTimeReport::beforeEachCycle() { EventHandlerResult CycleTimeReport::beforeEachCycle() {
// A counter storing the number of cycles since the last mean cycle time loop_start_time_ = micros();
// report was sent: return EventHandlerResult::OK;
static uint16_t elapsed_cycles = 0; }
// We only compute the mean cycle time once per report interval. EventHandlerResult CycleTimeReport::afterEachCycle() {
if (Runtime.hasTimeExpired(last_report_millis_, report_interval_)) { uint32_t loop_time = micros() - loop_start_time_;
uint32_t elapsed_time = micros() - last_report_micros_;
uint32_t mean_cycle_time = elapsed_time / elapsed_cycles;
report(mean_cycle_time); if (average_loop_time)
average_loop_time = (average_loop_time + loop_time) / 2;
else
average_loop_time = loop_time;
// Reset the cycle counter and timestamps. if (Runtime.hasTimeExpired(last_report_time_, uint16_t(1000))) {
elapsed_cycles = 0; cycleTimeReport();
last_report_millis_ += report_interval_;
last_report_micros_ = micros();
}
// Increment the cycle counter unconditionally. average_loop_time = 0;
++elapsed_cycles; last_report_time_ = Runtime.millisAtCycleStart();
}
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
__attribute__((weak)) void CycleTimeReport::report(uint16_t mean_cycle_time) {
Focus.send(Focus.COMMENT,
F("mean cycle time:"),
mean_cycle_time,
F("µs"),
Focus.NEWLINE);
}
} // namespace plugin } // namespace plugin
} // namespace kaleidoscope } // namespace kaleidoscope
__attribute__((weak)) void cycleTimeReport(void) {
Focus.send(Focus.COMMENT, F("average loop time:"), CycleTimeReport.average_loop_time, Focus.NEWLINE);
}
kaleidoscope::plugin::CycleTimeReport CycleTimeReport; kaleidoscope::plugin::CycleTimeReport CycleTimeReport;

@ -17,49 +17,31 @@
#pragma once #pragma once
#include <stdint.h> // for uint16_t, uint32_t #include <stdint.h> // for uint32_t, uint16_t
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult #include "kaleidoscope/event_handler_result.h" // for EventHandlerResult
#include "kaleidoscope/plugin.h" // for Plugin #include "kaleidoscope/plugin.h" // for Plugin
// -----------------------------------------------------------------------------
// Deprecation warning messages
#include "kaleidoscope_internal/deprecations.h" // for DEPRECATED
#define _DEPRECATED_MESSAGE_CYCLETIMEREPORT_AVG_TIME \
"The `CycleTimeReport.average_loop_time` variable is deprecated. See\n" \
"the current documentation for CycleTimeReport for details.\n" \
"This variable will be removed after 2022-09-01."
// -----------------------------------------------------------------------------
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
class CycleTimeReport : public kaleidoscope::Plugin { class CycleTimeReport : public kaleidoscope::Plugin {
public: public:
CycleTimeReport() {}
EventHandlerResult onSetup();
EventHandlerResult beforeEachCycle(); EventHandlerResult beforeEachCycle();
EventHandlerResult afterEachCycle();
#ifndef NDEPRECATED
DEPRECATED(CYCLETIMEREPORT_AVG_TIME)
static uint32_t average_loop_time; static uint32_t average_loop_time;
#endif
/// Set the length of time between reports (in milliseconds)
void setReportInterval(uint16_t interval) {
report_interval_ = interval;
}
/// Report the given mean cycle time in microseconds
void report(uint16_t mean_cycle_time);
private: private:
// Interval between reports, in milliseconds static uint16_t last_report_time_;
uint16_t report_interval_ = 1000; static uint32_t loop_start_time_;
// Timestamps recording when the last report was sent
uint16_t last_report_millis_ = 0;
uint32_t last_report_micros_ = 0;
}; };
} // namespace plugin } // namespace plugin
} // namespace kaleidoscope } // namespace kaleidoscope
void cycleTimeReport(void);
extern kaleidoscope::plugin::CycleTimeReport CycleTimeReport; extern kaleidoscope::plugin::CycleTimeReport CycleTimeReport;

@ -1,62 +0,0 @@
# DefaultLEDModeConfig
The `DefaultLEDModeConfig` plugin provides a way to set a default LED mode, the
LED mode the device starts up with active, via Focus.
By default the first LED mode enabled will be the active one, unless set
otherwise in `setup()`. To make this configurable, without having to reorder the
LED modes, this plugin provides the necessary tools to accomplish that.
## Using the plugin
The example below shows how to use the plugin, including setting up a LED mode
other than the first to use as a default in case EEPROM is uninitialized.
```c++
#include <Kaleidoscope.h>
#include <Kaleidoscope-EEPROM-Settings.h>
#include <Kaleidoscope-LEDControl.h>
#include <Kaleidoscope-DefaultLEDModeConfig.h>
#include <Kaleidoscope-LEDEffect-Rainbow.h>
#include <Kaleidoscope-FocusSerial.h>
KALEIDOSCOPE_INIT_PLUGINS(EEPROMSettings,
LEDControl,
LEDOff,
LEDRainbowEffect,
LEDRainbowWaveEffect,
Focus,
DefaultLEDModeConfig);
void setup() {
Kaleidoscope.setup();
DefaultLEDModeConfig.activateLEDModeIfUnconfigured(
&LEDRainbowWaveEffect
);
}
```
## Plugin methods
The plugin provides a singleton object called `DefaultLEDModeConfig`, with a single method:
### `.activateLEDModeIfUnconfigured(&LEDModePlugin)`
> Activates the LED mode pointed to by `&LEDModePlugin` if and only if the
> EEPROM slice of the plugin is unconfigured. This lets us set a default LED
> mode without persisting it into storage, or hard-coding it.
## Focus commands
### `led_mode.default`
> Without arguments, prints the default LED mode's index.
>
> If an argument is given, it must be the index of the LED mode we wish to set
> as the default.
## Dependencies
* [Kaleidoscope-EEPROM-Settings](Kaleidoscope-EEPROM-Settings.md)
* [Kaleidoscope-FocusSerial](Kaleidoscope-FocusSerial.md)

@ -1,7 +0,0 @@
name=Kaleidoscope-DefaultLEDModeConfig
version=0.0.0
sentence=Save & restore the default LED mode
maintainer=Kaleidoscope's Developers <jesse@keyboard.io>
url=https://github.com/keyboardio/Kaleidoscope
author=Keyboardio
paragraph=

@ -1,20 +0,0 @@
/* -*- mode: c++ -*-
* Kaleidoscope - Firmware for computer input devices
* Copyright (C) 2022 Keyboard.io, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "kaleidoscope/plugin/DefaultLEDModeConfig.h" // IWYU pragma: export

@ -1,89 +0,0 @@
/* -*- mode: c++ -*-
* Kaleidoscope - Firmware for computer input devices
* Copyright (C) 2022 Keyboard.io, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "kaleidoscope/plugin/DefaultLEDModeConfig.h"
#include <Arduino.h> // for PSTR, F, __FlashStringHelper
#include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint8_t, uint16_t
#include "kaleidoscope/Runtime.h" // for Runtime, Runtime_
#include "kaleidoscope/device/device.h" // for VirtualProps::Storage, Base<>::Storage
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult, EventHandlerResult::OK
#include "kaleidoscope/plugin/LEDControl.h" // for LEDControl
namespace kaleidoscope {
namespace plugin {
uint16_t DefaultLEDModeConfig::settings_base_;
struct DefaultLEDModeConfig::settings DefaultLEDModeConfig::settings_;
EventHandlerResult DefaultLEDModeConfig::onSetup() {
settings_base_ = ::EEPROMSettings.requestSlice(sizeof(settings_));
Runtime.storage().get(settings_base_, settings_);
// If our slice is uninitialized, then return early, without touching the
// current mode.
if (Runtime.storage().isSliceUninitialized(settings_base_, sizeof(settings_)))
return EventHandlerResult::OK;
::LEDControl.set_mode(settings_.default_mode_index);
return EventHandlerResult::OK;
}
EventHandlerResult DefaultLEDModeConfig::onFocusEvent(const char *input) {
const char *cmd = PSTR("led_mode.default");
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd);
if (!::Focus.inputMatchesCommand(input, cmd))
return EventHandlerResult::OK;
if (::Focus.isEOL()) {
::Focus.send(settings_.default_mode_index);
} else {
uint8_t idx;
::Focus.read(idx);
settings_.default_mode_index = idx;
::LEDControl.set_mode(idx);
Runtime.storage().put(settings_base_, settings_);
Runtime.storage().commit();
}
return EventHandlerResult::EVENT_CONSUMED;
}
EventHandlerResult DefaultLEDModeConfig::onNameQuery() {
return ::Focus.sendName(F("DefaultLEDModeConfig"));
}
void DefaultLEDModeConfig::activateLEDModeIfUnconfigured(LEDModeInterface *plugin) {
if (!Runtime.storage().isSliceUninitialized(settings_base_, sizeof(settings_)))
return;
plugin->activate();
}
} // namespace plugin
} // namespace kaleidoscope
kaleidoscope::plugin::DefaultLEDModeConfig DefaultLEDModeConfig;

@ -1,47 +0,0 @@
/* -*- mode: c++ -*-
* Kaleidoscope - Firmware for computer input devices
* Copyright (C) 2022 Keyboard.io, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdint.h> // for uint8_t, uint16_t
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult
#include "kaleidoscope/plugin.h" // for Plugin
#include "kaleidoscope/plugin/LEDModeInterface.h" // for LEDModeInterface
namespace kaleidoscope {
namespace plugin {
class DefaultLEDModeConfig : public kaleidoscope::Plugin {
public:
EventHandlerResult onSetup();
EventHandlerResult onNameQuery();
EventHandlerResult onFocusEvent(const char *input);
void activateLEDModeIfUnconfigured(LEDModeInterface *plugin);
private:
static uint16_t settings_base_;
static struct settings {
uint8_t default_mode_index;
} settings_;
};
} // namespace plugin
} // namespace kaleidoscope
extern kaleidoscope::plugin::DefaultLEDModeConfig DefaultLEDModeConfig;

@ -15,7 +15,7 @@ the box, without any further configuration:
/* ... */ /* ... */
void setup () { void setup (void) {
Kaleidoscope.setup (); Kaleidoscope.setup ();
TRACE() TRACE()
} }

@ -19,9 +19,9 @@ except the amount of storage available on the keyboard.
## Using the plugin ## Using the plugin
To use the plugin, we need to include the header, initialize the plugin with To use the plugin, we need to include the header, tell the firmware to `use` the
`KALEIDOSCOPE_INIT_PLUGINS()`, and reserve storage space for the macros. This is plugin, and reserve storage space for the macros. This is best illustrated with
best illustrated with an example: an example:
```c++ ```c++
#include <Kaleidoscope.h> #include <Kaleidoscope.h>
@ -96,6 +96,5 @@ The plugin provides two Focus commands: `macros.map` and `macros.trigger`.
## Dependencies ## Dependencies
* [Kaleidoscope-MacroSupport](Kaleidoscope-MacroSupport.md)
* [Kaleidoscope-EEPROM-Settings](Kaleidoscope-EEPROM-Settings.md) * [Kaleidoscope-EEPROM-Settings](Kaleidoscope-EEPROM-Settings.md)
* [Kaleidoscope-FocusSerial](Kaleidoscope-FocusSerial.md) * [Kaleidoscope-FocusSerial](Kaleidoscope-FocusSerial.md)

@ -16,14 +16,15 @@
#include "kaleidoscope/plugin/DynamicMacros.h" #include "kaleidoscope/plugin/DynamicMacros.h"
#include <Arduino.h> // for delay, PSTR, F, __FlashStri... #include <Arduino.h> // for delay, PSTR, strcmp_P, F, __FlashStri...
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <Kaleidoscope-Ranges.h> // for DYNAMIC_MACRO_FIRST, DYNAMIC_MACRO_LAST #include <Kaleidoscope-Ranges.h> // for DYNAMIC_MACRO_FIRST, DYNAMIC_MACRO_LAST
#include "kaleidoscope/KeyAddr.h" // for KeyAddr
#include "kaleidoscope/KeyEvent.h" // for KeyEvent #include "kaleidoscope/KeyEvent.h" // for KeyEvent
#include "kaleidoscope/Runtime.h" // for Runtime, Runtime_ #include "kaleidoscope/Runtime.h" // for Runtime, Runtime_
#include "kaleidoscope/device/device.h" // for VirtualProps::Storage, Base<>::Storage #include "kaleidoscope/device/device.h" // for VirtualProps::Storage, Base<>::Storage
#include "kaleidoscope/keyswitch_state.h" // for keyToggledOn #include "kaleidoscope/keyswitch_state.h" // for INJECTED, IS_PRESSED, WAS_PRESSED
#include "kaleidoscope/plugin/EEPROM-Settings.h" // for EEPROMSettings #include "kaleidoscope/plugin/EEPROM-Settings.h" // for EEPROMSettings
// This is a special exception to the rule of only including a plugin's // This is a special exception to the rule of only including a plugin's
// top-level header file, because DynamicMacros doesn't depend on the Macros // top-level header file, because DynamicMacros doesn't depend on the Macros
@ -33,7 +34,38 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
uint16_t DynamicMacros::storage_base_;
uint16_t DynamicMacros::storage_size_;
uint16_t DynamicMacros::map_[];
uint8_t DynamicMacros::macro_count_;
Key DynamicMacros::active_macro_keys_[];
// ============================================================================= // =============================================================================
// It might be possible to use Macros instead of reproducing it
void DynamicMacros::press(Key key) {
Runtime.handleKeyEvent(KeyEvent(KeyAddr::none(), IS_PRESSED | INJECTED, key));
for (Key &mkey : active_macro_keys_) {
if (mkey == Key_NoKey) {
mkey = key;
break;
}
}
}
void DynamicMacros::release(Key key) {
for (Key &mkey : active_macro_keys_) {
if (mkey == key) {
mkey = Key_NoKey;
}
}
Runtime.handleKeyEvent(KeyEvent(KeyAddr::none(), WAS_PRESSED | INJECTED, key));
}
void DynamicMacros::tap(Key key) {
Runtime.handleKeyEvent(KeyEvent(KeyAddr::none(), IS_PRESSED | INJECTED, key));
Runtime.handleKeyEvent(KeyEvent(KeyAddr::none(), WAS_PRESSED | INJECTED, key));
}
uint8_t DynamicMacros::updateDynamicMacroCache() { uint8_t DynamicMacros::updateDynamicMacroCache() {
uint16_t pos = storage_base_; uint16_t pos = storage_base_;
uint8_t current_id = 0; uint8_t current_id = 0;
@ -196,7 +228,6 @@ bool isDynamicMacrosKey(Key key) {
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
EventHandlerResult DynamicMacros::onKeyEvent(KeyEvent &event) { EventHandlerResult DynamicMacros::onKeyEvent(KeyEvent &event) {
// Ignore everything except DynamicMacros keys
if (!isDynamicMacrosKey(event.key)) if (!isDynamicMacrosKey(event.key))
return EventHandlerResult::OK; return EventHandlerResult::OK;
@ -204,24 +235,37 @@ EventHandlerResult DynamicMacros::onKeyEvent(KeyEvent &event) {
uint8_t macro_id = event.key.getRaw() - ranges::DYNAMIC_MACRO_FIRST; uint8_t macro_id = event.key.getRaw() - ranges::DYNAMIC_MACRO_FIRST;
play(macro_id); play(macro_id);
} else { } else {
clear(); for (Key key : active_macro_keys_) {
release(key);
}
} }
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
EventHandlerResult DynamicMacros::beforeReportingState(const KeyEvent &event) {
// Here we add keycodes to the HID report for keys held in a macro sequence.
// This is necessary because Kaleidoscope doesn't know about the supplemental
// `active_macro_keys_[]` array.
for (Key key : active_macro_keys_) {
if (key != Key_NoKey)
Runtime.addToReport(key);
}
return EventHandlerResult::OK;
}
EventHandlerResult DynamicMacros::onNameQuery() { EventHandlerResult DynamicMacros::onNameQuery() {
return ::Focus.sendName(F("DynamicMacros")); return ::Focus.sendName(F("DynamicMacros"));
} }
EventHandlerResult DynamicMacros::onFocusEvent(const char *input) { EventHandlerResult DynamicMacros::onFocusEvent(const char *command) {
const char *cmd_map = PSTR("macros.map"); if (::Focus.handleHelp(command, PSTR("macros.map\nmacros.trigger")))
const char *cmd_trigger = PSTR("macros.trigger"); return EventHandlerResult::OK;
if (::Focus.inputMatchesHelp(input)) if (strncmp_P(command, PSTR("macros."), 7) != 0)
return ::Focus.printHelp(cmd_map, cmd_trigger); return EventHandlerResult::OK;
if (::Focus.inputMatchesCommand(input, cmd_map)) { if (strcmp_P(command + 7, PSTR("map")) == 0) {
if (::Focus.isEOL()) { if (::Focus.isEOL()) {
for (uint16_t i = 0; i < storage_size_; i++) { for (uint16_t i = 0; i < storage_size_; i++) {
uint8_t b; uint8_t b;
@ -240,16 +284,15 @@ EventHandlerResult DynamicMacros::onFocusEvent(const char *input) {
Runtime.storage().commit(); Runtime.storage().commit();
macro_count_ = updateDynamicMacroCache(); macro_count_ = updateDynamicMacroCache();
} }
return EventHandlerResult::EVENT_CONSUMED; }
} else if (::Focus.inputMatchesCommand(input, cmd_trigger)) {
if (strcmp_P(command + 7, PSTR("trigger")) == 0) {
uint8_t id = 0; uint8_t id = 0;
::Focus.read(id); ::Focus.read(id);
play(id); play(id);
return EventHandlerResult::EVENT_CONSUMED;
} }
return EventHandlerResult::OK; return EventHandlerResult::EVENT_CONSUMED;
} }
// public // public

@ -16,16 +16,17 @@
#pragma once #pragma once
#include <Kaleidoscope-MacroSupport.h> // for MacroSupport #include <Kaleidoscope-Ranges.h> // for DYNAMIC_MACRO_FIRST
#include <Kaleidoscope-Ranges.h> // for DYNAMIC_MACRO_FIRST #include <stdint.h> // for uint16_t, uint8_t
#include <stdint.h> // for uint16_t, uint8_t
#include "kaleidoscope/KeyEvent.h" // for KeyEvent #include "kaleidoscope/KeyEvent.h" // for KeyEvent
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult #include "kaleidoscope/event_handler_result.h" // for EventHandlerResult
#include "kaleidoscope/key_defs.h" // for Key #include "kaleidoscope/key_defs.h" // for Key
#include "kaleidoscope/plugin.h" // for Plugin #include "kaleidoscope/plugin.h" // for Plugin
#define DM(n) ::kaleidoscope::plugin::DynamicMacrosKey(n) #define DM(n) ::kaleidoscope::plugin::DynamicMacrosKey(n)
#define MAX_CONCURRENT_DYNAMIC_MACRO_KEYS 8
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
@ -38,26 +39,23 @@ class DynamicMacros : public kaleidoscope::Plugin {
public: public:
EventHandlerResult onNameQuery(); EventHandlerResult onNameQuery();
EventHandlerResult onKeyEvent(KeyEvent &event); EventHandlerResult onKeyEvent(KeyEvent &event);
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult beforeReportingState(const KeyEvent &event);
EventHandlerResult beforeReportingState(const KeyEvent &event) { EventHandlerResult onFocusEvent(const char *command);
return ::MacroSupport.beforeReportingState(event);
}
void reserve_storage(uint16_t size); static void reserve_storage(uint16_t size);
void play(uint8_t seq_id); void play(uint8_t seq_id);
private: private:
uint16_t storage_base_; static uint16_t storage_base_;
uint16_t storage_size_; static uint16_t storage_size_;
uint16_t map_[32]; static uint16_t map_[32];
uint8_t macro_count_; static uint8_t macro_count_;
uint8_t updateDynamicMacroCache(); static uint8_t updateDynamicMacroCache();
static Key active_macro_keys_[MAX_CONCURRENT_DYNAMIC_MACRO_KEYS];
inline void press(Key key) { ::MacroSupport.press(key); } static void press(Key key);
inline void release(Key key) { ::MacroSupport.release(key); } static void release(Key key);
inline void tap(Key key) const { ::MacroSupport.tap(key); } static void tap(Key key);
inline void clear() { ::MacroSupport.clear(); }
}; };
} // namespace plugin } // namespace plugin

@ -17,7 +17,7 @@
#include "kaleidoscope/plugin/DynamicTapDance.h" #include "kaleidoscope/plugin/DynamicTapDance.h"
#include <Arduino.h> // for PSTR, F, __FlashStringHelper #include <Arduino.h> // for PSTR, F, __FlashStringHelper, strcmp_P
#include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings #include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint16_t, uint8_t #include <stdint.h> // for uint16_t, uint8_t
@ -34,6 +34,13 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
uint16_t DynamicTapDance::storage_base_;
uint16_t DynamicTapDance::storage_size_;
uint16_t DynamicTapDance::map_[];
uint8_t DynamicTapDance::offset_;
uint8_t DynamicTapDance::dance_count_;
constexpr uint8_t DynamicTapDance::reserved_tap_dance_key_count_;
void DynamicTapDance::updateDynamicTapDanceCache() { void DynamicTapDance::updateDynamicTapDanceCache() {
uint16_t pos = storage_base_; uint16_t pos = storage_base_;
uint8_t current_id = 0; uint8_t current_id = 0;
@ -93,33 +100,33 @@ EventHandlerResult DynamicTapDance::onNameQuery() {
return ::Focus.sendName(F("DynamicTapDance")); return ::Focus.sendName(F("DynamicTapDance"));
} }
EventHandlerResult DynamicTapDance::onFocusEvent(const char *input) { EventHandlerResult DynamicTapDance::onFocusEvent(const char *command) {
const char *cmd_map = PSTR("tapdance.map"); if (::Focus.handleHelp(command, PSTR("tapdance.map")))
return EventHandlerResult::OK;
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd_map);
if (!::Focus.inputMatchesCommand(input, cmd_map)) if (strncmp_P(command, PSTR("tapdance."), 9) != 0)
return EventHandlerResult::OK; return EventHandlerResult::OK;
if (::Focus.isEOL()) { if (strcmp_P(command + 9, PSTR("map")) == 0) {
for (uint16_t i = 0; i < storage_size_; i += 2) { if (::Focus.isEOL()) {
Key k; for (uint16_t i = 0; i < storage_size_; i += 2) {
Runtime.storage().get(storage_base_ + i, k); Key k;
::Focus.send(k); Runtime.storage().get(storage_base_ + i, k);
} ::Focus.send(k);
} else { }
uint16_t pos = 0; } else {
uint16_t pos = 0;
while (!::Focus.isEOL()) { while (!::Focus.isEOL()) {
Key k; Key k;
::Focus.read(k); ::Focus.read(k);
Runtime.storage().put(storage_base_ + pos, k); Runtime.storage().put(storage_base_ + pos, k);
pos += 2; pos += 2;
}
Runtime.storage().commit();
updateDynamicTapDanceCache();
} }
Runtime.storage().commit();
updateDynamicTapDanceCache();
} }
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;

@ -30,21 +30,23 @@ namespace plugin {
class DynamicTapDance : public kaleidoscope::Plugin { class DynamicTapDance : public kaleidoscope::Plugin {
public: public:
DynamicTapDance() {}
EventHandlerResult onNameQuery(); EventHandlerResult onNameQuery();
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
void setup(uint8_t dynamic_offset, uint16_t size); static void setup(uint8_t dynamic_offset, uint16_t size);
bool dance(uint8_t tap_dance_index, KeyAddr key_addr, uint8_t tap_count, TapDance::ActionType tap_dance_action); static bool dance(uint8_t tap_dance_index, KeyAddr key_addr, uint8_t tap_count, TapDance::ActionType tap_dance_action);
private: private:
uint16_t storage_base_; static uint16_t storage_base_;
uint16_t storage_size_; static uint16_t storage_size_;
static constexpr uint8_t reserved_tap_dance_key_count_ = ranges::TD_LAST - ranges::TD_FIRST + 1; static constexpr uint8_t reserved_tap_dance_key_count_ = ranges::TD_LAST - ranges::TD_FIRST + 1;
uint16_t map_[reserved_tap_dance_key_count_]; // NOLINT(runtime/arrays) static uint16_t map_[reserved_tap_dance_key_count_];
uint8_t dance_count_; static uint8_t dance_count_;
uint8_t offset_; static uint8_t offset_;
void updateDynamicTapDanceCache(); static void updateDynamicTapDanceCache();
}; };
} // namespace plugin } // namespace plugin

@ -17,7 +17,7 @@
#include "kaleidoscope/plugin/EEPROM-Keymap-Programmer.h" #include "kaleidoscope/plugin/EEPROM-Keymap-Programmer.h"
#include <Arduino.h> // for PSTR #include <Arduino.h> // for PSTR, strcmp_P
#include <Kaleidoscope-EEPROM-Keymap.h> // for EEPROMKeymap #include <Kaleidoscope-EEPROM-Keymap.h> // for EEPROMKeymap
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint16_t, uint8_t #include <stdint.h> // for uint16_t, uint8_t
@ -33,8 +33,12 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
uint16_t EEPROMKeymapProgrammer::update_position_;
EEPROMKeymapProgrammer::state_t EEPROMKeymapProgrammer::state_;
EEPROMKeymapProgrammer::mode_t EEPROMKeymapProgrammer::mode;
Key EEPROMKeymapProgrammer::new_key_;
void EEPROMKeymapProgrammer::nextState() { void EEPROMKeymapProgrammer::nextState(void) {
switch (state_) { switch (state_) {
case INACTIVE: case INACTIVE:
state_ = WAIT_FOR_KEY; state_ = WAIT_FOR_KEY;
@ -54,7 +58,7 @@ void EEPROMKeymapProgrammer::nextState() {
} }
} }
void EEPROMKeymapProgrammer::cancel() { void EEPROMKeymapProgrammer::cancel(void) {
update_position_ = 0; update_position_ = 0;
new_key_ = Key_NoKey; new_key_ = Key_NoKey;
state_ = INACTIVE; state_ = INACTIVE;
@ -106,13 +110,13 @@ EventHandlerResult EEPROMKeymapProgrammer::onKeyEvent(KeyEvent &event) {
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
EventHandlerResult EEPROMKeymapProgrammer::onFocusEvent(const char *input) { EventHandlerResult EEPROMKeymapProgrammer::onFocusEvent(const char *command) {
const char *cmd = PSTR("keymap.toggleProgrammer"); const char *cmd = PSTR("keymap.toggleProgrammer");
if (::Focus.inputMatchesHelp(input)) if (::Focus.handleHelp(command, cmd))
return ::Focus.printHelp(cmd); return EventHandlerResult::OK;
if (!::Focus.inputMatchesCommand(input, cmd)) if (strcmp_P(command, cmd) != 0)
return EventHandlerResult::OK; return EventHandlerResult::OK;
if (state_ == INACTIVE) if (state_ == INACTIVE)

@ -32,16 +32,18 @@ class EEPROMKeymapProgrammer : public kaleidoscope::Plugin {
CODE, CODE,
COPY, COPY,
} mode_t; } mode_t;
mode_t mode; static mode_t mode;
void activate() { EEPROMKeymapProgrammer(void) {}
static void activate(void) {
nextState(); nextState();
} }
void nextState(); static void nextState(void);
void cancel(); static void cancel(void);
EventHandlerResult onKeyEvent(KeyEvent &event); EventHandlerResult onKeyEvent(KeyEvent &event);
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
private: private:
typedef enum { typedef enum {
@ -50,10 +52,10 @@ class EEPROMKeymapProgrammer : public kaleidoscope::Plugin {
WAIT_FOR_CODE, WAIT_FOR_CODE,
WAIT_FOR_SOURCE_KEY, WAIT_FOR_SOURCE_KEY,
} state_t; } state_t;
state_t state_; static state_t state_;
uint16_t update_position_; // layer, row, col static uint16_t update_position_; // layer, row, col
Key new_key_; static Key new_key_;
}; };
} // namespace plugin } // namespace plugin

@ -17,7 +17,7 @@
#include "kaleidoscope/plugin/EEPROM-Keymap.h" #include "kaleidoscope/plugin/EEPROM-Keymap.h"
#include <Arduino.h> // for PSTR, F, __FlashStringHelper #include <Arduino.h> // for PSTR, strcmp_P, F, __FlashStringHelper
#include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings #include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint8_t, uint16_t #include <stdint.h> // for uint8_t, uint16_t
@ -82,7 +82,7 @@ Key EEPROMKeymap::getKeyExtended(uint8_t layer, KeyAddr key_addr) {
return getKey(layer - progmem_layers_, key_addr); return getKey(layer - progmem_layers_, key_addr);
} }
uint16_t EEPROMKeymap::keymap_base() { uint16_t EEPROMKeymap::keymap_base(void) {
return keymap_base_; return keymap_base_;
} }
@ -101,15 +101,14 @@ void EEPROMKeymap::dumpKeymap(uint8_t layers, Key (*getkey)(uint8_t, KeyAddr)) {
} }
} }
EventHandlerResult EEPROMKeymap::onFocusEvent(const char *input) { EventHandlerResult EEPROMKeymap::onFocusEvent(const char *command) {
const char *cmd_custom = PSTR("keymap.custom"); if (::Focus.handleHelp(command, PSTR("keymap.custom\nkeymap.default\nkeymap.onlyCustom")))
const char *cmd_default = PSTR("keymap.default"); return EventHandlerResult::OK;
const char *cmd_onlyCustom = PSTR("keymap.onlyCustom");
if (::Focus.inputMatchesHelp(input)) if (strncmp_P(command, PSTR("keymap."), 7) != 0)
return ::Focus.printHelp(cmd_custom, cmd_default, cmd_onlyCustom); return EventHandlerResult::OK;
if (::Focus.inputMatchesCommand(input, cmd_onlyCustom)) { if (strcmp_P(command + 7, PSTR("onlyCustom")) == 0) {
if (::Focus.isEOL()) { if (::Focus.isEOL()) {
::Focus.send((uint8_t)::EEPROMSettings.ignoreHardcodedLayers()); ::Focus.send((uint8_t)::EEPROMSettings.ignoreHardcodedLayers());
} else { } else {
@ -129,7 +128,7 @@ EventHandlerResult EEPROMKeymap::onFocusEvent(const char *input) {
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
if (::Focus.inputMatchesCommand(input, cmd_default)) { if (strcmp_P(command + 7, PSTR("default")) == 0) {
// By using a cast to the appropriate function type, // By using a cast to the appropriate function type,
// tell the compiler which overload of getKeyFromPROGMEM // tell the compiler which overload of getKeyFromPROGMEM
// we actully want. // we actully want.
@ -139,7 +138,7 @@ EventHandlerResult EEPROMKeymap::onFocusEvent(const char *input) {
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
if (!::Focus.inputMatchesCommand(input, cmd_custom)) if (strcmp_P(command + 7, PSTR("custom")) != 0)
return EventHandlerResult::OK; return EventHandlerResult::OK;
if (::Focus.isEOL()) { if (::Focus.isEOL()) {

@ -33,15 +33,17 @@ class EEPROMKeymap : public kaleidoscope::Plugin {
EXTEND EXTEND
}; };
EEPROMKeymap(void) {}
EventHandlerResult onSetup(); EventHandlerResult onSetup();
EventHandlerResult onNameQuery(); EventHandlerResult onNameQuery();
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
static void setup(uint8_t max); static void setup(uint8_t max);
static void max_layers(uint8_t max); static void max_layers(uint8_t max);
static uint16_t keymap_base(); static uint16_t keymap_base(void);
static Key getKey(uint8_t layer, KeyAddr key_addr); static Key getKey(uint8_t layer, KeyAddr key_addr);
static Key getKeyExtended(uint8_t layer, KeyAddr key_addr); static Key getKeyExtended(uint8_t layer, KeyAddr key_addr);
@ -53,7 +55,7 @@ class EEPROMKeymap : public kaleidoscope::Plugin {
static uint8_t max_layers_; static uint8_t max_layers_;
static uint8_t progmem_layers_; static uint8_t progmem_layers_;
static Key parseKey(); static Key parseKey(void);
static void printKey(Key key); static void printKey(Key key);
static void dumpKeymap(uint8_t layers, Key (*getkey)(uint8_t, KeyAddr)); static void dumpKeymap(uint8_t layers, Key (*getkey)(uint8_t, KeyAddr));
}; };

@ -17,7 +17,7 @@
#include "kaleidoscope/plugin/EEPROM-Settings.h" #include "kaleidoscope/plugin/EEPROM-Settings.h"
#include <Arduino.h> // for PSTR, F, __FlashStringHelper #include <Arduino.h> // for PSTR, strcmp_P, F, __FlashStringHelper
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint16_t, uint8_t #include <stdint.h> // for uint16_t, uint8_t
@ -30,6 +30,11 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
struct EEPROMSettings::settings EEPROMSettings::settings_;
bool EEPROMSettings::is_valid_;
bool EEPROMSettings::sealed_;
uint16_t EEPROMSettings::next_start_ = sizeof(EEPROMSettings::settings);
EventHandlerResult EEPROMSettings::onSetup() { EventHandlerResult EEPROMSettings::onSetup() {
Runtime.storage().get(0, settings_); Runtime.storage().get(0, settings_);
@ -65,11 +70,11 @@ EventHandlerResult EEPROMSettings::beforeEachCycle() {
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
bool EEPROMSettings::isValid() { bool EEPROMSettings::isValid(void) {
return is_valid_; return is_valid_;
} }
uint16_t EEPROMSettings::crc() { uint16_t EEPROMSettings::crc(void) {
if (sealed_) if (sealed_)
return settings_.crc; return settings_.crc;
return 0; return 0;
@ -100,7 +105,7 @@ void EEPROMSettings::ignoreHardcodedLayers(bool value) {
update(); update();
} }
void EEPROMSettings::seal() { void EEPROMSettings::seal(void) {
sealed_ = true; sealed_ = true;
CRCCalculator.finalize(); CRCCalculator.finalize();
@ -141,22 +146,22 @@ uint16_t EEPROMSettings::requestSlice(uint16_t size) {
return start; return start;
} }
void EEPROMSettings::invalidate() { void EEPROMSettings::invalidate(void) {
is_valid_ = false; is_valid_ = false;
} }
uint16_t EEPROMSettings::used() { uint16_t EEPROMSettings::used(void) {
return next_start_; return next_start_;
} }
void EEPROMSettings::update() { void EEPROMSettings::update(void) {
Runtime.storage().put(0, settings_); Runtime.storage().put(0, settings_);
Runtime.storage().commit(); Runtime.storage().commit();
is_valid_ = true; is_valid_ = true;
} }
/** Focus **/ /** Focus **/
EventHandlerResult FocusSettingsCommand::onFocusEvent(const char *input) { EventHandlerResult FocusSettingsCommand::onFocusEvent(const char *command) {
enum { enum {
DEFAULT_LAYER, DEFAULT_LAYER,
IS_VALID, IS_VALID,
@ -164,21 +169,19 @@ EventHandlerResult FocusSettingsCommand::onFocusEvent(const char *input) {
GET_CRC, GET_CRC,
} sub_command; } sub_command;
const char *cmd_defaultLayer = PSTR("settings.defaultLayer"); if (::Focus.handleHelp(command, PSTR("settings.defaultLayer\nsettings.valid?\nsettings.version\nsettings.crc")))
const char *cmd_isValid = PSTR("settings.valid?"); return EventHandlerResult::OK;
const char *cmd_version = PSTR("settings.version");
const char *cmd_crc = PSTR("settings.crc");
if (::Focus.inputMatchesHelp(input)) if (strncmp_P(command, PSTR("settings."), 9) != 0)
return ::Focus.printHelp(cmd_defaultLayer, cmd_isValid, cmd_version, cmd_crc); return EventHandlerResult::OK;
if (::Focus.inputMatchesCommand(input, cmd_defaultLayer)) if (strcmp_P(command + 9, PSTR("defaultLayer")) == 0)
sub_command = DEFAULT_LAYER; sub_command = DEFAULT_LAYER;
else if (::Focus.inputMatchesCommand(input, cmd_isValid)) else if (strcmp_P(command + 9, PSTR("valid?")) == 0)
sub_command = IS_VALID; sub_command = IS_VALID;
else if (::Focus.inputMatchesCommand(input, cmd_version)) else if (strcmp_P(command + 9, PSTR("version")) == 0)
sub_command = GET_VERSION; sub_command = GET_VERSION;
else if (::Focus.inputMatchesCommand(input, cmd_crc)) else if (strcmp_P(command + 9, PSTR("crc")) == 0)
sub_command = GET_CRC; sub_command = GET_CRC;
else else
return EventHandlerResult::OK; return EventHandlerResult::OK;
@ -208,25 +211,21 @@ EventHandlerResult FocusSettingsCommand::onFocusEvent(const char *input) {
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
EventHandlerResult FocusEEPROMCommand::onFocusEvent(const char *input) { EventHandlerResult FocusEEPROMCommand::onFocusEvent(const char *command) {
enum { enum {
CONTENTS, CONTENTS,
FREE, FREE,
ERASE, ERASE,
} sub_command; } sub_command;
const char *cmd_contents = PSTR("eeprom.contents"); if (::Focus.handleHelp(command, PSTR("eeprom.contents\neeprom.free\neeprom.erase")))
const char *cmd_free = PSTR("eeprom.free"); return EventHandlerResult::OK;
const char *cmd_erase = PSTR("eeprom.erase");
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd_contents, cmd_free, cmd_erase);
if (::Focus.inputMatchesCommand(input, cmd_contents)) if (strcmp_P(command, PSTR("eeprom.contents")) == 0)
sub_command = CONTENTS; sub_command = CONTENTS;
else if (::Focus.inputMatchesCommand(input, cmd_free)) else if (strcmp_P(command, PSTR("eeprom.free")) == 0)
sub_command = FREE; sub_command = FREE;
else if (::Focus.inputMatchesCommand(input, cmd_erase)) else if (strcmp_P(command, PSTR("eeprom.erase")) == 0)
sub_command = ERASE; sub_command = ERASE;
else else
return EventHandlerResult::OK; return EventHandlerResult::OK;

@ -24,17 +24,10 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
class EEPROMSettings : public kaleidoscope::Plugin { class EEPROMSettings : public kaleidoscope::Plugin {
private:
struct Settings {
uint8_t default_layer : 7;
bool ignore_hardcoded_layers : 1;
uint8_t version;
uint16_t crc;
};
public: public:
EEPROMSettings(void) {}
EventHandlerResult onSetup(); EventHandlerResult onSetup();
EventHandlerResult beforeEachCycle(); EventHandlerResult beforeEachCycle();
@ -53,45 +46,53 @@ class EEPROMSettings : public kaleidoscope::Plugin {
* fall back to not using it. */ * fall back to not using it. */
static constexpr uint8_t VERSION_CURRENT = 0x01; static constexpr uint8_t VERSION_CURRENT = 0x01;
void update(); static void update(void);
bool isValid(); static bool isValid(void);
void invalidate(); static void invalidate(void);
uint8_t version() { static uint8_t version(void) {
return settings_.version; return settings_.version;
} }
uint16_t requestSlice(uint16_t size); static uint16_t requestSlice(uint16_t size);
void seal(); static void seal(void);
uint16_t crc(); static uint16_t crc(void);
uint16_t used(); static uint16_t used(void);
uint8_t default_layer(uint8_t layer); static uint8_t default_layer(uint8_t layer);
uint8_t default_layer() { static uint8_t default_layer() {
return settings_.default_layer; return settings_.default_layer;
} }
void ignoreHardcodedLayers(bool value); static void ignoreHardcodedLayers(bool value);
bool ignoreHardcodedLayers() { static bool ignoreHardcodedLayers() {
return settings_.ignore_hardcoded_layers; return settings_.ignore_hardcoded_layers;
} }
private: private:
static constexpr uint8_t IGNORE_HARDCODED_LAYER = 0x7e; static constexpr uint8_t IGNORE_HARDCODED_LAYER = 0x7e;
static uint16_t next_start_;
static bool is_valid_;
static bool sealed_;
uint16_t next_start_ = sizeof(EEPROMSettings::Settings); static struct settings {
bool is_valid_; uint8_t default_layer : 7;
bool sealed_; bool ignore_hardcoded_layers : 1;
uint8_t version;
Settings settings_; uint16_t crc;
} settings_;
}; };
class FocusSettingsCommand : public kaleidoscope::Plugin { class FocusSettingsCommand : public kaleidoscope::Plugin {
public: public:
EventHandlerResult onFocusEvent(const char *input); FocusSettingsCommand() {}
EventHandlerResult onFocusEvent(const char *command);
}; };
class FocusEEPROMCommand : public kaleidoscope::Plugin { class FocusEEPROMCommand : public kaleidoscope::Plugin {
public: public:
EventHandlerResult onFocusEvent(const char *input); FocusEEPROMCommand() {}
EventHandlerResult onFocusEvent(const char *command);
}; };
} // namespace plugin } // namespace plugin

@ -34,8 +34,10 @@ class CRC_ {
public: public:
uint16_t crc = 0; uint16_t crc = 0;
CRC_(void){};
void update(const void *data, uint8_t len); void update(const void *data, uint8_t len);
void finalize() { void finalize(void) {
reflect(16); reflect(16);
} }
void reflect(uint8_t len); void reflect(uint8_t len);

@ -17,9 +17,10 @@
#include "kaleidoscope/plugin/Escape-OneShot.h" // IWYU pragma: associated #include "kaleidoscope/plugin/Escape-OneShot.h" // IWYU pragma: associated
#include <Arduino.h> // for PSTR, F, __FlashStringHelper #include <Arduino.h> // for PSTR, F, __FlashStringHelper, strcmp_P
#include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings #include <Kaleidoscope-EEPROM-Settings.h> // for EEPROMSettings
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint16_t
#include "kaleidoscope/Runtime.h" // for Runtime, Runtime_ #include "kaleidoscope/Runtime.h" // for Runtime, Runtime_
#include "kaleidoscope/device/device.h" // for VirtualProps::Storage, Base<>::Storage #include "kaleidoscope/device/device.h" // for VirtualProps::Storage, Base<>::Storage
@ -29,18 +30,20 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
uint16_t EscapeOneShotConfig::settings_base_;
EventHandlerResult EscapeOneShotConfig::onSetup() { EventHandlerResult EscapeOneShotConfig::onSetup() {
settings_base_ = ::EEPROMSettings.requestSlice(sizeof(EscapeOneShot::settings_)); settings_base_ = ::EEPROMSettings.requestSlice(sizeof(EscapeOneShot::settings_));
if (Runtime.storage().isSliceUninitialized( if (Runtime.storage().isSliceUninitialized(
settings_base_, settings_base_,
sizeof(EscapeOneShot::Settings))) { sizeof(EscapeOneShot::settings_))) {
// If our slice is uninitialized, set sensible defaults. // If our slice is uninitialized, set sensible defaults.
Runtime.storage().put(settings_base_, ::EscapeOneShot.settings_); Runtime.storage().put(settings_base_, EscapeOneShot::settings_);
Runtime.storage().commit(); Runtime.storage().commit();
} }
Runtime.storage().get(settings_base_, ::EscapeOneShot.settings_); Runtime.storage().get(settings_base_, EscapeOneShot::settings_);
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
@ -48,12 +51,11 @@ EventHandlerResult EscapeOneShotConfig::onNameQuery() {
return ::Focus.sendName(F("EscapeOneShot")); return ::Focus.sendName(F("EscapeOneShot"));
} }
EventHandlerResult EscapeOneShotConfig::onFocusEvent(const char *input) { EventHandlerResult EscapeOneShotConfig::onFocusEvent(const char *command) {
const char *cmd_cancel_key = PSTR("escape_oneshot.cancel_key"); if (::Focus.handleHelp(command, PSTR("escape_oneshot.cancel_key")))
if (::Focus.inputMatchesHelp(input)) return EventHandlerResult::OK;
return ::Focus.printHelp(cmd_cancel_key);
if (!::Focus.inputMatchesCommand(input, cmd_cancel_key)) if (strcmp_P(command, PSTR("escape_oneshot.cancel_key")) != 0)
return EventHandlerResult::OK; return EventHandlerResult::OK;
if (::Focus.isEOL()) { if (::Focus.isEOL()) {
@ -64,7 +66,7 @@ EventHandlerResult EscapeOneShotConfig::onFocusEvent(const char *input) {
::EscapeOneShot.setCancelKey(k); ::EscapeOneShot.setCancelKey(k);
} }
Runtime.storage().put(settings_base_, ::EscapeOneShot.settings_); Runtime.storage().put(settings_base_, EscapeOneShot::settings_);
Runtime.storage().commit(); Runtime.storage().commit();
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }

@ -21,12 +21,15 @@
#include "kaleidoscope/KeyEvent.h" // for KeyEvent #include "kaleidoscope/KeyEvent.h" // for KeyEvent
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult, EventHandlerResult::E... #include "kaleidoscope/event_handler_result.h" // for EventHandlerResult, EventHandlerResult::E...
#include "kaleidoscope/key_defs.h" // for Key, Key_NoKey #include "kaleidoscope/key_defs.h" // for Key, Key_Escape, Key_NoKey
#include "kaleidoscope/keyswitch_state.h" // for keyIsInjected, keyToggledOn #include "kaleidoscope/keyswitch_state.h" // for keyIsInjected, keyToggledOn
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
EscapeOneShot::Settings EscapeOneShot::settings_ = {
.cancel_oneshot_key = Key_Escape};
EventHandlerResult EscapeOneShot::onKeyEvent(KeyEvent &event) { EventHandlerResult EscapeOneShot::onKeyEvent(KeyEvent &event) {
// We only act on an escape key (or `cancel_oneshot_key_`, if that has been // We only act on an escape key (or `cancel_oneshot_key_`, if that has been
// set) that has just been pressed, and not generated by some other // set) that has just been pressed, and not generated by some other

@ -22,7 +22,7 @@
#include "kaleidoscope/KeyEvent.h" // for KeyEvent #include "kaleidoscope/KeyEvent.h" // for KeyEvent
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult #include "kaleidoscope/event_handler_result.h" // for EventHandlerResult
#include "kaleidoscope/key_defs.h" // for Key, Key_Escape #include "kaleidoscope/key_defs.h" // for Key
#include "kaleidoscope/plugin.h" // for Plugin #include "kaleidoscope/plugin.h" // for Plugin
// DEPRECATED: `OneShotCancelKey` doesn't match our normal naming, and should // DEPRECATED: `OneShotCancelKey` doesn't match our normal naming, and should
@ -35,12 +35,14 @@ namespace plugin {
class EscapeOneShot : public kaleidoscope::Plugin { class EscapeOneShot : public kaleidoscope::Plugin {
public: public:
EscapeOneShot(void) {}
EventHandlerResult onKeyEvent(KeyEvent &event); EventHandlerResult onKeyEvent(KeyEvent &event);
void setCancelKey(Key cancel_key) { static void setCancelKey(Key cancel_key) {
settings_.cancel_oneshot_key = cancel_key; settings_.cancel_oneshot_key = cancel_key;
} }
Key getCancelKey() { static Key getCancelKey() {
return settings_.cancel_oneshot_key; return settings_.cancel_oneshot_key;
} }
@ -50,17 +52,17 @@ class EscapeOneShot : public kaleidoscope::Plugin {
struct Settings { struct Settings {
Key cancel_oneshot_key; Key cancel_oneshot_key;
}; };
Settings settings_ = {.cancel_oneshot_key = Key_Escape}; static Settings settings_;
}; };
class EscapeOneShotConfig : public Plugin { class EscapeOneShotConfig : public Plugin {
public: public:
EventHandlerResult onSetup(); EventHandlerResult onSetup();
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
EventHandlerResult onNameQuery(); EventHandlerResult onNameQuery();
private: private:
uint16_t settings_base_; static uint16_t settings_base_;
}; };
} // namespace plugin } // namespace plugin

@ -1,6 +1,6 @@
/* -*- mode: c++ -*- /* -*- mode: c++ -*-
* Kaleidoscope-FingerPainter -- On-the-fly keyboard painting. * Kaleidoscope-FingerPainter -- On-the-fly keyboard painting.
* Copyright (C) 2017-2022 Keyboard.io, Inc * Copyright (C) 2017-2021 Keyboard.io, Inc
* *
* This program is free software: you can redistribute it and/or modify it under * This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software * the terms of the GNU General Public License as published by the Free Software
@ -17,7 +17,7 @@
#include "kaleidoscope/plugin/FingerPainter.h" #include "kaleidoscope/plugin/FingerPainter.h"
#include <Arduino.h> // for PSTR, F, __FlashStringHelper #include <Arduino.h> // for PSTR, strcmp_P, F, __FlashStringHelper
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <Kaleidoscope-LED-Palette-Theme.h> // for LEDPaletteTheme #include <Kaleidoscope-LED-Palette-Theme.h> // for LEDPaletteTheme
#include <stdint.h> // for uint16_t, uint8_t #include <stdint.h> // for uint16_t, uint8_t
@ -33,6 +33,9 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
uint16_t FingerPainter::color_base_;
bool FingerPainter::edit_mode_;
EventHandlerResult FingerPainter::onNameQuery() { EventHandlerResult FingerPainter::onNameQuery() {
return ::Focus.sendName(F("FingerPainter")); return ::Focus.sendName(F("FingerPainter"));
} }
@ -42,7 +45,7 @@ EventHandlerResult FingerPainter::onSetup() {
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
void FingerPainter::update() { void FingerPainter::update(void) {
::LEDPaletteTheme.updateHandler(color_base_, 0); ::LEDPaletteTheme.updateHandler(color_base_, 0);
} }
@ -50,7 +53,7 @@ void FingerPainter::refreshAt(KeyAddr key_addr) {
::LEDPaletteTheme.refreshAt(color_base_, 0, key_addr); ::LEDPaletteTheme.refreshAt(color_base_, 0, key_addr);
} }
void FingerPainter::toggle() { void FingerPainter::toggle(void) {
edit_mode_ = !edit_mode_; edit_mode_ = !edit_mode_;
} }
@ -89,26 +92,25 @@ EventHandlerResult FingerPainter::onKeyEvent(KeyEvent &event) {
::LEDPaletteTheme.updateColorIndexAtPosition(color_base_, ::LEDPaletteTheme.updateColorIndexAtPosition(color_base_,
Runtime.device().getLedIndex(event.addr), Runtime.device().getLedIndex(event.addr),
color_index); color_index);
Runtime.storage().commit();
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
EventHandlerResult FingerPainter::onFocusEvent(const char *input) { EventHandlerResult FingerPainter::onFocusEvent(const char *command) {
enum { enum {
TOGGLE, TOGGLE,
CLEAR, CLEAR,
} sub_command; } sub_command;
const char *cmd_toggle = PSTR("fingerpainter.toggle"); if (::Focus.handleHelp(command, PSTR("fingerpainter.toggle\nfingerpainter.clear")))
const char *cmd_clear = PSTR("fingerpainter.clear"); return EventHandlerResult::OK;
if (::Focus.inputMatchesHelp(input)) if (strncmp_P(command, PSTR("fingerpainter."), 14) != 0)
return ::Focus.printHelp(cmd_toggle, cmd_clear); return EventHandlerResult::OK;
if (::Focus.inputMatchesCommand(input, cmd_toggle)) if (strcmp_P(command + 14, PSTR("toggle")) == 0)
sub_command = TOGGLE; sub_command = TOGGLE;
else if (::Focus.inputMatchesCommand(input, cmd_clear)) else if (strcmp_P(command + 14, PSTR("clear")) == 0)
sub_command = CLEAR; sub_command = CLEAR;
else else
return EventHandlerResult::OK; return EventHandlerResult::OK;

@ -33,20 +33,22 @@ namespace plugin {
// //
class FingerPainter : public LEDMode { class FingerPainter : public LEDMode {
public: public:
void toggle(); FingerPainter(void) {}
static void toggle(void);
EventHandlerResult onKeyEvent(KeyEvent &event); EventHandlerResult onKeyEvent(KeyEvent &event);
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
EventHandlerResult onSetup(); EventHandlerResult onSetup();
EventHandlerResult onNameQuery(); EventHandlerResult onNameQuery();
protected: protected:
void update() final; void update(void) final;
void refreshAt(KeyAddr key_addr) final; void refreshAt(KeyAddr key_addr) final;
private: private:
uint16_t color_base_; static uint16_t color_base_;
bool edit_mode_; static bool edit_mode_;
}; };
} // namespace plugin } // namespace plugin

@ -50,13 +50,13 @@ EventHandlerResult FirmwareDump::onSetup() {
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
EventHandlerResult FirmwareDump::onFocusEvent(const char *input) { EventHandlerResult FirmwareDump::onFocusEvent(const char *command) {
const char *cmd = PSTR("firmware.dump"); const char *cmd = PSTR("firmware.dump");
if (::Focus.inputMatchesHelp(input)) if (::Focus.handleHelp(command, cmd))
return ::Focus.printHelp(cmd); return EventHandlerResult::OK;
if (!::Focus.inputMatchesCommand(input, cmd)) if (strcmp_P(command, cmd) != 0)
return EventHandlerResult::OK; return EventHandlerResult::OK;
uint16_t flash_size = (FLASHEND + 1L); uint16_t flash_size = (FLASHEND + 1L);

@ -33,8 +33,10 @@ namespace plugin {
class FirmwareDump : public kaleidoscope::Plugin { class FirmwareDump : public kaleidoscope::Plugin {
public: public:
FirmwareDump() {}
EventHandlerResult onSetup(); EventHandlerResult onSetup();
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
private: private:
uint16_t bootloader_size_; uint16_t bootloader_size_;

@ -1,36 +0,0 @@
# FirmwareVersion
Implements a new focus command - version - that simply prints the version set up
at compile time.
## Using the plugin
To use the plugin, first define the version to be printed, then include the
header, and activate the plugin.
```c++
#define KALEIDOSCOPE_FIRMWARE_VERSION "0.1.2"
#include <Kaleidoscope.h>
#include <Kaleidoscope-FirmwareVersion.h>
#include <Kaleidoscope-FocusSerial.h>
KALEIDOSCOPE_INIT_PLUGINS(Focus,
FirmwareVersion);
void setup () {
Kaleidoscope.setup ();
}
```
## Focus commands
The plugin provides a single Focus command: `version`.
### `version`
> Prints the version configured at build time.
## Dependencies
* [Kaleidoscope-FocusSerial](Kaleidoscope-FocusSerial.md)

@ -1,7 +0,0 @@
name=Kaleidoscope-FirmwareVersion
version=0.0.0
sentence=Provides a Focus command to print a preconfigured version
maintainer=Kaleidoscope's Developers <jesse@keyboard.io>
url=https://github.com/keyboardio/Kaleidoscope
author=Keyboardio
paragraph=

@ -1,20 +0,0 @@
/* -*- mode: c++ -*-
* Kaleidoscope-FirmwareVersion -- Provides a Focus command to print a version
* Copyright (C) 2022 Keyboard.io, Inc
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "kaleidoscope/plugin/FirmwareVersion.h" // IWYU pragma: export

@ -1,56 +0,0 @@
/* -*- mode: c++ -*-
* Kaleidoscope-FirmwareVersion -- Provides a Focus command to print a version
* Copyright (C) 2022 Keyboard.io, Inc
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef KALEIDOSCOPE_FIRMWARE_VERSION
#define KALEIDOSCOPE_FIRMWARE_VERSION "0.0.0"
#endif
#include <Arduino.h> // for PSTR, F, __FlashStringHelper
#include "Kaleidoscope-FocusSerial.h" // for Focus, FocusSerial
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult
#include "kaleidoscope/plugin.h" // for Plugin
namespace kaleidoscope {
namespace plugin {
class FirmwareVersion : public Plugin {
public:
EventHandlerResult onFocusEvent(const char *input) {
const char *cmd_version = PSTR("version");
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd_version);
if (!::Focus.inputMatchesCommand(input, cmd_version))
return EventHandlerResult::OK;
#ifdef KALEIDOSCOPE_FIRMWARE_VERSION
::Focus.send(F(KALEIDOSCOPE_FIRMWARE_VERSION));
#else
::Focus.send(F("0.0.0"));
#endif
return EventHandlerResult::OK;
}
};
} // namespace plugin
} // namespace kaleidoscope
kaleidoscope::plugin::FirmwareVersion FirmwareVersion;

@ -20,17 +20,14 @@ Nevertheless, a very simple example is shown below:
namespace kaleidoscope { namespace kaleidoscope {
class FocusTestCommand : public Plugin { class FocusTestCommand : public Plugin {
public: public:
FocusTestCommand() {}
EventHandlerResult onNameQuery() { EventHandlerResult onNameQuery() {
return ::Focus.sendName(F("FocusTestCommand")); return ::Focus.sendName(F("FocusTestCommand"));
} }
EventHandlerResult onFocusEvent(const char *input) { EventHandlerResult onFocusEvent(const char *command) {
const char *cmd = PSTR("test"); if (strcmp_P(command, PSTR("test")) != 0)
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd);
if (!::Focus.inputMatchesCommand(input, cmd))
return EventHandlerResult::OK; return EventHandlerResult::OK;
::Focus.send(F("Congratulations, the test command works!")); ::Focus.send(F("Congratulations, the test command works!"));
@ -52,18 +49,6 @@ void setup () {
The plugin provides the `Focus` object, with a couple of helper methods aimed at developers. Terminating the response with a dot on its own line is handled implicitly by `FocusSerial`, one does not need to do that explicitly. The plugin provides the `Focus` object, with a couple of helper methods aimed at developers. Terminating the response with a dot on its own line is handled implicitly by `FocusSerial`, one does not need to do that explicitly.
### `.inputMatchesHelp(input)`
Returns `true` if the given `input` matches the `help` command. To be used at the top of `onFocusEvent()`, followed by `.printHelp(...)`.
### `.printHelp(...)`
Given a series of strings (stored in `PROGMEM`, via `PSTR()`), prints them one per line. Assumes it is run as part of handling the `help` command. Returns `EventHandlerResult::OK`.
### `.inputMatchesCommand(input, command)`
Returns `true` if the `input` matches the expected `command`, false otherwise. A convenience function over `strcmp_P()`.
### `.send(...)` ### `.send(...)`
### `.sendRaw(...)` ### `.sendRaw(...)`

@ -19,6 +19,7 @@
#include <Arduino.h> // for PSTR, __FlashStringHelper, F, strcmp_P #include <Arduino.h> // for PSTR, __FlashStringHelper, F, strcmp_P
#include <HardwareSerial.h> // for HardwareSerial #include <HardwareSerial.h> // for HardwareSerial
#include <stdint.h> // for uint8_t
#include <string.h> // for memset #include <string.h> // for memset
#include "kaleidoscope/Runtime.h" // for Runtime, Runtime_ #include "kaleidoscope/Runtime.h" // for Runtime, Runtime_
@ -32,8 +33,10 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
char FocusSerial::command_[32];
uint8_t FocusSerial::buf_cursor_ = 0;
EventHandlerResult FocusSerial::afterEachCycle() { EventHandlerResult FocusSerial::afterEachCycle() {
int c;
// GD32 doesn't currently autoflush the very last packet. So manually flush here // GD32 doesn't currently autoflush the very last packet. So manually flush here
Runtime.serialPort().flush(); Runtime.serialPort().flush();
// If the serial buffer is empty, we don't have any work to do // If the serial buffer is empty, we don't have any work to do
@ -42,28 +45,33 @@ EventHandlerResult FocusSerial::afterEachCycle() {
} }
do { do {
// If there's a newline pending, don't read it command_[buf_cursor_++] = Runtime.serialPort().read();
if (Runtime.serialPort().peek() == NEWLINE) { } while (command_[buf_cursor_ - 1] != SEPARATOR && buf_cursor_ < sizeof(command_) && Runtime.serialPort().available() && (Runtime.serialPort().peek() != NEWLINE));
break;
}
c = Runtime.serialPort().read();
// Don't store the separator; just stash it
if (c == SEPARATOR) {
break;
}
input_[buf_cursor_++] = c;
} while (buf_cursor_ < (sizeof(input_) - 1) && Runtime.serialPort().available());
if ((c != SEPARATOR) && (Runtime.serialPort().peek() != NEWLINE) && buf_cursor_ < (sizeof(input_) - 1)) { // If there was no command, there's nothing to do
if (command_[0] == '\0') {
buf_cursor_ = 0;
memset(command_, 0, sizeof(command_));
return EventHandlerResult::OK;
}
if ((command_[buf_cursor_ - 1] != SEPARATOR) && (Runtime.serialPort().peek() != NEWLINE) && buf_cursor_ < sizeof(command_)) {
// We don't have enough command to work with yet. // We don't have enough command to work with yet.
// Let's leave the buffer around for another cycle // Let's leave the buffer around for another cycle
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
// If this was a command with a space-delimited payload,
// strip the space delimiter off
if ((command_[buf_cursor_ - 1] == SEPARATOR)) {
command_[buf_cursor_ - 1] = '\0';
}
// Then process the command // Then process the command
Runtime.onFocusEvent(input_); Runtime.onFocusEvent(command_);
while (Runtime.serialPort().available()) { while (Runtime.serialPort().available()) {
c = Runtime.serialPort().read(); char c = Runtime.serialPort().read();
if (c == NEWLINE) { if (c == NEWLINE) {
// newline serves as an end-of-command marker // newline serves as an end-of-command marker
// don't drain the buffer past there // don't drain the buffer past there
@ -73,23 +81,28 @@ EventHandlerResult FocusSerial::afterEachCycle() {
// End of command processing is signalled with a CRLF followed by a single period // End of command processing is signalled with a CRLF followed by a single period
Runtime.serialPort().println(F("\r\n.")); Runtime.serialPort().println(F("\r\n."));
buf_cursor_ = 0; buf_cursor_ = 0;
memset(input_, 0, sizeof(input_)); memset(command_, 0, sizeof(command_));
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
EventHandlerResult FocusSerial::onFocusEvent(const char *input) { bool FocusSerial::handleHelp(const char *command,
const char *cmd_help = PSTR("help"); const char *help_message) {
const char *cmd_reset = PSTR("device.reset"); if (strcmp_P(command, PSTR("help")) != 0)
const char *cmd_plugins = PSTR("plugins"); return false;
Runtime.serialPort().println((const __FlashStringHelper *)help_message);
return true;
}
if (inputMatchesHelp(input)) EventHandlerResult FocusSerial::onFocusEvent(const char *command) {
return printHelp(cmd_help, cmd_reset, cmd_plugins); if (handleHelp(command, PSTR("help\ndevice.reset\nplugins")))
return EventHandlerResult::OK;
if (inputMatchesCommand(input, cmd_reset)) { if (strcmp_P(command, PSTR("device.reset")) == 0) {
Runtime.device().rebootBootloader(); Runtime.device().rebootBootloader();
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
if (inputMatchesCommand(input, cmd_plugins)) { if (strcmp_P(command, PSTR("plugins")) == 0) {
kaleidoscope::Hooks::onNameQuery(); kaleidoscope::Hooks::onNameQuery();
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
@ -97,27 +110,10 @@ EventHandlerResult FocusSerial::onFocusEvent(const char *input) {
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
#ifndef NDEPRECATED
bool FocusSerial::handleHelp(const char *input, const char *help_message) {
if (!inputMatchesHelp(input)) return false;
printHelp(help_message);
return true;
}
#endif
void FocusSerial::printBool(bool b) { void FocusSerial::printBool(bool b) {
Runtime.serialPort().print((b) ? F("true") : F("false")); Runtime.serialPort().print((b) ? F("true") : F("false"));
} }
bool FocusSerial::inputMatchesHelp(const char *input) {
return inputMatchesCommand(input, PSTR("help"));
}
bool FocusSerial::inputMatchesCommand(const char *input, const char *expected) {
return strcmp_P(input, expected) == 0;
}
} // namespace plugin } // namespace plugin
} // namespace kaleidoscope } // namespace kaleidoscope

@ -26,15 +26,6 @@
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult, EventHandlerResult::OK #include "kaleidoscope/event_handler_result.h" // for EventHandlerResult, EventHandlerResult::OK
#include "kaleidoscope/key_defs.h" // for Key #include "kaleidoscope/key_defs.h" // for Key
#include "kaleidoscope/plugin.h" // for Plugin #include "kaleidoscope/plugin.h" // for Plugin
// -----------------------------------------------------------------------------
// Deprecation warning messages
#include "kaleidoscope_internal/deprecations.h" // for DEPRECATED
#define _DEPRECATED_MESSAGE_FOCUS_HANDLEHELP \
"The `Focus.handleHelp()` method is deprecated. Please use\n" \
"`Focus.inputMatchesHelp()` and `Focus.printHelp()` instead.\n" \
"This method will be removed after 2022-12-26."
// -----------------------------------------------------------------------------
// IWYU pragma: no_include "WString.h" // IWYU pragma: no_include "WString.h"
@ -42,32 +33,19 @@ namespace kaleidoscope {
namespace plugin { namespace plugin {
class FocusSerial : public kaleidoscope::Plugin { class FocusSerial : public kaleidoscope::Plugin {
public: public:
FocusSerial(void) {}
static constexpr char COMMENT = '#'; static constexpr char COMMENT = '#';
static constexpr char SEPARATOR = ' '; static constexpr char SEPARATOR = ' ';
static constexpr char NEWLINE = '\n'; static constexpr char NEWLINE = '\n';
#ifndef NDEPRECATED bool handleHelp(const char *command,
DEPRECATED(FOCUS_HANDLEHELP) const char *help_message);
bool handleHelp(const char *input, const char *help_message);
#endif
bool inputMatchesHelp(const char *input);
bool inputMatchesCommand(const char *input, const char *expected);
EventHandlerResult printHelp() {
return EventHandlerResult::OK;
}
template<typename... Vars>
EventHandlerResult printHelp(const char *h1, Vars... vars) {
Runtime.serialPort().println((const __FlashStringHelper *)h1);
delayAfterPrint();
return printHelp(vars...);
}
EventHandlerResult sendName(const __FlashStringHelper *name) { EventHandlerResult sendName(const __FlashStringHelper *name) {
Runtime.serialPort().print(name); Runtime.serialPort().print(name);
delayAfterPrint(); delayAfterPrint();
Runtime.serialPort().println(); Runtime.serialPort().print(NEWLINE);
delayAfterPrint(); delayAfterPrint();
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
@ -118,9 +96,6 @@ class FocusSerial : public kaleidoscope::Plugin {
color.g = Runtime.serialPort().parseInt(); color.g = Runtime.serialPort().parseInt();
color.b = Runtime.serialPort().parseInt(); color.b = Runtime.serialPort().parseInt();
} }
void read(char &c) {
Runtime.serialPort().readBytes(&c, 1);
}
void read(uint8_t &u8) { void read(uint8_t &u8) {
u8 = Runtime.serialPort().parseInt(); u8 = Runtime.serialPort().parseInt();
} }
@ -137,18 +112,18 @@ class FocusSerial : public kaleidoscope::Plugin {
/* Hooks */ /* Hooks */
EventHandlerResult afterEachCycle(); EventHandlerResult afterEachCycle();
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
private: private:
char input_[32]; static char command_[32];
uint8_t buf_cursor_ = 0; static uint8_t buf_cursor_;
void printBool(bool b); static void printBool(bool b);
// This is a hacky workaround for the host seemingly dropping characters // This is a hacky workaround for the host seemingly dropping characters
// when a client spams its serial port too quickly // when a client spams its serial port too quickly
// Verified on GD32 and macOS 12.3 2022-03-29 // Verified on GD32 and macOS 12.3 2022-03-29
static constexpr uint8_t focus_delay_us_after_character_ = 100; static constexpr uint8_t focus_delay_us_after_character_ = 100;
void delayAfterPrint() { delayMicroseconds(focus_delay_us_after_character_); } static void delayAfterPrint() { delayMicroseconds(focus_delay_us_after_character_); }
}; };
} // namespace plugin } // namespace plugin

@ -28,8 +28,12 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
const GhostInTheFirmware::GhostKey *GhostInTheFirmware::ghost_keys;
bool GhostInTheFirmware::is_active_ = false;
uint16_t GhostInTheFirmware::current_pos_ = 0;
uint16_t GhostInTheFirmware::start_time_;
void GhostInTheFirmware::activate() { void GhostInTheFirmware::activate(void) {
is_active_ = true; is_active_ = true;
} }

@ -32,16 +32,18 @@ class GhostInTheFirmware : public kaleidoscope::Plugin {
uint16_t press_time; uint16_t press_time;
uint16_t delay; uint16_t delay;
}; };
const GhostKey *ghost_keys; static const GhostKey *ghost_keys;
void activate(); GhostInTheFirmware(void) {}
static void activate(void);
EventHandlerResult afterEachCycle(); EventHandlerResult afterEachCycle();
private: private:
bool is_active_ = false; static bool is_active_;
uint16_t current_pos_ = 0; static uint16_t current_pos_;
uint16_t start_time_; static uint16_t start_time_;
}; };
} // namespace plugin } // namespace plugin

@ -170,7 +170,7 @@ struct RaiseProps : kaleidoscope::device::BaseProps {
typedef RaiseKeyScanner KeyScanner; typedef RaiseKeyScanner KeyScanner;
typedef RaiseStorageProps StorageProps; typedef RaiseStorageProps StorageProps;
typedef kaleidoscope::driver::storage::Flash<StorageProps> Storage; typedef kaleidoscope::driver::storage::Flash<StorageProps> Storage;
typedef kaleidoscope::driver::bootloader::samd::Bossac Bootloader; typedef kaleidoscope::driver::bootloader::samd::Bossac BootLoader;
typedef RaiseSideFlasherProps SideFlasherProps; typedef RaiseSideFlasherProps SideFlasherProps;
typedef kaleidoscope::util::flasher::KeyboardioI2CBootloader<SideFlasherProps> SideFlasher; typedef kaleidoscope::util::flasher::KeyboardioI2CBootloader<SideFlasherProps> SideFlasher;

@ -33,37 +33,24 @@ namespace raise {
#define RAISE_FIRMWARE_VERSION "<unknown>" #define RAISE_FIRMWARE_VERSION "<unknown>"
#endif #endif
EventHandlerResult Focus::onFocusEvent(const char *input) { EventHandlerResult Focus::onFocusEvent(const char *command) {
const char *cmd_version = PSTR("hardware.version"); if (::Focus.handleHelp(command, PSTR("hardware.version\nhardware.side_power\nhardware.side_ver\nhardware.sled_ver\nhardware.sled_current\nhardware.layout\nhardware.joint\nhardware.keyscan\nhardware.crc_errors\nhardware.firmware")))
const char *cmd_side_power = PSTR("hardware.side_power"); return EventHandlerResult::OK;
const char *cmd_side_ver = PSTR("hardware.side_ver");
const char *cmd_sled_ver = PSTR("hardware.sled_ver"); if (strncmp_P(command, PSTR("hardware."), 9) != 0)
const char *cmd_sled_current = PSTR("hardware.sled_current"); return EventHandlerResult::OK;
const char *cmd_layout = PSTR("hardware.layout");
const char *cmd_joint = PSTR("hardware.joint"); if (strcmp_P(command + 9, PSTR("version")) == 0) {
const char *cmd_keyscan = PSTR("hardware.keyscan");
const char *cmd_crc_errors = PSTR("hardware.crc_errors");
const char *cmd_firmware = PSTR("hardware.firmware");
if (::Focus.inputMatchesHelp(input))
return ::Focus.printHelp(cmd_version,
cmd_side_power,
cmd_side_ver,
cmd_sled_ver,
cmd_sled_current,
cmd_layout,
cmd_joint,
cmd_keyscan,
cmd_crc_errors,
cmd_firmware);
if (::Focus.inputMatchesCommand(input, cmd_version)) {
::Focus.send("Dygma Raise"); ::Focus.send("Dygma Raise");
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else if (::Focus.inputMatchesCommand(input, cmd_firmware)) { }
if (strcmp_P(command + 9, PSTR("firmware")) == 0) {
::Focus.send(RAISE_FIRMWARE_VERSION); ::Focus.send(RAISE_FIRMWARE_VERSION);
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else if (::Focus.inputMatchesCommand(input, cmd_side_power)) { }
if (strcmp_P(command + 9, PSTR("side_power")) == 0) {
if (::Focus.isEOL()) { if (::Focus.isEOL()) {
::Focus.send(Runtime.device().side.getPower()); ::Focus.send(Runtime.device().side.getPower());
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
@ -73,29 +60,37 @@ EventHandlerResult Focus::onFocusEvent(const char *input) {
Runtime.device().side.setPower(power); Runtime.device().side.setPower(power);
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
} else if (::Focus.inputMatchesCommand(input, cmd_side_ver)) { }
if (strcmp_P(command + 9, PSTR("side_ver")) == 0) {
::Focus.send("left:"); ::Focus.send("left:");
::Focus.send(Runtime.device().side.leftVersion()); ::Focus.send(Runtime.device().side.leftVersion());
::Focus.send("\r\nright:"); ::Focus.send("\nright:");
::Focus.send(Runtime.device().side.rightVersion()); ::Focus.send(Runtime.device().side.rightVersion());
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else if (::Focus.inputMatchesCommand(input, cmd_crc_errors)) { }
if (strcmp_P(command + 9, PSTR("crc_errors")) == 0) {
::Focus.send("left:"); ::Focus.send("left:");
::Focus.send(Runtime.device().side.leftCRCErrors()); ::Focus.send(Runtime.device().side.leftCRCErrors());
::Focus.send("\r\nright:"); ::Focus.send("\nright:");
::Focus.send(Runtime.device().side.rightCRCErrors()); ::Focus.send(Runtime.device().side.rightCRCErrors());
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else if (::Focus.inputMatchesCommand(input, cmd_sled_ver)) { }
if (strcmp_P(command + 9, PSTR("sled_ver")) == 0) {
::Focus.send("left:"); ::Focus.send("left:");
::Focus.send(Runtime.device().side.leftSLEDVersion()); ::Focus.send(Runtime.device().side.leftSLEDVersion());
::Focus.send("\r\nright:"); ::Focus.send("\nright:");
::Focus.send(Runtime.device().side.rightSLEDVersion()); ::Focus.send(Runtime.device().side.rightSLEDVersion());
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else if (::Focus.inputMatchesCommand(input, cmd_sled_current)) { }
if (strcmp_P(command + 9, PSTR("sled_current")) == 0) {
if (::Focus.isEOL()) { if (::Focus.isEOL()) {
::Focus.send("left:"); ::Focus.send("left:");
::Focus.send(Runtime.device().side.leftSLEDCurrent()); ::Focus.send(Runtime.device().side.leftSLEDCurrent());
::Focus.send("\r\nright:"); ::Focus.send("\nright:");
::Focus.send(Runtime.device().side.rightSLEDCurrent()); ::Focus.send(Runtime.device().side.rightSLEDCurrent());
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else { } else {
@ -104,14 +99,20 @@ EventHandlerResult Focus::onFocusEvent(const char *input) {
Runtime.device().side.setSLEDCurrent(current); Runtime.device().side.setSLEDCurrent(current);
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} }
} else if (::Focus.inputMatchesCommand(input, cmd_layout)) { }
if (strcmp_P(command + 9, PSTR("layout")) == 0) {
static const auto ANSI = Runtime.device().settings.Layout::ANSI; static const auto ANSI = Runtime.device().settings.Layout::ANSI;
::Focus.send(Runtime.device().settings.layout() == ANSI ? "ANSI" : "ISO"); ::Focus.send(Runtime.device().settings.layout() == ANSI ? "ANSI" : "ISO");
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else if (::Focus.inputMatchesCommand(input, cmd_joint)) { }
if (strcmp_P(command + 9, PSTR("joint")) == 0) {
::Focus.send(Runtime.device().settings.joint()); ::Focus.send(Runtime.device().settings.joint());
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;
} else if (::Focus.inputMatchesCommand(input, cmd_keyscan)) { }
if (strcmp_P(command + 9, PSTR("keyscan")) == 0) {
if (::Focus.isEOL()) { if (::Focus.isEOL()) {
::Focus.send(Runtime.device().settings.keyscanInterval()); ::Focus.send(Runtime.device().settings.keyscanInterval());
return EventHandlerResult::EVENT_CONSUMED; return EventHandlerResult::EVENT_CONSUMED;

@ -29,7 +29,7 @@ namespace raise {
class Focus : public kaleidoscope::Plugin { class Focus : public kaleidoscope::Plugin {
public: public:
EventHandlerResult onFocusEvent(const char *input); EventHandlerResult onFocusEvent(const char *command);
}; };
} // namespace raise } // namespace raise

@ -34,14 +34,12 @@ class SideFlash : public kaleidoscope::Plugin {
_Firmware firmware; _Firmware firmware;
public: public:
EventHandlerResult onFocusEvent(const char *input) { EventHandlerResult onFocusEvent(const char *command) {
const char *cmd_flash_left = PSTR("hardware.flash_left_side"); if (::Focus.handleHelp(command, PSTR("hardware.flash_left_side\nhardware.flash_right_side\nhardware.verify_left_side\nhardware.verify_right_side")))
const char *cmd_flash_right = PSTR("hardware.flash_right_side"); return EventHandlerResult::OK;
const char *cmd_verify_left = PSTR("hardware.verify_left_side");
const char *cmd_verify_right = PSTR("hardware.verify_right_side");
if (::Focus.inputMatchesHelp(input)) if (strncmp_P(command, PSTR("hardware."), 9) != 0)
return ::Focus.printHelp(cmd_flash_left, cmd_flash_right, cmd_verify_left, cmd_verify_right); return EventHandlerResult::OK;
auto sideFlasher = Runtime.device().sideFlasher(); auto sideFlasher = Runtime.device().sideFlasher();
uint8_t left_boot_address = Runtime.device().side.left_boot_address; uint8_t left_boot_address = Runtime.device().side.left_boot_address;
@ -52,16 +50,16 @@ class SideFlash : public kaleidoscope::Plugin {
} sub_command; } sub_command;
uint8_t address = 0; uint8_t address = 0;
if (::Focus.inputMatchesCommand(input, cmd_flash_left)) { if (strcmp_P(command + 9, PSTR("flash_left_side")) == 0) {
sub_command = FLASH; sub_command = FLASH;
address = left_boot_address; address = left_boot_address;
} else if (::Focus.inputMatchesCommand(input, cmd_flash_right)) { } else if (strcmp_P(command + 9, PSTR("flash_right_side")) == 0) {
sub_command = FLASH; sub_command = FLASH;
address = right_boot_address; address = right_boot_address;
} else if (::Focus.inputMatchesCommand(input, cmd_verify_left)) { } else if (strcmp_P(command + 9, PSTR("verify_left_side")) == 0) {
sub_command = VERIFY; sub_command = VERIFY;
address = left_boot_address; address = left_boot_address;
} else if (::Focus.inputMatchesCommand(input, cmd_verify_right)) { } else if (strcmp_P(command + 9, PSTR("verify_right_side")) == 0) {
sub_command = VERIFY; sub_command = VERIFY;
address = right_boot_address; address = right_boot_address;
} else { } else {

@ -38,9 +38,15 @@ namespace kaleidoscope {
namespace device { namespace device {
namespace ez { namespace ez {
ErgoDoxScanner ErgoDox::scanner_;
uint8_t ErgoDox::previousKeyState_[matrix_rows];
uint8_t ErgoDox::keyState_[matrix_rows];
uint8_t ErgoDox::debounce_matrix_[matrix_rows][matrix_columns];
uint8_t ErgoDox::debounce = 5;
static bool do_scan_ = 1; static bool do_scan_ = 1;
void ErgoDox::setup() { void ErgoDox::setup(void) {
wdt_disable(); wdt_disable();
delay(100); delay(100);

@ -60,9 +60,11 @@ struct ErgoDoxProps : public kaleidoscope::device::ATmega32U4KeyboardProps {
#ifndef KALEIDOSCOPE_VIRTUAL_BUILD #ifndef KALEIDOSCOPE_VIRTUAL_BUILD
class ErgoDox : public kaleidoscope::device::ATmega32U4Keyboard<ErgoDoxProps> { class ErgoDox : public kaleidoscope::device::ATmega32U4Keyboard<ErgoDoxProps> {
public: public:
void scanMatrix(); ErgoDox(void) {}
void readMatrix();
void actOnMatrixScan(); void scanMatrix(void);
void readMatrix(void);
void actOnMatrixScan(void);
void setup(); void setup();
bool isKeyswitchPressed(KeyAddr key_addr); bool isKeyswitchPressed(KeyAddr key_addr);
@ -78,17 +80,17 @@ class ErgoDox : public kaleidoscope::device::ATmega32U4Keyboard<ErgoDoxProps> {
void setStatusLED(uint8_t led, bool state = true); void setStatusLED(uint8_t led, bool state = true);
void setStatusLEDBrightness(uint8_t led, uint8_t brightness); void setStatusLEDBrightness(uint8_t led, uint8_t brightness);
uint8_t debounce = 5; static uint8_t debounce;
private: private:
ErgoDoxScanner scanner_; static ErgoDoxScanner scanner_;
uint8_t previousKeyState_[matrix_rows]; // NOLINT(runtime/arrays) static uint8_t previousKeyState_[matrix_rows];
uint8_t keyState_[matrix_rows]; // NOLINT(runtime/arrays) static uint8_t keyState_[matrix_rows];
uint8_t debounce_matrix_[matrix_rows][matrix_columns]; static uint8_t debounce_matrix_[matrix_rows][matrix_columns];
uint8_t debounceMaskForRow(uint8_t row); static uint8_t debounceMaskForRow(uint8_t row);
void debounceRow(uint8_t change, uint8_t row); static void debounceRow(uint8_t change, uint8_t row);
void readMatrixRow(uint8_t row); static void readMatrixRow(uint8_t row);
}; };
#else // ifndef KALEIDOSCOPE_VIRTUAL_BUILD #else // ifndef KALEIDOSCOPE_VIRTUAL_BUILD
class ErgoDox; class ErgoDox;

@ -35,6 +35,8 @@ namespace ez {
class ErgoDoxScanner { class ErgoDoxScanner {
public: public:
ErgoDoxScanner() {}
void begin(); void begin();
void toggleATMegaRow(int row); void toggleATMegaRow(int row);
void selectExtenderRow(int row); void selectExtenderRow(int row);

@ -37,7 +37,7 @@ struct EvalProps : kaleidoscope::device::BaseProps {
typedef kaleidoscope::driver::hid::KeyboardioProps HIDProps; typedef kaleidoscope::driver::hid::KeyboardioProps HIDProps;
typedef kaleidoscope::driver::hid::Keyboardio<HIDProps> HID; typedef kaleidoscope::driver::hid::Keyboardio<HIDProps> HID;
typedef kaleidoscope::driver::bootloader::gd32::Base Bootloader; typedef kaleidoscope::driver::bootloader::gd32::Base BootLoader;
typedef EvalStorageProps StorageProps; typedef EvalStorageProps StorageProps;
typedef kaleidoscope::driver::storage::GD32Flash<StorageProps> Storage; typedef kaleidoscope::driver::storage::GD32Flash<StorageProps> Storage;

@ -45,7 +45,7 @@ struct AtreusProps : kaleidoscope::device::ATmega32U4KeyboardProps {
}; };
typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner; typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner;
typedef kaleidoscope::driver::bootloader::avr::Caterina Bootloader; typedef kaleidoscope::driver::bootloader::avr::Caterina BootLoader;
static constexpr const char *short_name = "atreus"; static constexpr const char *short_name = "atreus";
}; };

@ -102,7 +102,7 @@ void ImagoLEDDriver::twiSend(uint8_t addr, uint8_t Reg_Add, uint8_t Reg_Dat) {
uint8_t result = twi_writeTo(addr, data, ELEMENTS(data), 1, 0); uint8_t result = twi_writeTo(addr, data, ELEMENTS(data), 1, 0);
} }
void ImagoLEDDriver::unlockRegister() { void ImagoLEDDriver::unlockRegister(void) {
twiSend(LED_DRIVER_ADDR, CMD_WRITE_ENABLE, WRITE_ENABLE_ONCE); //unlock twiSend(LED_DRIVER_ADDR, CMD_WRITE_ENABLE, WRITE_ENABLE_ONCE); //unlock
} }

@ -99,7 +99,7 @@ struct ImagoProps : kaleidoscope::device::ATmega32U4KeyboardProps {
typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner; typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner;
typedef ImagoLEDDriverProps LEDDriverProps; typedef ImagoLEDDriverProps LEDDriverProps;
typedef ImagoLEDDriver LEDDriver; typedef ImagoLEDDriver LEDDriver;
typedef kaleidoscope::driver::bootloader::avr::Caterina Bootloader; typedef kaleidoscope::driver::bootloader::avr::Caterina BootLoader;
static constexpr const char *short_name = "imago"; static constexpr const char *short_name = "imago";
}; };

@ -56,7 +56,7 @@ struct Model01Hands {
driver::keyboardio::Model01Side Model01Hands::leftHand(0); driver::keyboardio::Model01Side Model01Hands::leftHand(0);
driver::keyboardio::Model01Side Model01Hands::rightHand(3); driver::keyboardio::Model01Side Model01Hands::rightHand(3);
void Model01Hands::setup() { void Model01Hands::setup(void) {
// This lets the keyboard pull up to 1.6 amps from the host. // This lets the keyboard pull up to 1.6 amps from the host.
// That violates the USB spec. But it sure is pretty looking // That violates the USB spec. But it sure is pretty looking
DDRE |= _BV(6); DDRE |= _BV(6);
@ -149,7 +149,7 @@ driver::keyboardio::keydata_t Model01KeyScanner::rightHandState;
driver::keyboardio::keydata_t Model01KeyScanner::previousLeftHandState; driver::keyboardio::keydata_t Model01KeyScanner::previousLeftHandState;
driver::keyboardio::keydata_t Model01KeyScanner::previousRightHandState; driver::keyboardio::keydata_t Model01KeyScanner::previousRightHandState;
void Model01KeyScanner::enableScannerPower() { void Model01KeyScanner::enableScannerPower(void) {
// Turn on power to the LED net // Turn on power to the LED net
DDRC |= _BV(7); DDRC |= _BV(7);
PORTC |= _BV(7); PORTC |= _BV(7);

@ -126,7 +126,7 @@ struct Model01Props : public kaleidoscope::device::ATmega32U4KeyboardProps {
typedef Model01LEDDriver LEDDriver; typedef Model01LEDDriver LEDDriver;
typedef Model01KeyScannerProps KeyScannerProps; typedef Model01KeyScannerProps KeyScannerProps;
typedef Model01KeyScanner KeyScanner; typedef Model01KeyScanner KeyScanner;
typedef kaleidoscope::driver::bootloader::avr::Caterina Bootloader; typedef kaleidoscope::driver::bootloader::avr::Caterina BootLoader;
static constexpr const char *short_name = "kbio01"; static constexpr const char *short_name = "kbio01";
}; };

@ -44,7 +44,7 @@ struct Model100Hands {
driver::keyboardio::Model100Side Model100Hands::leftHand(0); driver::keyboardio::Model100Side Model100Hands::leftHand(0);
driver::keyboardio::Model100Side Model100Hands::rightHand(3); driver::keyboardio::Model100Side Model100Hands::rightHand(3);
void Model100Hands::setup() { void Model100Hands::setup(void) {
Model100KeyScanner::enableScannerPower(); Model100KeyScanner::enableScannerPower();
Wire.begin(); Wire.begin();
Wire.setClock(400000); Wire.setClock(400000);
@ -123,7 +123,7 @@ driver::keyboardio::keydata_t Model100KeyScanner::rightHandState;
driver::keyboardio::keydata_t Model100KeyScanner::previousLeftHandState; driver::keyboardio::keydata_t Model100KeyScanner::previousLeftHandState;
driver::keyboardio::keydata_t Model100KeyScanner::previousRightHandState; driver::keyboardio::keydata_t Model100KeyScanner::previousRightHandState;
void Model100KeyScanner::enableScannerPower() { void Model100KeyScanner::enableScannerPower(void) {
// Turn on the switched 5V network. // Turn on the switched 5V network.
// make sure this happens at least 100ms after USB connect // make sure this happens at least 100ms after USB connect
// to satisfy inrush limits // to satisfy inrush limits
@ -137,7 +137,7 @@ void Model100KeyScanner::enableScannerPower() {
digitalWrite(PB15, LOW); digitalWrite(PB15, LOW);
} }
void Model100KeyScanner::disableScannerPower() { void Model100KeyScanner::disableScannerPower(void) {
// Turn on power to the 5V net // Turn on power to the 5V net
// //
pinMode(PB9, OUTPUT_OPEN_DRAIN); pinMode(PB9, OUTPUT_OPEN_DRAIN);

@ -141,7 +141,7 @@ struct Model100Props : public kaleidoscope::device::BaseProps {
typedef Model100StorageProps StorageProps; typedef Model100StorageProps StorageProps;
typedef kaleidoscope::driver::storage::GD32Flash<StorageProps> Storage; typedef kaleidoscope::driver::storage::GD32Flash<StorageProps> Storage;
typedef kaleidoscope::driver::bootloader::gd32::Base Bootloader; typedef kaleidoscope::driver::bootloader::gd32::Base BootLoader;
static constexpr const char *short_name = "kbio100"; static constexpr const char *short_name = "kbio100";
typedef kaleidoscope::driver::mcu::GD32Props MCUProps; typedef kaleidoscope::driver::mcu::GD32Props MCUProps;

@ -214,7 +214,6 @@ void Model100Side::sendLEDData() {
} }
} }
auto constexpr gamma8 = kaleidoscope::driver::color::gamma_correction;
void Model100Side::sendLEDBank(uint8_t bank) { void Model100Side::sendLEDBank(uint8_t bank) {
uint8_t data[LED_BYTES_PER_BANK + 1]; uint8_t data[LED_BYTES_PER_BANK + 1];
@ -230,25 +229,25 @@ void Model100Side::sendLEDBank(uint8_t bank) {
else else
c = 0; c = 0;
data[i + 1] = pgm_read_byte(&gamma8[c]); data[i + 1] = c;
} }
uint8_t result = writeData(data, ELEMENTS(data)); uint8_t result = writeData(data, ELEMENTS(data));
} }
void Model100Side::setAllLEDsTo(cRGB color) { void Model100Side::setAllLEDsTo(cRGB color) {
uint8_t data[] = {TWI_CMD_LED_SET_ALL_TO, uint8_t data[] = {TWI_CMD_LED_SET_ALL_TO,
pgm_read_byte(&gamma8[color.b]), color.b,
pgm_read_byte(&gamma8[color.g]), color.g,
pgm_read_byte(&gamma8[color.r])}; color.r};
uint8_t result = writeData(data, ELEMENTS(data)); uint8_t result = writeData(data, ELEMENTS(data));
} }
void Model100Side::setOneLEDTo(uint8_t led, cRGB color) { void Model100Side::setOneLEDTo(uint8_t led, cRGB color) {
uint8_t data[] = {TWI_CMD_LED_SET_ONE_TO, uint8_t data[] = {TWI_CMD_LED_SET_ONE_TO,
led, led,
pgm_read_byte(&gamma8[color.b]), color.b,
pgm_read_byte(&gamma8[color.g]), color.g,
pgm_read_byte(&gamma8[color.r])}; color.r};
uint8_t result = writeData(data, ELEMENTS(data)); uint8_t result = writeData(data, ELEMENTS(data));
} }

@ -53,7 +53,7 @@ struct SplitographyProps : kaleidoscope::device::ATmega32U4KeyboardProps {
#endif // KALEIDOSCOPE_VIRTUAL_BUILD #endif // KALEIDOSCOPE_VIRTUAL_BUILD
}; };
typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner; typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner;
typedef kaleidoscope::driver::bootloader::avr::FLIP Bootloader; typedef kaleidoscope::driver::bootloader::avr::FLIP BootLoader;
static constexpr const char *short_name = "splitography"; static constexpr const char *short_name = "splitography";
}; };

@ -67,9 +67,9 @@ struct AtreusProps : kaleidoscope::device::ATmega32U4KeyboardProps {
typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner; typedef kaleidoscope::driver::keyscanner::ATmega<KeyScannerProps> KeyScanner;
#ifdef KALEIDOSCOPE_HARDWARE_ATREUS_PINOUT_LEGACY_TEENSY2 #ifdef KALEIDOSCOPE_HARDWARE_ATREUS_PINOUT_LEGACY_TEENSY2
typedef kaleidoscope::driver::bootloader::avr::HalfKay Bootloader; typedef kaleidoscope::driver::bootloader::avr::HalfKay BootLoader;
#else #else
typedef kaleidoscope::driver::bootloader::avr::Caterina Bootloader; typedef kaleidoscope::driver::bootloader::avr::Caterina BootLoader;
#endif #endif
static constexpr const char *short_name = "atreus"; static constexpr const char *short_name = "atreus";
}; };

@ -53,7 +53,7 @@ void HardwareTestMode::setLeds(cRGB color) {
waitForKeypress(); waitForKeypress();
} }
void HardwareTestMode::testLeds() { void HardwareTestMode::testLeds(void) {
constexpr cRGB red = CRGB(255, 0, 0); constexpr cRGB red = CRGB(255, 0, 0);
constexpr cRGB blue = CRGB(0, 0, 255); constexpr cRGB blue = CRGB(0, 0, 255);
constexpr cRGB green = CRGB(0, 255, 0); constexpr cRGB green = CRGB(0, 255, 0);

@ -33,6 +33,8 @@ class HardwareTestMode : public kaleidoscope::Plugin {
} chatter_data; } chatter_data;
static uint8_t actionKey; static uint8_t actionKey;
HardwareTestMode(void) {}
static void runTests(); static void runTests();
static void setActionKey(uint8_t key); static void setActionKey(uint8_t key);

@ -41,13 +41,13 @@ uint8_t Heatmap::heat_colors_length = 4;
// number of millisecond to wait between each heatmap computation // number of millisecond to wait between each heatmap computation
uint16_t Heatmap::update_delay = 1000; uint16_t Heatmap::update_delay = 1000;
uint16_t Heatmap::highest_ = 1;
uint16_t Heatmap::heatmap_[];
Heatmap::TransientLEDMode::TransientLEDMode(const Heatmap *parent) Heatmap::TransientLEDMode::TransientLEDMode(const Heatmap *parent)
: // last heatmap computation time : // store the number of times each key has been strock
last_heatmap_comp_time_(Runtime.millisAtCycleStart()), heatmap_{},
parent_(parent) {} // max of heatmap_ (we divide by it so we start at 1)
highest_(1),
// last heatmap computation time
last_heatmap_comp_time_(Runtime.millisAtCycleStart()) {}
cRGB Heatmap::TransientLEDMode::computeColor(float v) { cRGB Heatmap::TransientLEDMode::computeColor(float v) {
// compute the color corresponding to a value between 0 and 1 // compute the color corresponding to a value between 0 and 1
@ -107,21 +107,21 @@ cRGB Heatmap::TransientLEDMode::computeColor(float v) {
return {b, g, r}; return {b, g, r};
} }
void Heatmap::TransientLEDMode::shiftStats() { void Heatmap::TransientLEDMode::shiftStats(void) {
// this method is called when: // this method is called when:
// 1. a value in heatmap_ reach INT8_MAX // 1. a value in heatmap_ reach INT8_MAX
// 2. highest_ reach heat_colors_length*512 (see Heatmap::loopHook) // 2. highest_ reach heat_colors_length*512 (see Heatmap::loopHook)
// we divide every heatmap element by 2 // we divide every heatmap element by 2
for (auto key_addr : KeyAddr::all()) { for (auto key_addr : KeyAddr::all()) {
parent_->heatmap_[key_addr.toInt()] = parent_->heatmap_[key_addr.toInt()] >> 1; heatmap_[key_addr.toInt()] = heatmap_[key_addr.toInt()] >> 1;
} }
// and also divide highest_ accordingly // and also divide highest_ accordingly
parent_->highest_ = parent_->highest_ >> 1; highest_ = highest_ >> 1;
} }
void Heatmap::resetMap() { void Heatmap::resetMap(void) {
if (::LEDControl.get_mode_index() != led_mode_id_) if (::LEDControl.get_mode_index() != led_mode_id_)
return; return;
@ -134,10 +134,10 @@ void Heatmap::TransientLEDMode::resetMap() {
// this method can be used as a way to work around an existing bug with a single key // this method can be used as a way to work around an existing bug with a single key
// getting special attention or if the user just wants a button to reset the map // getting special attention or if the user just wants a button to reset the map
for (auto key_addr : KeyAddr::all()) { for (auto key_addr : KeyAddr::all()) {
parent_->heatmap_[key_addr.toInt()] = 0; heatmap_[key_addr.toInt()] = 0;
} }
parent_->highest_ = 1; highest_ = 1;
} }
// It may be better to use `onKeyswitchEvent()` here // It may be better to use `onKeyswitchEvent()` here
@ -167,17 +167,17 @@ EventHandlerResult Heatmap::onKeyEvent(KeyEvent &event) {
EventHandlerResult Heatmap::TransientLEDMode::onKeyEvent(KeyEvent &event) { EventHandlerResult Heatmap::TransientLEDMode::onKeyEvent(KeyEvent &event) {
// increment the heatmap_ value related to the key // increment the heatmap_ value related to the key
parent_->heatmap_[event.addr.toInt()]++; heatmap_[event.addr.toInt()]++;
// check highest_ // check highest_
if (parent_->highest_ < parent_->heatmap_[event.addr.toInt()]) { if (highest_ < heatmap_[event.addr.toInt()]) {
parent_->highest_ = parent_->heatmap_[event.addr.toInt()]; highest_ = heatmap_[event.addr.toInt()];
// if highest_ (and so heatmap_ value related to the key) // if highest_ (and so heatmap_ value related to the key)
// is close to overflow: call shiftStats // is close to overflow: call shiftStats
// NOTE: this is barely impossible since shiftStats should be // NOTE: this is barely impossible since shiftStats should be
// called much sooner by Heatmap::loopHook // called much sooner by Heatmap::loopHook
if (parent_->highest_ == INT16_MAX) if (highest_ == INT16_MAX)
shiftStats(); shiftStats();
} }
@ -204,13 +204,13 @@ EventHandlerResult Heatmap::TransientLEDMode::beforeEachCycle() {
// didn't lose any precision in our heatmap since between each color we have a // didn't lose any precision in our heatmap since between each color we have a
// maximum precision of 256 ; said differently, there is 256 state (at max) // maximum precision of 256 ; said differently, there is 256 state (at max)
// between heat_colors[x] and heat_colors[x+1]. // between heat_colors[x] and heat_colors[x+1].
if (parent_->highest_ > (static_cast<uint16_t>(heat_colors_length) << 9)) if (highest_ > (static_cast<uint16_t>(heat_colors_length) << 9))
shiftStats(); shiftStats();
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }
void Heatmap::TransientLEDMode::update() { void Heatmap::TransientLEDMode::update(void) {
if (!Runtime.has_leds) if (!Runtime.has_leds)
return; return;
@ -229,7 +229,7 @@ void Heatmap::TransientLEDMode::update() {
for (auto key_addr : KeyAddr::all()) { for (auto key_addr : KeyAddr::all()) {
// how much the key was pressed compared to the others (between 0 and 1) // how much the key was pressed compared to the others (between 0 and 1)
// (total_keys_ can't be equal to 0) // (total_keys_ can't be equal to 0)
float v = static_cast<float>(parent_->heatmap_[key_addr.toInt()]) / parent_->highest_; float v = static_cast<float>(heatmap_[key_addr.toInt()]) / highest_;
// we could have used an interger instead of a float, but then we would // we could have used an interger instead of a float, but then we would
// have had to change some multiplication in division. // have had to change some multiplication in division.
// / on uint is slower than * on float, so I stay with the float // / on uint is slower than * on float, so I stay with the float

@ -34,11 +34,12 @@ class Heatmap : public Plugin,
public LEDModeInterface, public LEDModeInterface,
public AccessTransientLEDMode { public AccessTransientLEDMode {
public: public:
Heatmap(void) {}
static uint16_t update_delay; static uint16_t update_delay;
static const cRGB *heat_colors; static const cRGB *heat_colors;
static uint8_t heat_colors_length; static uint8_t heat_colors_length;
void resetMap(void);
void resetMap();
EventHandlerResult onKeyEvent(KeyEvent &event); EventHandlerResult onKeyEvent(KeyEvent &event);
EventHandlerResult beforeEachCycle(); EventHandlerResult beforeEachCycle();
@ -61,18 +62,15 @@ class Heatmap : public Plugin,
void update() final; void update() final;
private: private:
uint16_t heatmap_[Runtime.device().numKeys()];
uint16_t highest_;
uint16_t last_heatmap_comp_time_; uint16_t last_heatmap_comp_time_;
const Heatmap *parent_;
void shiftStats(); void shiftStats(void);
cRGB computeColor(float v); cRGB computeColor(float v);
friend class Heatmap; friend class Heatmap;
}; };
private:
static uint16_t heatmap_[Runtime.device().numKeys()];
static uint16_t highest_;
}; };
} // namespace plugin } // namespace plugin

@ -21,7 +21,7 @@ The extension provides a `HostOS` singleton object.
#include <Kaleidoscope.h> #include <Kaleidoscope.h>
#include <Kaleidoscope-HostOS.h> #include <Kaleidoscope-HostOS.h>
void someFunction() { void someFunction(void) {
if (HostOS.os() == kaleidoscope::hostos::LINUX) { if (HostOS.os() == kaleidoscope::hostos::LINUX) {
// do something linux-y // do something linux-y
} }
@ -32,7 +32,7 @@ void someFunction() {
KALEIDOSCOPE_INIT_PLUGINS(HostOS) KALEIDOSCOPE_INIT_PLUGINS(HostOS)
void setup() { void setup(void) {
Kaleidoscope.setup (); Kaleidoscope.setup ();
} }
``` ```

@ -17,7 +17,7 @@
#include "kaleidoscope/plugin/HostOS-Focus.h" #include "kaleidoscope/plugin/HostOS-Focus.h"
#include <Arduino.h> // for PSTR #include <Arduino.h> // for PSTR, strcmp_P
#include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial #include <Kaleidoscope-FocusSerial.h> // for Focus, FocusSerial
#include <stdint.h> // for uint8_t #include <stdint.h> // for uint8_t
@ -27,13 +27,12 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
EventHandlerResult FocusHostOSCommand::onFocusEvent(const char *input) { EventHandlerResult FocusHostOSCommand::onFocusEvent(const char *command) {
const char *cmd = PSTR("hostos.type"); const char *cmd = PSTR("hostos.type");
if (::Focus.inputMatchesHelp(input)) if (::Focus.handleHelp(command, cmd))
return ::Focus.printHelp(cmd); return EventHandlerResult::OK;
if (strcmp_P(command, cmd) != 0)
if (!::Focus.inputMatchesCommand(input, cmd))
return EventHandlerResult::OK; return EventHandlerResult::OK;
if (::Focus.isEOL()) { if (::Focus.isEOL()) {

@ -25,7 +25,8 @@ namespace plugin {
class FocusHostOSCommand : public kaleidoscope::Plugin { class FocusHostOSCommand : public kaleidoscope::Plugin {
public: public:
EventHandlerResult onFocusEvent(const char *input); FocusHostOSCommand() {}
EventHandlerResult onFocusEvent(const char *command);
}; };
} // namespace plugin } // namespace plugin

@ -26,7 +26,7 @@
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
EventHandlerResult HostOS::onSetup() { EventHandlerResult HostOS::onSetup(void) {
if (is_configured_) if (is_configured_)
return EventHandlerResult::OK; return EventHandlerResult::OK;

@ -41,9 +41,10 @@ typedef enum {
class HostOS : public kaleidoscope::Plugin { class HostOS : public kaleidoscope::Plugin {
public: public:
HostOS() {}
EventHandlerResult onSetup(); EventHandlerResult onSetup();
hostos::Type os() { hostos::Type os(void) {
return os_; return os_;
} }
void os(hostos::Type new_os); void os(hostos::Type new_os);

@ -20,41 +20,39 @@
#include <Arduino.h> // IWYU pragma: keep #include <Arduino.h> // IWYU pragma: keep
#include <stdint.h> // for uint8_t #include <stdint.h> // for uint8_t
#ifdef ARDUINO_ARCH_GD32
#include "USBCore.h"
#endif
#include "kaleidoscope/event_handler_result.h" // for EventHandlerResult, EventHandlerResult::OK #include "kaleidoscope/event_handler_result.h" // for EventHandlerResult, EventHandlerResult::OK
// This is a terrible hack until Arduino#6964 gets implemented.
// It makes the `_usbSuspendState` symbol available to us.
extern uint8_t _usbSuspendState;
namespace kaleidoscope { namespace kaleidoscope {
namespace plugin { namespace plugin {
bool HostPowerManagement::was_suspended_ = false; bool HostPowerManagement::was_suspended_ = false;
bool HostPowerManagement::initial_suspend_ = true;
bool HostPowerManagement::isSuspended() {
#if defined(__AVR__)
return USBDevice.isSuspended();
#elif defined(ARDUINO_ARCH_GD32)
return USBCore().isSuspended();
#else
return false;
#endif
}
EventHandlerResult HostPowerManagement::beforeEachCycle() { EventHandlerResult HostPowerManagement::beforeEachCycle() {
if (isSuspended()) {
if (!was_suspended_) { #ifdef __AVR__
was_suspended_ = true; if ((_usbSuspendState & (1 << SUSPI))) {
hostPowerManagementEventHandler(Suspend); if (!initial_suspend_) {
} else { if (!was_suspended_) {
hostPowerManagementEventHandler(Sleep); was_suspended_ = true;
hostPowerManagementEventHandler(Suspend);
} else {
hostPowerManagementEventHandler(Sleep);
}
} }
} else { } else {
if (initial_suspend_)
initial_suspend_ = false;
if (was_suspended_) { if (was_suspended_) {
was_suspended_ = false; was_suspended_ = false;
hostPowerManagementEventHandler(Resume); hostPowerManagementEventHandler(Resume);
} }
} }
#endif
return EventHandlerResult::OK; return EventHandlerResult::OK;
} }

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save