1
0
Fork 0

Squashed 'tmk_core/' content from commit 05caacc

git-subtree-dir: tmk_core
git-subtree-split: 05caaccec92694bb24c8c3c3a9940b96efd4605c
This commit is contained in:
tmk 2015-04-10 01:32:04 +09:00
commit a074364c37
533 changed files with 102049 additions and 0 deletions

13
.gitignore vendored Normal file
View file

@ -0,0 +1,13 @@
.dep
*.o
*.eep
*.elf
*.hex
*.lss
*.lst
*.map
*.sym
tags
*~
build/
*.bak

6
.gitmodules vendored Normal file
View file

@ -0,0 +1,6 @@
[submodule "protocol/lufa/LUFA-git"]
path = protocol/lufa/LUFA-git
url = https://github.com/abcminiuser/lufa.git
[submodule "protocol/usb_hid/USB_Host_Shield_2.0"]
path = protocol/usb_hid/USB_Host_Shield_2.0
url = https://github.com/felis/USB_Host_Shield_2.0.git

296
README.md Normal file
View file

@ -0,0 +1,296 @@
TMK Keyboard Firmware Collection
================================
This is a keyboard firmware with some useful features for Atmel AVR controller.
Source code is available here: <http://github.com/tmk/tmk_keyboard>
Features
--------
These features can be used in your keyboard.
* Multi-layer Keymap - Multiple keyboard layouts with layer switching
* Mouse key - Mouse control with keyboard
* System Control Key - Power Down, Sleep, Wake Up and USB Remote Wake up
* Media Control Key - Volume Down/Up, Mute, Next/Prev track, Play, Stop and etc
* USB NKRO - 120 keys(+ 8 modifiers) simultaneously
* PS/2 mouse support - PS/2 mouse(TrackPoint) as composite device
* Keyboard protocols - PS/2, ADB, M0110, Sun and other old keyboard protocols
* User Function - Customizable function of key with writing code
* Macro - Very primitive at this time
* Keyboard Tricks - Oneshot modifier and modifier with tapping feature
* Debug Console - Messages for debug and interaction with firmware
* Virtual DIP Switch - Configurations stored EEPROM(Boot Magic)
* Locking CapsLock - Mechanical switch support for CapsLock
* Breathing Sleep LED - Sleep indicator with charm during USB suspend
* Backlight - Control backlight levels
Projects
--------
You can find some keyboard specific projects under `converter` and `keyboard` directory.
### converter
* [ps2_usb](converter/ps2_usb/) - [PS/2 keyboard to USB][GH_ps2]
* [adb_usb](converter/adb_usb/) - [ADB keyboard to USB][GH_adb]
* [m0110_usb](converter/m0110_usb) - [Macintosh 128K/512K/Plus keyboard to USB][GH_m0110]
* [terminal_usb](converter/terminal_usb/) - [IBM Model M terminal keyboard(PS/2 scancode set3) to USB][GH_terminal]
* [news_usb](converter/news_usb/) - [Sony NEWS keyboard to USB][GH_news]
* [x68k_usb](converter/x68k_usb/) - [Sharp X68000 keyboard to USB][GH_x68k]
* [sun_usb](converter/sun_usb/) - [Sun] to USB(type4, 5 and 3?)
* [pc98_usb](converter/pc98_usb/) - [PC98] to USB
* [usb_usb](converter/usb_usb/) - USB to USB(experimental)
* [ascii_usb](converter/ascii_usb/) - ASCII(Serial console terminal) to USB
* [ibm4704_usb](converter/ibm4704_usb) - [IBM 4704 keyboard Converter][GH_ibm4704]
### keyboard
* [hhkb](keyboard/hhkb/) - [Happy Hacking Keyboard pro][GH_hhkb] **my main board**
* [gh60](keyboard/gh60/) - [GH60] DIY 60% keyboard [prototype][GH60_proto] **my second board**
* [hbkb](keyboard/hbkb/) - [Happy Buckling spring keyboard][GH_hbkb](IBM Model M 60% mod)
* [hid_liber](keyboard/hid_liber/) - [HID liberation][HID_liber] controller (by alaricljs)
* [phantom](keyboard/phantom/) - [Phantom] keyboard (by Tranquilite)
* [IIgs_Standard](keyboard/IIgs/) - Apple [IIGS] keyboard mod(by JeffreySung)
* [macway](keyboard/macway/) - [Compact keyboard mod][GH_macway] [retired]
* [KMAC](keyboard/kmac/) - Korean custom keyboard
* [Lightsaber](keyboard/lightsaber/) - Korean custom keyboard
* [Infinity](keyboard/infinity/) - Massdrop [Infinity keyboard][Infinity]
* [NerD](keyboard/nerd/) - Korean custom keyboard
* [KittenPaw](keyboard/kitten_paw) - Custom Majestouch controller
* [Lightpad](keyboard/lightpad) - Korean custom keypad
* [ghost_squid](keyboard/ghost_squid/) - [The Ghost Squid][ghost_squid] controller for [Cooler Master QuickFire XT][cmxt]
### Extenal projects using tmk_keyboard
* [ErgoDox_cub-uanic][cub-uanic] - Split Ergonomic Keyboard [ErgoDox][ergodox_org]
* [mcdox][mcdox_tmk] - [mcdox][mcdox]
[GH_macway]: http://geekhack.org/showwiki.php?title=Island:11930
[GH_hhkb]: http://geekhack.org/showwiki.php?title=Island:12047
[GH_ps2]: http://geekhack.org/showwiki.php?title=Island:14618
[GH_adb]: http://geekhack.org/showwiki.php?title=Island:14290
[GH_hhkb_bt]: http://geekhack.org/showwiki.php?title=Island:20851
[GH_m0110]: http://geekhack.org/showwiki.php?title=Island:24965
[GH_news]: http://geekhack.org/showwiki.php?title=Island:25759
[GH_terminal]: http://geekhack.org/showwiki.php?title=Island:27272
[GH_x68k]: http://geekhack.org/showwiki.php?title=Island:29060
[GH_hbkb]: http://geekhack.org/showwiki.php?title=Island:29483
[GH_ibm4704]: http://geekhack.org/index.php?topic=54706.0
[HID_liber]: http://deskthority.net/wiki/HID_Liberation_Device_-_DIY_Instructions
[Phantom]: http://geekhack.org/index.php?topic=26742
[GH60]: http://geekhack.org/index.php?topic=34959
[GH60_proto]: http://geekhack.org/index.php?topic=37570.0
[PC98]: http://en.wikipedia.org/wiki/NEC_PC-9801
[Sun]: http://en.wikipedia.org/wiki/Sun-3
[IIGS]: http://en.wikipedia.org/wiki/Apple_IIGS
[Infinity]: https://www.massdrop.com/buy/infinity-keyboard-kit
[ghost_squid]: http://deskthority.net/wiki/Costar_replacement_controllers#The_Ghost_Squid
[cmxt]: http://gaming.coolermaster.com/en/products/keyboards/quickfirext/
[ergodox_org]: http://ergodox.org/
[cub-uanic]: https://github.com/cub-uanic/tmk_keyboard/tree/master/keyboard/ergodox
[mcdox]: https://github.com/DavidMcEwan/mcdox
[mcdox_tmk]: https://github.com/DavidMcEwan/tmk_keyboard/tree/master/keyboard/mcdox
License
-------
**GPLv2** or later. Some protocol files are under **Modified BSD License**.
LUFA, PJRC and V-USB stack have their own license respectively.
Build Firmware and Program Controller
-------------------------------------
See [doc/build.md](doc/build.md).
Change your keymap
------------------
See [doc/keymap.md](doc/keymap.md).
Magic Commands
--------------
To see help press `Magic` + `H`.
`Magic` key bind may be `LShift` + `RShift` in many project, but `Power` key on ADB converter. `Magic` keybind can be vary on each project, check `config.h` in project directory.
Following commands can be also executed with `Magic` + key. In console mode `Magic` keybind is not needed.
----- Command Help -----
c: enter console mode
d: toggle debug enable
x: toggle matrix debug
k: toggle keyboard debug
m: toggle mouse debug
v: print device version & info
t: print timer count
s: print status
e: print eeprom config
n: toggle NKRO
0/F10: switch to Layer0
1/F1: switch to Layer1
2/F2: switch to Layer2
3/F3: switch to Layer3
4/F4: switch to Layer4
PScr: power down/remote wake-up
Caps: Lock Keyboard(Child Proof)
Paus: jump to bootloader
**TBD**
### Boot Magic Configuration - Virtual DIP Switch
Boot Magic are executed during boot up time. Press Magic key below then plug in keyboard cable.
Note that you must use keys of **Layer 0** as Magic keys. These settings are stored in EEPROM so that retain your configure over power cycles.
To avoid configuring accidentally additive salt key `KC_SPACE` also needs to be pressed along with the following configuration keys. The salt key is configurable in `config.h`. See [common/bootmagic.h](common/bootmagic.h).
#### General
- Skip reading EEPROM to start with default configuration(`ESC`)
- Clear configuration stored in EEPROM to reset configuration(`Backspace`)
#### Bootloader
- Kick up Bootloader(`B`)
#### Debug
- Debug enable(`D`)
- Debug matrix enable(`D`+`X`)
- Debug keyboard enable(`D`+`K`)
- Debug mouse enable(`D`+`M`)
#### Keymap
- Swap Control and CapsLock(`Left Control`)
- Change CapsLock to Control(`Caps Lock`)
- Swap LeftAlt and Gui(`Left Alt`)
- Swap RightAlt and Gui(`Right Alt`)
- Disable Gui(`Left Gui`)
- Swap Grave and Escape(`Grave`)
- Swap BackSlash and BackSpace(`Back Slash`)
- Enable NKRO on boot(`N`)
#### Default Layer
- Set Default Layer to 0(`0`)
- Set Default Layer to 1(`1`)
- Set Default Layer to 2(`2`)
- Set Default Layer to 3(`3`)
- Set Default Layer to 4(`4`)
- Set Default Layer to 5(`5`)
- Set Default Layer to 6(`6`)
- Set Default Layer to 7(`7`)
#### Caution
Unintentional use of this feature will cause user confusion.
TODO: Magic key combination to avoid unintentional press during plug in
**TBD**
Mechanical Locking support
--------------------------
This feature makes it possible for you to use mechanical switch for `CapsLock`, `NumLock` or `ScrollLock`. To enable this feature define these macros in `config.h` and use `KC_LCAP`, `KC_LNUM` or `KC_LSCR` in keymap for locking key instead of normal `KC_CAPS`, `KC_NLCK` or `KC_SLCK`. Resync option tries to keep lock switch state consistent with keyboard LED state.
#define LOCKING_SUPPORT_ENABLE
#define LOCKING_RESYNC_ENABLE
Start Your Own Project
-----------------------
**TBD**
### Config.h Options
#### 1. USB vendor/product ID and device description
#define VENDOR_ID 0xFEED
#define PRODUCT_ID 0xBEEF
#define MANUFACTURER t.m.k.
#define PRODUCT Macway mod
#define DESCRIPTION t.m.k. keyboard firmware for Macway mod
#### 2. Keyboard matrix configuration
#define MATRIX_ROWS 8
#define MATRIX_COLS 8
#define MATRIX_HAS_GHOST
Architecture
------------
Architecture Diagram
+---------------+---------------+-------------+
| Host | Keyboard | Matrix, LED |
___________ |-----------+-+ +-------------+ | +-----------|
/ /| Keys/Mouse | Protocol |d| | Action | | | Protocol |
/__________/ |<-----------| LUFA |r| | Layer, Tap | | | Matrix |
|.--------.| | LED | V-USB |i| |-------------| | | PS/2,IBM | __________________
|| || |----------->| PJRC |v| | Keymap | | | ADB,M0110| Keys / /_/_/_/_/_/_/_/ /|
|| Host || | Console | iWRAP(BT)|e| | Mousekey | | | SUN/NEWS |<----------/ /_/_/_/_/_/_/_/ / /
||________||/.<-----------| UART |r| | Report | | | X68K/PC98| Control / /_/_/_/_/_/_/_/ / /
`_========_'/| |---------------------------------------------|-------->/___ /_______/ ___/ /
|_o______o_|/ | Sendchar, Print, Debug, Command, ... | |_________________|/
+---------------------------------------------+ Keyboard
Debugging
--------
Use PJRC's `hid_listen` to see debug messages. You can use the tool for debug even if firmware use LUFA stack.
You can use xprintf() to display debug info on `hid_listen`, see `common/xprintf.h`.
Files and Directories
-------------------
### Top
* common/ - common codes
* protocol/ - keyboard protocol support
* keyboard/ - keyboard projects
* converter/ - protocol converter projects
* doc/ - documents
* common.mk - Makefile for common
* protocol.mk - Makefile for protocol
* rules.mk - Makefile for build rules
### Common
* host.h
* host_driver.h
* keyboard.h
* command.h
* keymap.h
* action.h
* keycode.h
* matrix.h
* led.h
* mousekey.h
* report.h
* debug.h
* print.h
* bootloader.h
* sendchar.h
* timer.h
* util.h
### Keyboard Protocols
* lufa/ - LUFA USB stack
* pjrc/ - PJRC USB stack
* vusb/ - Objective Development V-USB
* iwrap/ - Bluetooth HID for Bluegiga iWRAP
* ps2.c - PS/2 protocol
* adb.c - Apple Desktop Bus protocol
* m0110.c - Macintosh 128K/512K/Plus keyboard protocol
* news.c - Sony NEWS keyboard protocol
* x68k.c - Sharp X68000 keyboard protocol
* serial_soft.c - Asynchronous Serial protocol implemented by software
Coding Style
-------------
- Doesn't use Tab to indent, use 4-spaces instead.
Other Keyboard Firmware Projects
------------------
You can learn a lot about keyboard firmware from these. See [doc/other_projects.md](doc/other_projects.md).

77
common.mk Normal file
View file

@ -0,0 +1,77 @@
COMMON_DIR = common
SRC += $(COMMON_DIR)/host.c \
$(COMMON_DIR)/keyboard.c \
$(COMMON_DIR)/action.c \
$(COMMON_DIR)/action_tapping.c \
$(COMMON_DIR)/action_macro.c \
$(COMMON_DIR)/action_layer.c \
$(COMMON_DIR)/action_util.c \
$(COMMON_DIR)/keymap.c \
$(COMMON_DIR)/print.c \
$(COMMON_DIR)/debug.c \
$(COMMON_DIR)/util.c \
$(COMMON_DIR)/avr/suspend.c \
$(COMMON_DIR)/avr/xprintf.S \
$(COMMON_DIR)/avr/timer.c \
$(COMMON_DIR)/avr/bootloader.c
# Option modules
ifdef BOOTMAGIC_ENABLE
SRC += $(COMMON_DIR)/bootmagic.c
SRC += $(COMMON_DIR)/avr/eeconfig.c
OPT_DEFS += -DBOOTMAGIC_ENABLE
endif
ifdef MOUSEKEY_ENABLE
SRC += $(COMMON_DIR)/mousekey.c
OPT_DEFS += -DMOUSEKEY_ENABLE
OPT_DEFS += -DMOUSE_ENABLE
endif
ifdef EXTRAKEY_ENABLE
OPT_DEFS += -DEXTRAKEY_ENABLE
endif
ifdef CONSOLE_ENABLE
OPT_DEFS += -DCONSOLE_ENABLE
else
OPT_DEFS += -DNO_PRINT
OPT_DEFS += -DNO_DEBUG
endif
ifdef COMMAND_ENABLE
SRC += $(COMMON_DIR)/command.c
OPT_DEFS += -DCOMMAND_ENABLE
endif
ifdef NKRO_ENABLE
OPT_DEFS += -DNKRO_ENABLE
endif
ifdef USB_6KRO_ENABLE
OPT_DEFS += -DUSB_6KRO_ENABLE
endif
ifdef SLEEP_LED_ENABLE
SRC += $(COMMON_DIR)/sleep_led.c
OPT_DEFS += -DSLEEP_LED_ENABLE
OPT_DEFS += -DNO_SUSPEND_POWER_DOWN
endif
ifdef BACKLIGHT_ENABLE
SRC += $(COMMON_DIR)/backlight.c
OPT_DEFS += -DBACKLIGHT_ENABLE
endif
ifdef KEYMAP_SECTION_ENABLE
OPT_DEFS += -DKEYMAP_SECTION_ENABLE
EXTRALDFLAGS = -Wl,-L$(TMK_DIR),-Tldscript_keymap_avr5.x
endif
# Version string
OPT_DEFS += -DVERSION=$(shell (git describe --always --dirty || echo 'unknown') 2> /dev/null)
# Search Path
VPATH += $(TMK_DIR)/common

565
common/action.c Normal file
View file

@ -0,0 +1,565 @@
/*
Copyright 2012,2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 "host.h"
#include "keycode.h"
#include "keyboard.h"
#include "mousekey.h"
#include "command.h"
#include "led.h"
#include "backlight.h"
#include "action_layer.h"
#include "action_tapping.h"
#include "action_macro.h"
#include "action_util.h"
#include "action.h"
#ifdef DEBUG_ACTION
#include "debug.h"
#else
#include "nodebug.h"
#endif
void action_exec(keyevent_t event)
{
if (!IS_NOEVENT(event)) {
dprint("\n---- action_exec: start -----\n");
dprint("EVENT: "); debug_event(event); dprintln();
}
keyrecord_t record = { .event = event };
#ifndef NO_ACTION_TAPPING
action_tapping_process(record);
#else
process_action(&record);
if (!IS_NOEVENT(record.event)) {
dprint("processed: "); debug_record(record); dprintln();
}
#endif
}
void process_action(keyrecord_t *record)
{
keyevent_t event = record->event;
#ifndef NO_ACTION_TAPPING
uint8_t tap_count = record->tap.count;
#endif
if (IS_NOEVENT(event)) { return; }
action_t action = layer_switch_get_action(event.key);
dprint("ACTION: "); debug_action(action);
#ifndef NO_ACTION_LAYER
dprint(" layer_state: "); layer_debug();
dprint(" default_layer_state: "); default_layer_debug();
#endif
dprintln();
switch (action.kind.id) {
/* Key and Mods */
case ACT_LMODS:
case ACT_RMODS:
{
uint8_t mods = (action.kind.id == ACT_LMODS) ? action.key.mods :
action.key.mods<<4;
if (event.pressed) {
if (mods) {
add_weak_mods(mods);
send_keyboard_report();
}
register_code(action.key.code);
} else {
unregister_code(action.key.code);
if (mods) {
del_weak_mods(mods);
send_keyboard_report();
}
}
}
break;
#ifndef NO_ACTION_TAPPING
case ACT_LMODS_TAP:
case ACT_RMODS_TAP:
{
uint8_t mods = (action.kind.id == ACT_LMODS_TAP) ? action.key.mods :
action.key.mods<<4;
switch (action.layer_tap.code) {
#ifndef NO_ACTION_ONESHOT
case MODS_ONESHOT:
// Oneshot modifier
if (event.pressed) {
if (tap_count == 0) {
register_mods(mods);
}
else if (tap_count == 1) {
dprint("MODS_TAP: Oneshot: start\n");
set_oneshot_mods(mods);
}
else {
register_mods(mods);
}
} else {
if (tap_count == 0) {
clear_oneshot_mods();
unregister_mods(mods);
}
else if (tap_count == 1) {
// Retain Oneshot mods
}
else {
clear_oneshot_mods();
unregister_mods(mods);
}
}
break;
#endif
case MODS_TAP_TOGGLE:
if (event.pressed) {
if (tap_count <= TAPPING_TOGGLE) {
register_mods(mods);
}
} else {
if (tap_count < TAPPING_TOGGLE) {
unregister_mods(mods);
}
}
break;
default:
if (event.pressed) {
if (tap_count > 0) {
if (record->tap.interrupted) {
dprint("MODS_TAP: Tap: Cancel: add_mods\n");
// ad hoc: set 0 to cancel tap
record->tap.count = 0;
register_mods(mods);
} else {
dprint("MODS_TAP: Tap: register_code\n");
register_code(action.key.code);
}
} else {
dprint("MODS_TAP: No tap: add_mods\n");
register_mods(mods);
}
} else {
if (tap_count > 0) {
dprint("MODS_TAP: Tap: unregister_code\n");
unregister_code(action.key.code);
} else {
dprint("MODS_TAP: No tap: add_mods\n");
unregister_mods(mods);
}
}
break;
}
}
break;
#endif
#ifdef EXTRAKEY_ENABLE
/* other HID usage */
case ACT_USAGE:
switch (action.usage.page) {
case PAGE_SYSTEM:
if (event.pressed) {
host_system_send(action.usage.code);
} else {
host_system_send(0);
}
break;
case PAGE_CONSUMER:
if (event.pressed) {
host_consumer_send(action.usage.code);
} else {
host_consumer_send(0);
}
break;
}
break;
#endif
#ifdef MOUSEKEY_ENABLE
/* Mouse key */
case ACT_MOUSEKEY:
if (event.pressed) {
mousekey_on(action.key.code);
mousekey_send();
} else {
mousekey_off(action.key.code);
mousekey_send();
}
break;
#endif
#ifndef NO_ACTION_LAYER
case ACT_LAYER:
if (action.layer_bitop.on == 0) {
/* Default Layer Bitwise Operation */
if (!event.pressed) {
uint8_t shift = action.layer_bitop.part*4;
uint32_t bits = ((uint32_t)action.layer_bitop.bits)<<shift;
uint32_t mask = (action.layer_bitop.xbit) ? ~(((uint32_t)0xf)<<shift) : 0;
switch (action.layer_bitop.op) {
case OP_BIT_AND: default_layer_and(bits | mask); break;
case OP_BIT_OR: default_layer_or(bits | mask); break;
case OP_BIT_XOR: default_layer_xor(bits | mask); break;
case OP_BIT_SET: default_layer_and(mask); default_layer_or(bits); break;
}
}
} else {
/* Layer Bitwise Operation */
if (event.pressed ? (action.layer_bitop.on & ON_PRESS) :
(action.layer_bitop.on & ON_RELEASE)) {
uint8_t shift = action.layer_bitop.part*4;
uint32_t bits = ((uint32_t)action.layer_bitop.bits)<<shift;
uint32_t mask = (action.layer_bitop.xbit) ? ~(((uint32_t)0xf)<<shift) : 0;
switch (action.layer_bitop.op) {
case OP_BIT_AND: layer_and(bits | mask); break;
case OP_BIT_OR: layer_or(bits | mask); break;
case OP_BIT_XOR: layer_xor(bits | mask); break;
case OP_BIT_SET: layer_and(mask); layer_or(bits); break;
}
}
}
break;
#ifndef NO_ACTION_TAPPING
case ACT_LAYER_TAP:
case ACT_LAYER_TAP_EXT:
switch (action.layer_tap.code) {
case 0xe0 ... 0xef:
/* layer On/Off with modifiers(left only) */
if (event.pressed) {
layer_on(action.layer_tap.val);
register_mods(action.layer_tap.code & 0x0f);
} else {
layer_off(action.layer_tap.val);
unregister_mods(action.layer_tap.code & 0x0f);
}
break;
case OP_TAP_TOGGLE:
/* tap toggle */
if (event.pressed) {
if (tap_count < TAPPING_TOGGLE) {
layer_invert(action.layer_tap.val);
}
} else {
if (tap_count <= TAPPING_TOGGLE) {
layer_invert(action.layer_tap.val);
}
}
break;
case OP_ON_OFF:
event.pressed ? layer_on(action.layer_tap.val) :
layer_off(action.layer_tap.val);
break;
case OP_OFF_ON:
event.pressed ? layer_off(action.layer_tap.val) :
layer_on(action.layer_tap.val);
break;
case OP_SET_CLEAR:
event.pressed ? layer_move(action.layer_tap.val) :
layer_clear();
break;
default:
/* tap key */
if (event.pressed) {
if (tap_count > 0) {
dprint("KEYMAP_TAP_KEY: Tap: register_code\n");
register_code(action.layer_tap.code);
} else {
dprint("KEYMAP_TAP_KEY: No tap: On on press\n");
layer_on(action.layer_tap.val);
}
} else {
if (tap_count > 0) {
dprint("KEYMAP_TAP_KEY: Tap: unregister_code\n");
unregister_code(action.layer_tap.code);
} else {
dprint("KEYMAP_TAP_KEY: No tap: Off on release\n");
layer_off(action.layer_tap.val);
}
}
break;
}
break;
#endif
#endif
/* Extentions */
#ifndef NO_ACTION_MACRO
case ACT_MACRO:
action_macro_play(action_get_macro(record, action.func.id, action.func.opt));
break;
#endif
#ifdef BACKLIGHT_ENABLE
case ACT_BACKLIGHT:
if (!event.pressed) {
switch (action.backlight.opt) {
case BACKLIGHT_INCREASE:
backlight_increase();
break;
case BACKLIGHT_DECREASE:
backlight_decrease();
break;
case BACKLIGHT_TOGGLE:
backlight_toggle();
break;
case BACKLIGHT_STEP:
backlight_step();
break;
case BACKLIGHT_LEVEL:
backlight_level(action.backlight.level);
break;
}
}
break;
#endif
case ACT_COMMAND:
break;
#ifndef NO_ACTION_FUNCTION
case ACT_FUNCTION:
action_function(record, action.func.id, action.func.opt);
break;
#endif
default:
break;
}
}
/*
* Utilities for actions.
*/
void register_code(uint8_t code)
{
if (code == KC_NO) {
return;
}
#ifdef LOCKING_SUPPORT_ENABLE
else if (KC_LOCKING_CAPS == code) {
#ifdef LOCKING_RESYNC_ENABLE
// Resync: ignore if caps lock already is on
if (host_keyboard_leds() & (1<<USB_LED_CAPS_LOCK)) return;
#endif
add_key(KC_CAPSLOCK);
send_keyboard_report();
del_key(KC_CAPSLOCK);
send_keyboard_report();
}
else if (KC_LOCKING_NUM == code) {
#ifdef LOCKING_RESYNC_ENABLE
if (host_keyboard_leds() & (1<<USB_LED_NUM_LOCK)) return;
#endif
add_key(KC_NUMLOCK);
send_keyboard_report();
del_key(KC_NUMLOCK);
send_keyboard_report();
}
else if (KC_LOCKING_SCROLL == code) {
#ifdef LOCKING_RESYNC_ENABLE
if (host_keyboard_leds() & (1<<USB_LED_SCROLL_LOCK)) return;
#endif
add_key(KC_SCROLLLOCK);
send_keyboard_report();
del_key(KC_SCROLLLOCK);
send_keyboard_report();
}
#endif
else if IS_KEY(code) {
// TODO: should push command_proc out of this block?
if (command_proc(code)) return;
#ifndef NO_ACTION_ONESHOT
/* TODO: remove
if (oneshot_state.mods && !oneshot_state.disabled) {
uint8_t tmp_mods = get_mods();
add_mods(oneshot_state.mods);
add_key(code);
send_keyboard_report();
set_mods(tmp_mods);
send_keyboard_report();
oneshot_cancel();
} else
*/
#endif
{
add_key(code);
send_keyboard_report();
}
}
else if IS_MOD(code) {
add_mods(MOD_BIT(code));
send_keyboard_report();
}
else if IS_SYSTEM(code) {
host_system_send(KEYCODE2SYSTEM(code));
}
else if IS_CONSUMER(code) {
host_consumer_send(KEYCODE2CONSUMER(code));
}
}
void unregister_code(uint8_t code)
{
if (code == KC_NO) {
return;
}
#ifdef LOCKING_SUPPORT_ENABLE
else if (KC_LOCKING_CAPS == code) {
#ifdef LOCKING_RESYNC_ENABLE
// Resync: ignore if caps lock already is off
if (!(host_keyboard_leds() & (1<<USB_LED_CAPS_LOCK))) return;
#endif
add_key(KC_CAPSLOCK);
send_keyboard_report();
del_key(KC_CAPSLOCK);
send_keyboard_report();
}
else if (KC_LOCKING_NUM == code) {
#ifdef LOCKING_RESYNC_ENABLE
if (!(host_keyboard_leds() & (1<<USB_LED_NUM_LOCK))) return;
#endif
add_key(KC_NUMLOCK);
send_keyboard_report();
del_key(KC_NUMLOCK);
send_keyboard_report();
}
else if (KC_LOCKING_SCROLL == code) {
#ifdef LOCKING_RESYNC_ENABLE
if (!(host_keyboard_leds() & (1<<USB_LED_SCROLL_LOCK))) return;
#endif
add_key(KC_SCROLLLOCK);
send_keyboard_report();
del_key(KC_SCROLLLOCK);
send_keyboard_report();
}
#endif
else if IS_KEY(code) {
del_key(code);
send_keyboard_report();
}
else if IS_MOD(code) {
del_mods(MOD_BIT(code));
send_keyboard_report();
}
else if IS_SYSTEM(code) {
host_system_send(0);
}
else if IS_CONSUMER(code) {
host_consumer_send(0);
}
}
void register_mods(uint8_t mods)
{
if (mods) {
add_mods(mods);
send_keyboard_report();
}
}
void unregister_mods(uint8_t mods)
{
if (mods) {
del_mods(mods);
send_keyboard_report();
}
}
void clear_keyboard(void)
{
clear_mods();
clear_keyboard_but_mods();
}
void clear_keyboard_but_mods(void)
{
clear_weak_mods();
clear_keys();
send_keyboard_report();
#ifdef MOUSEKEY_ENABLE
mousekey_clear();
mousekey_send();
#endif
#ifdef EXTRAKEY_ENABLE
host_system_send(0);
host_consumer_send(0);
#endif
}
bool is_tap_key(keypos_t key)
{
action_t action = layer_switch_get_action(key);
switch (action.kind.id) {
case ACT_LMODS_TAP:
case ACT_RMODS_TAP:
case ACT_LAYER_TAP:
case ACT_LAYER_TAP_EXT:
return true;
case ACT_MACRO:
case ACT_FUNCTION:
if (action.func.opt & FUNC_TAP) { return true; }
return false;
}
return false;
}
/*
* debug print
*/
void debug_event(keyevent_t event)
{
dprintf("%04X%c(%u)", (event.key.row<<8 | event.key.col), (event.pressed ? 'd' : 'u'), event.time);
}
void debug_record(keyrecord_t record)
{
debug_event(record.event);
#ifndef NO_ACTION_TAPPING
dprintf(":%u%c", record.tap.count, (record.tap.interrupted ? '-' : ' '));
#endif
}
void debug_action(action_t action)
{
switch (action.kind.id) {
case ACT_LMODS: dprint("ACT_LMODS"); break;
case ACT_RMODS: dprint("ACT_RMODS"); break;
case ACT_LMODS_TAP: dprint("ACT_LMODS_TAP"); break;
case ACT_RMODS_TAP: dprint("ACT_RMODS_TAP"); break;
case ACT_USAGE: dprint("ACT_USAGE"); break;
case ACT_MOUSEKEY: dprint("ACT_MOUSEKEY"); break;
case ACT_LAYER: dprint("ACT_LAYER"); break;
case ACT_LAYER_TAP: dprint("ACT_LAYER_TAP"); break;
case ACT_LAYER_TAP_EXT: dprint("ACT_LAYER_TAP_EXT"); break;
case ACT_MACRO: dprint("ACT_MACRO"); break;
case ACT_COMMAND: dprint("ACT_COMMAND"); break;
case ACT_FUNCTION: dprint("ACT_FUNCTION"); break;
default: dprint("UNKNOWN"); break;
}
dprintf("[%X:%02X]", action.kind.param>>8, action.kind.param&0xff);
}

82
common/action.h Normal file
View file

@ -0,0 +1,82 @@
/*
Copyright 2012,2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef ACTION_H
#define ACTION_H
#include <stdint.h>
#include <stdbool.h>
#include "keyboard.h"
#include "keycode.h"
#include "action_code.h"
#include "action_macro.h"
#ifdef __cplusplus
extern "C" {
#endif
/* tapping count and state */
typedef struct {
bool interrupted :1;
bool reserved2 :1;
bool reserved1 :1;
bool reserved0 :1;
uint8_t count :4;
} tap_t;
/* Key event container for recording */
typedef struct {
keyevent_t event;
#ifndef NO_ACTION_TAPPING
tap_t tap;
#endif
} keyrecord_t;
/* Execute action per keyevent */
void action_exec(keyevent_t event);
/* action for key */
action_t action_for_key(uint8_t layer, keypos_t key);
/* macro */
const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt);
/* user defined special function */
void action_function(keyrecord_t *record, uint8_t id, uint8_t opt);
/* Utilities for actions. */
void process_action(keyrecord_t *record);
void register_code(uint8_t code);
void unregister_code(uint8_t code);
void register_mods(uint8_t mods);
void unregister_mods(uint8_t mods);
//void set_mods(uint8_t mods);
void clear_keyboard(void);
void clear_keyboard_but_mods(void);
void layer_switch(uint8_t new_layer);
bool is_tap_key(keypos_t key);
/* debug */
void debug_event(keyevent_t event);
void debug_record(keyrecord_t record);
void debug_action(action_t action);
#ifdef __cplusplus
}
#endif
#endif /* ACTION_H */

315
common/action_code.h Normal file
View file

@ -0,0 +1,315 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef ACTION_CODE_H
#define ACTION_CODE_H
/* Action codes
* ============
* 16bit code: action_kind(4bit) + action_parameter(12bit)
*
*
* Key Actions(00xx)
* -----------------
* ACT_MODS(000r):
* 000r|0000|0000 0000 No action code
* 000r|0000|0000 0001 Transparent code
* 000r|0000| keycode Key
* 000r|mods|0000 0000 Modifiers
* 000r|mods| keycode Modifiers+Key(Modified key)
* r: Left/Right flag(Left:0, Right:1)
*
* ACT_MODS_TAP(001r):
* 001r|mods|0000 0000 Modifiers with OneShot
* 001r|mods|0000 0001 Modifiers with tap toggle
* 001r|mods|0000 00xx (reserved)
* 001r|mods| keycode Modifiers with Tap Key(Dual role)
*
*
* Other Keys(01xx)
* ----------------
* ACT_USAGE(0100): TODO: Not needed?
* 0100|00| usage(10) System control(0x80) - General Desktop page(0x01)
* 0100|01| usage(10) Consumer control(0x01) - Consumer page(0x0C)
* 0100|10| usage(10) (reserved)
* 0100|11| usage(10) (reserved)
*
* ACT_MOUSEKEY(0110): TODO: Not needed?
* 0101|xxxx| keycode Mouse key
*
* 011x|xxxx xxxx xxxx (reseved)
*
*
* Layer Actions(10xx)
* -------------------
* ACT_LAYER(1000):
* 1000|oo00|pppE BBBB Default Layer Bitwise operation
* oo: operation(00:AND, 01:OR, 10:XOR, 11:SET)
* ppp: 4-bit chunk part(0-7)
* EBBBB: bits and extra bit
* 1000|ooee|pppE BBBB Layer Bitwise Operation
* oo: operation(00:AND, 01:OR, 10:XOR, 11:SET)
* ppp: 4-bit chunk part(0-7)
* EBBBB: bits and extra bit
* ee: on event(01:press, 10:release, 11:both)
*
* 1001|xxxx|xxxx xxxx (reserved)
* 1001|oopp|BBBB BBBB 8-bit Bitwise Operation???
*
* ACT_LAYER_TAP(101x):
* 101E|LLLL| keycode On/Off with tap key
* 101E|LLLL|1110 mods On/Off with modifiers(0xE0-EF)
* 101E|LLLL|1111 0000 Invert with tap toggle(0xF0)
* 101E|LLLL|1111 0001 On/Off
* 101E|LLLL|1111 0010 Off/On
* 101E|LLLL|1111 0011 Set/Clear
* 101E|LLLL|1111 xxxx Reserved(0xF4-FF)
* ELLLL: layer 0-31(E: extra bit for layer 16-31)
*
*
* Extensions(11xx)
* ----------------
* ACT_MACRO(1100):
* 1100|opt | id(8) Macro play?
* 1100|1111| id(8) Macro record?
*
* ACT_BACKLIGHT(1101):
* 1101|opt |level(8) Backlight commands
*
* ACT_COMMAND(1110):
* 1110|opt | id(8) Built-in Command exec
*
* ACT_FUNCTION(1111):
* 1111| address(12) Function?
* 1111|opt | id(8) Function?
*/
enum action_kind_id {
/* Key Actions */
ACT_MODS = 0b0000,
ACT_LMODS = 0b0000,
ACT_RMODS = 0b0001,
ACT_MODS_TAP = 0b0010,
ACT_LMODS_TAP = 0b0010,
ACT_RMODS_TAP = 0b0011,
/* Other Keys */
ACT_USAGE = 0b0100,
ACT_MOUSEKEY = 0b0101,
/* Layer Actions */
ACT_LAYER = 0b1000,
ACT_LAYER_TAP = 0b1010, /* Layer 0-15 */
ACT_LAYER_TAP_EXT = 0b1011, /* Layer 16-31 */
/* Extensions */
ACT_MACRO = 0b1100,
ACT_BACKLIGHT = 0b1101,
ACT_COMMAND = 0b1110,
ACT_FUNCTION = 0b1111
};
/* Action Code Struct
*
* NOTE:
* In avr-gcc bit field seems to be assigned from LSB(bit0) to MSB(bit15).
* AVR looks like a little endian in avr-gcc.
* Not portable across compiler/endianness?
*
* Byte order and bit order of 0x1234:
* Big endian: Little endian:
* -------------------- --------------------
* FEDC BA98 7654 3210 0123 4567 89AB CDEF
* 0001 0010 0011 0100 0010 1100 0100 1000
* 0x12 0x34 0x34 0x12
*/
typedef union {
uint16_t code;
struct action_kind {
uint16_t param :12;
uint8_t id :4;
} kind;
struct action_key {
uint8_t code :8;
uint8_t mods :4;
uint8_t kind :4;
} key;
struct action_layer_bitop {
uint8_t bits :4;
uint8_t xbit :1;
uint8_t part :3;
uint8_t on :2;
uint8_t op :2;
uint8_t kind :4;
} layer_bitop;
struct action_layer_tap {
uint8_t code :8;
uint8_t val :5;
uint8_t kind :3;
} layer_tap;
struct action_usage {
uint16_t code :10;
uint8_t page :2;
uint8_t kind :4;
} usage;
struct action_backlight {
uint8_t level :8;
uint8_t opt :4;
uint8_t kind :4;
} backlight;
struct action_command {
uint8_t id :8;
uint8_t opt :4;
uint8_t kind :4;
} command;
struct action_function {
uint8_t id :8;
uint8_t opt :4;
uint8_t kind :4;
} func;
} action_t;
/* action utility */
#define ACTION_NO 0
#define ACTION_TRANSPARENT 1
#define ACTION(kind, param) ((kind)<<12 | (param))
/*
* Key Actions
*/
/* Mod bits: 43210
* bit 0 ||||+- Control
* bit 1 |||+-- Shift
* bit 2 ||+--- Alt
* bit 3 |+---- Gui
* bit 4 +----- LR flag(Left:0, Right:1)
*/
enum mods_bit {
MOD_LCTL = 0x01,
MOD_LSFT = 0x02,
MOD_LALT = 0x04,
MOD_LGUI = 0x08,
MOD_RCTL = 0x11,
MOD_RSFT = 0x12,
MOD_RALT = 0x14,
MOD_RGUI = 0x18,
};
enum mods_codes {
MODS_ONESHOT = 0x00,
MODS_TAP_TOGGLE = 0x01,
};
#define ACTION_KEY(key) ACTION(ACT_MODS, (key))
#define ACTION_MODS(mods) ACTION(ACT_MODS, ((mods)&0x1f)<<8 | 0)
#define ACTION_MODS_KEY(mods, key) ACTION(ACT_MODS, ((mods)&0x1f)<<8 | (key))
#define ACTION_MODS_TAP_KEY(mods, key) ACTION(ACT_MODS_TAP, ((mods)&0x1f)<<8 | (key))
#define ACTION_MODS_ONESHOT(mods) ACTION(ACT_MODS_TAP, ((mods)&0x1f)<<8 | MODS_ONESHOT)
#define ACTION_MODS_TAP_TOGGLE(mods) ACTION(ACT_MODS_TAP, ((mods)&0x1f)<<8 | MODS_TAP_TOGGLE)
/*
* Other Keys
*/
enum usage_pages {
PAGE_SYSTEM,
PAGE_CONSUMER
};
#define ACTION_USAGE_SYSTEM(id) ACTION(ACT_USAGE, PAGE_SYSTEM<<10 | (id))
#define ACTION_USAGE_CONSUMER(id) ACTION(ACT_USAGE, PAGE_CONSUMER<<10 | (id))
#define ACTION_MOUSEKEY(key) ACTION(ACT_MOUSEKEY, key)
/*
* Layer Actions
*/
enum layer_param_on {
ON_PRESS = 1,
ON_RELEASE = 2,
ON_BOTH = 3,
};
enum layer_param_bit_op {
OP_BIT_AND = 0,
OP_BIT_OR = 1,
OP_BIT_XOR = 2,
OP_BIT_SET = 3,
};
enum layer_pram_tap_op {
OP_TAP_TOGGLE = 0xF0,
OP_ON_OFF,
OP_OFF_ON,
OP_SET_CLEAR,
};
#define ACTION_LAYER_BITOP(op, part, bits, on) (ACT_LAYER<<12 | (op)<<10 | (on)<<8 | (part)<<5 | ((bits)&0x1f))
#define ACTION_LAYER_TAP(layer, key) (ACT_LAYER_TAP<<12 | (layer)<<8 | (key))
/* Default Layer */
#define ACTION_DEFAULT_LAYER_SET(layer) ACTION_DEFAULT_LAYER_BIT_SET((layer)/4, 1<<((layer)%4))
/* Layer Operation */
#define ACTION_LAYER_CLEAR(on) ACTION_LAYER_BIT_AND(0, 0, (on))
#define ACTION_LAYER_MOMENTARY(layer) ACTION_LAYER_ON_OFF(layer)
#define ACTION_LAYER_TOGGLE(layer) ACTION_LAYER_INVERT(layer, ON_RELEASE)
#define ACTION_LAYER_INVERT(layer, on) ACTION_LAYER_BIT_XOR((layer)/4, 1<<((layer)%4), (on))
#define ACTION_LAYER_ON(layer, on) ACTION_LAYER_BIT_OR( (layer)/4, 1<<((layer)%4), (on))
#define ACTION_LAYER_OFF(layer, on) ACTION_LAYER_BIT_AND((layer)/4, ~(1<<((layer)%4)), (on))
#define ACTION_LAYER_SET(layer, on) ACTION_LAYER_BIT_SET((layer)/4, 1<<((layer)%4), (on))
#define ACTION_LAYER_ON_OFF(layer) ACTION_LAYER_TAP((layer), OP_ON_OFF)
#define ACTION_LAYER_OFF_ON(layer) ACTION_LAYER_TAP((layer), OP_OFF_ON)
#define ACTION_LAYER_SET_CLEAR(layer) ACTION_LAYER_TAP((layer), OP_SET_CLEAR)
#define ACTION_LAYER_MODS(layer, mods) ACTION_LAYER_TAP((layer), 0xe0 | (mods)&0x0f)
/* With Tapping */
#define ACTION_LAYER_TAP_KEY(layer, key) ACTION_LAYER_TAP((layer), (key))
#define ACTION_LAYER_TAP_TOGGLE(layer) ACTION_LAYER_TAP((layer), OP_TAP_TOGGLE)
/* Bitwise Operation */
#define ACTION_LAYER_BIT_AND(part, bits, on) ACTION_LAYER_BITOP(OP_BIT_AND, (part), (bits), (on))
#define ACTION_LAYER_BIT_OR( part, bits, on) ACTION_LAYER_BITOP(OP_BIT_OR, (part), (bits), (on))
#define ACTION_LAYER_BIT_XOR(part, bits, on) ACTION_LAYER_BITOP(OP_BIT_XOR, (part), (bits), (on))
#define ACTION_LAYER_BIT_SET(part, bits, on) ACTION_LAYER_BITOP(OP_BIT_SET, (part), (bits), (on))
/* Default Layer Bitwise Operation */
#define ACTION_DEFAULT_LAYER_BIT_AND(part, bits) ACTION_LAYER_BITOP(OP_BIT_AND, (part), (bits), 0)
#define ACTION_DEFAULT_LAYER_BIT_OR( part, bits) ACTION_LAYER_BITOP(OP_BIT_OR, (part), (bits), 0)
#define ACTION_DEFAULT_LAYER_BIT_XOR(part, bits) ACTION_LAYER_BITOP(OP_BIT_XOR, (part), (bits), 0)
#define ACTION_DEFAULT_LAYER_BIT_SET(part, bits) ACTION_LAYER_BITOP(OP_BIT_SET, (part), (bits), 0)
/*
* Extensions
*/
enum backlight_opt {
BACKLIGHT_INCREASE = 0,
BACKLIGHT_DECREASE = 1,
BACKLIGHT_TOGGLE = 2,
BACKLIGHT_STEP = 3,
BACKLIGHT_LEVEL = 4,
};
/* Macro */
#define ACTION_MACRO(id) ACTION(ACT_MACRO, (id))
#define ACTION_MACRO_TAP(id) ACTION(ACT_MACRO, FUNC_TAP<<8 | (id))
#define ACTION_MACRO_OPT(id, opt) ACTION(ACT_MACRO, (opt)<<8 | (id))
/* Backlight */
#define ACTION_BACKLIGHT_INCREASE() ACTION(ACT_BACKLIGHT, BACKLIGHT_INCREASE << 8)
#define ACTION_BACKLIGHT_DECREASE() ACTION(ACT_BACKLIGHT, BACKLIGHT_DECREASE << 8)
#define ACTION_BACKLIGHT_TOGGLE() ACTION(ACT_BACKLIGHT, BACKLIGHT_TOGGLE << 8)
#define ACTION_BACKLIGHT_STEP() ACTION(ACT_BACKLIGHT, BACKLIGHT_STEP << 8)
#define ACTION_BACKLIGHT_LEVEL(level) ACTION(ACT_BACKLIGHT, BACKLIGHT_LEVEL << 8 | level)
/* Command */
#define ACTION_COMMAND(id, opt) ACTION(ACT_COMMAND, (opt)<<8 | (addr))
/* Function */
enum function_opts {
FUNC_TAP = 0x8, /* indciates function is tappable */
};
#define ACTION_FUNCTION(id) ACTION(ACT_FUNCTION, (id))
#define ACTION_FUNCTION_TAP(id) ACTION(ACT_FUNCTION, FUNC_TAP<<8 | (id))
#define ACTION_FUNCTION_OPT(id, opt) ACTION(ACT_FUNCTION, (opt)<<8 | (id))
#endif /* ACTION_CODE_H */

138
common/action_layer.c Normal file
View file

@ -0,0 +1,138 @@
#include <stdint.h>
#include "keyboard.h"
#include "action.h"
#include "util.h"
#include "action_layer.h"
#ifdef DEBUG_ACTION
#include "debug.h"
#else
#include "nodebug.h"
#endif
/*
* Default Layer State
*/
uint32_t default_layer_state = 0;
static void default_layer_state_set(uint32_t state)
{
debug("default_layer_state: ");
default_layer_debug(); debug(" to ");
default_layer_state = state;
default_layer_debug(); debug("\n");
clear_keyboard_but_mods(); // To avoid stuck keys
}
void default_layer_debug(void)
{
dprintf("%08lX(%u)", default_layer_state, biton32(default_layer_state));
}
void default_layer_set(uint32_t state)
{
default_layer_state_set(state);
}
#ifndef NO_ACTION_LAYER
void default_layer_or(uint32_t state)
{
default_layer_state_set(default_layer_state | state);
}
void default_layer_and(uint32_t state)
{
default_layer_state_set(default_layer_state & state);
}
void default_layer_xor(uint32_t state)
{
default_layer_state_set(default_layer_state ^ state);
}
#endif
#ifndef NO_ACTION_LAYER
/*
* Keymap Layer State
*/
uint32_t layer_state = 0;
static void layer_state_set(uint32_t state)
{
dprint("layer_state: ");
layer_debug(); dprint(" to ");
layer_state = state;
layer_debug(); dprintln();
clear_keyboard_but_mods(); // To avoid stuck keys
}
void layer_clear(void)
{
layer_state_set(0);
}
void layer_move(uint8_t layer)
{
layer_state_set(1UL<<layer);
}
void layer_on(uint8_t layer)
{
layer_state_set(layer_state | (1UL<<layer));
}
void layer_off(uint8_t layer)
{
layer_state_set(layer_state & ~(1UL<<layer));
}
void layer_invert(uint8_t layer)
{
layer_state_set(layer_state ^ (1UL<<layer));
}
void layer_or(uint32_t state)
{
layer_state_set(layer_state | state);
}
void layer_and(uint32_t state)
{
layer_state_set(layer_state & state);
}
void layer_xor(uint32_t state)
{
layer_state_set(layer_state ^ state);
}
void layer_debug(void)
{
dprintf("%08lX(%u)", layer_state, biton32(layer_state));
}
#endif
action_t layer_switch_get_action(keypos_t key)
{
action_t action;
action.code = ACTION_TRANSPARENT;
#ifndef NO_ACTION_LAYER
uint32_t layers = layer_state | default_layer_state;
/* check top layer first */
for (int8_t i = 31; i >= 0; i--) {
if (layers & (1UL<<i)) {
action = action_for_key(i, key);
if (action.code != ACTION_TRANSPARENT) {
return action;
}
}
}
/* fall back to layer 0 */
action = action_for_key(0, key);
return action;
#else
action = action_for_key(biton32(default_layer_state), key);
return action;
#endif
}

77
common/action_layer.h Normal file
View file

@ -0,0 +1,77 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef ACTION_LAYER_H
#define ACTION_LAYER_H
#include <stdint.h>
#include "keyboard.h"
#include "action.h"
/*
* Default Layer
*/
extern uint32_t default_layer_state;
void default_layer_debug(void);
void default_layer_set(uint32_t state);
#ifndef NO_ACTION_LAYER
/* bitwise operation */
void default_layer_or(uint32_t state);
void default_layer_and(uint32_t state);
void default_layer_xor(uint32_t state);
#else
#define default_layer_or(state)
#define default_layer_and(state)
#define default_layer_xor(state)
#endif
/*
* Keymap Layer
*/
#ifndef NO_ACTION_LAYER
extern uint32_t layer_state;
void layer_debug(void);
void layer_clear(void);
void layer_move(uint8_t layer);
void layer_on(uint8_t layer);
void layer_off(uint8_t layer);
void layer_invert(uint8_t layer);
/* bitwise operation */
void layer_or(uint32_t state);
void layer_and(uint32_t state);
void layer_xor(uint32_t state);
#else
#define layer_state 0
#define layer_clear()
#define layer_move(layer)
#define layer_on(layer)
#define layer_off(layer)
#define layer_invert(layer)
#define layer_or(state)
#define layer_and(state)
#define layer_xor(state)
#define layer_debug()
#endif
/* return action depending on current layer status */
action_t layer_switch_get_action(keypos_t key);
#endif

83
common/action_macro.c Normal file
View file

@ -0,0 +1,83 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 "action.h"
#include "action_util.h"
#include "action_macro.h"
#include "wait.h"
#ifdef DEBUG_ACTION
#include "debug.h"
#else
#include "nodebug.h"
#endif
#ifndef NO_ACTION_MACRO
#define MACRO_READ() (macro = MACRO_GET(macro_p++))
void action_macro_play(const macro_t *macro_p)
{
macro_t macro = END;
uint8_t interval = 0;
if (!macro_p) return;
while (true) {
switch (MACRO_READ()) {
case KEY_DOWN:
MACRO_READ();
dprintf("KEY_DOWN(%02X)\n", macro);
if (IS_MOD(macro)) {
add_weak_mods(MOD_BIT(macro));
} else {
register_code(macro);
}
break;
case KEY_UP:
MACRO_READ();
dprintf("KEY_UP(%02X)\n", macro);
if (IS_MOD(macro)) {
del_weak_mods(MOD_BIT(macro));
} else {
unregister_code(macro);
}
break;
case WAIT:
MACRO_READ();
dprintf("WAIT(%u)\n", macro);
{ uint8_t ms = macro; while (ms--) wait_ms(1); }
break;
case INTERVAL:
interval = MACRO_READ();
dprintf("INTERVAL(%u)\n", interval);
break;
case 0x04 ... 0x73:
dprintf("DOWN(%02X)\n", macro);
register_code(macro);
break;
case 0x84 ... 0xF3:
dprintf("UP(%02X)\n", macro);
unregister_code(macro&0x7F);
break;
case END:
default:
return;
}
// interval
{ uint8_t ms = interval; while (ms--) wait_ms(1); }
}
}
#endif

102
common/action_macro.h Normal file
View file

@ -0,0 +1,102 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef ACTION_MACRO_H
#define ACTION_MACRO_H
#include <stdint.h>
#include "progmem.h"
#define MACRO_NONE 0
#define MACRO(...) ({ static const macro_t __m[] PROGMEM = { __VA_ARGS__ }; &__m[0]; })
#define MACRO_GET(p) pgm_read_byte(p)
typedef uint8_t macro_t;
#ifndef NO_ACTION_MACRO
void action_macro_play(const macro_t *macro_p);
#else
#define action_macro_play(macro)
#endif
/* Macro commands
* code(0x04-73) // key down(1byte)
* code(0x04-73) | 0x80 // key up(1byte)
* { KEY_DOWN, code(0x04-0xff) } // key down(2bytes)
* { KEY_UP, code(0x04-0xff) } // key up(2bytes)
* WAIT // wait milli-seconds
* INTERVAL // set interval between macro commands
* END // stop macro execution
*
* Ideas(Not implemented):
* modifiers
* system usage
* consumer usage
* unicode usage
* function call
* conditionals
* loop
*/
enum macro_command_id{
/* 0x00 - 0x03 */
END = 0x00,
KEY_DOWN,
KEY_UP,
/* 0x04 - 0x73 (reserved for keycode down) */
/* 0x74 - 0x83 */
WAIT = 0x74,
INTERVAL,
/* 0x84 - 0xf3 (reserved for keycode up) */
/* 0xf4 - 0xff */
};
/* TODO: keycode:0x04-0x73 can be handled by 1byte command else 2bytes are needed
* if keycode between 0x04 and 0x73
* keycode / (keycode|0x80)
* else
* {KEY_DOWN, keycode} / {KEY_UP, keycode}
*/
#define DOWN(key) KEY_DOWN, (key)
#define UP(key) KEY_UP, (key)
#define TYPE(key) DOWN(key), UP(key)
#define WAIT(ms) WAIT, (ms)
#define INTERVAL(ms) INTERVAL, (ms)
/* key down */
#define D(key) DOWN(KC_##key)
/* key up */
#define U(key) UP(KC_##key)
/* key type */
#define T(key) TYPE(KC_##key)
/* wait */
#define W(ms) WAIT(ms)
/* interval */
#define I(ms) INTERVAL(ms)
/* for backward comaptibility */
#define MD(key) DOWN(KC_##key)
#define MU(key) UP(KC_##key)
#endif /* ACTION_MACRO_H */

376
common/action_tapping.c Normal file
View file

@ -0,0 +1,376 @@
#include <stdint.h>
#include <stdbool.h>
#include "action.h"
#include "action_layer.h"
#include "action_tapping.h"
#include "keycode.h"
#include "timer.h"
#ifdef DEBUG_ACTION
#include "debug.h"
#else
#include "nodebug.h"
#endif
#ifndef NO_ACTION_TAPPING
#define IS_TAPPING() !IS_NOEVENT(tapping_key.event)
#define IS_TAPPING_PRESSED() (IS_TAPPING() && tapping_key.event.pressed)
#define IS_TAPPING_RELEASED() (IS_TAPPING() && !tapping_key.event.pressed)
#define IS_TAPPING_KEY(k) (IS_TAPPING() && KEYEQ(tapping_key.event.key, (k)))
#define WITHIN_TAPPING_TERM(e) (TIMER_DIFF_16(e.time, tapping_key.event.time) < TAPPING_TERM)
static keyrecord_t tapping_key = {};
static keyrecord_t waiting_buffer[WAITING_BUFFER_SIZE] = {};
static uint8_t waiting_buffer_head = 0;
static uint8_t waiting_buffer_tail = 0;
static bool process_tapping(keyrecord_t *record);
static bool waiting_buffer_enq(keyrecord_t record);
static void waiting_buffer_clear(void);
static bool waiting_buffer_typed(keyevent_t event);
static bool waiting_buffer_has_anykey_pressed(void);
static void waiting_buffer_scan_tap(void);
static void debug_tapping_key(void);
static void debug_waiting_buffer(void);
void action_tapping_process(keyrecord_t record)
{
if (process_tapping(&record)) {
if (!IS_NOEVENT(record.event)) {
debug("processed: "); debug_record(record); debug("\n");
}
} else {
if (!waiting_buffer_enq(record)) {
// clear all in case of overflow.
debug("OVERFLOW: CLEAR ALL STATES\n");
clear_keyboard();
waiting_buffer_clear();
tapping_key = (keyrecord_t){};
}
}
// process waiting_buffer
if (!IS_NOEVENT(record.event) && waiting_buffer_head != waiting_buffer_tail) {
debug("---- action_exec: process waiting_buffer -----\n");
}
for (; waiting_buffer_tail != waiting_buffer_head; waiting_buffer_tail = (waiting_buffer_tail + 1) % WAITING_BUFFER_SIZE) {
if (process_tapping(&waiting_buffer[waiting_buffer_tail])) {
debug("processed: waiting_buffer["); debug_dec(waiting_buffer_tail); debug("] = ");
debug_record(waiting_buffer[waiting_buffer_tail]); debug("\n\n");
} else {
break;
}
}
if (!IS_NOEVENT(record.event)) {
debug("\n");
}
}
/* Tapping
*
* Rule: Tap key is typed(pressed and released) within TAPPING_TERM.
* (without interfering by typing other key)
*/
/* return true when key event is processed or consumed. */
bool process_tapping(keyrecord_t *keyp)
{
keyevent_t event = keyp->event;
// if tapping
if (IS_TAPPING_PRESSED()) {
if (WITHIN_TAPPING_TERM(event)) {
if (tapping_key.tap.count == 0) {
if (IS_TAPPING_KEY(event.key) && !event.pressed) {
// first tap!
debug("Tapping: First tap(0->1).\n");
tapping_key.tap.count = 1;
debug_tapping_key();
process_action(&tapping_key);
// copy tapping state
keyp->tap = tapping_key.tap;
// enqueue
return false;
}
#if TAPPING_TERM >= 500
/* Process a key typed within TAPPING_TERM
* This can register the key before settlement of tapping,
* useful for long TAPPING_TERM but may prevent fast typing.
*/
else if (IS_RELEASED(event) && waiting_buffer_typed(event)) {
debug("Tapping: End. No tap. Interfered by typing key\n");
process_action(&tapping_key);
tapping_key = (keyrecord_t){};
debug_tapping_key();
// enqueue
return false;
}
#endif
/* Process release event of a key pressed before tapping starts
* Without this unexpected repeating will occur with having fast repeating setting
* https://github.com/tmk/tmk_keyboard/issues/60
*/
else if (IS_RELEASED(event) && !waiting_buffer_typed(event)) {
// Modifier should be retained till end of this tapping.
action_t action = layer_switch_get_action(event.key);
switch (action.kind.id) {
case ACT_LMODS:
case ACT_RMODS:
if (action.key.mods && !action.key.code) return false;
if (IS_MOD(action.key.code)) return false;
break;
case ACT_LMODS_TAP:
case ACT_RMODS_TAP:
if (action.key.mods && keyp->tap.count == 0) return false;
if (IS_MOD(action.key.code)) return false;
break;
}
// Release of key should be process immediately.
debug("Tapping: release event of a key pressed before tapping\n");
process_action(keyp);
return true;
}
else {
// set interrupted flag when other key preesed during tapping
if (event.pressed) {
tapping_key.tap.interrupted = true;
}
// enqueue
return false;
}
}
// tap_count > 0
else {
if (IS_TAPPING_KEY(event.key) && !event.pressed) {
debug("Tapping: Tap release("); debug_dec(tapping_key.tap.count); debug(")\n");
keyp->tap = tapping_key.tap;
process_action(keyp);
tapping_key = *keyp;
debug_tapping_key();
return true;
}
else if (is_tap_key(event.key) && event.pressed) {
if (tapping_key.tap.count > 1) {
debug("Tapping: Start new tap with releasing last tap(>1).\n");
// unregister key
process_action(&(keyrecord_t){
.tap = tapping_key.tap,
.event.key = tapping_key.event.key,
.event.time = event.time,
.event.pressed = false
});
} else {
debug("Tapping: Start while last tap(1).\n");
}
tapping_key = *keyp;
waiting_buffer_scan_tap();
debug_tapping_key();
return true;
}
else {
if (!IS_NOEVENT(event)) {
debug("Tapping: key event while last tap(>0).\n");
}
process_action(keyp);
return true;
}
}
}
// after TAPPING_TERM
else {
if (tapping_key.tap.count == 0) {
debug("Tapping: End. Timeout. Not tap(0): ");
debug_event(event); debug("\n");
process_action(&tapping_key);
tapping_key = (keyrecord_t){};
debug_tapping_key();
return false;
} else {
if (IS_TAPPING_KEY(event.key) && !event.pressed) {
debug("Tapping: End. last timeout tap release(>0).");
keyp->tap = tapping_key.tap;
process_action(keyp);
tapping_key = (keyrecord_t){};
return true;
}
else if (is_tap_key(event.key) && event.pressed) {
if (tapping_key.tap.count > 1) {
debug("Tapping: Start new tap with releasing last timeout tap(>1).\n");
// unregister key
process_action(&(keyrecord_t){
.tap = tapping_key.tap,
.event.key = tapping_key.event.key,
.event.time = event.time,
.event.pressed = false
});
} else {
debug("Tapping: Start while last timeout tap(1).\n");
}
tapping_key = *keyp;
waiting_buffer_scan_tap();
debug_tapping_key();
return true;
}
else {
if (!IS_NOEVENT(event)) {
debug("Tapping: key event while last timeout tap(>0).\n");
}
process_action(keyp);
return true;
}
}
}
} else if (IS_TAPPING_RELEASED()) {
if (WITHIN_TAPPING_TERM(event)) {
if (event.pressed) {
if (IS_TAPPING_KEY(event.key)) {
if (!tapping_key.tap.interrupted && tapping_key.tap.count > 0) {
// sequential tap.
keyp->tap = tapping_key.tap;
if (keyp->tap.count < 15) keyp->tap.count += 1;
debug("Tapping: Tap press("); debug_dec(keyp->tap.count); debug(")\n");
process_action(keyp);
tapping_key = *keyp;
debug_tapping_key();
return true;
} else {
// FIX: start new tap again
tapping_key = *keyp;
return true;
}
} else if (is_tap_key(event.key)) {
// Sequential tap can be interfered with other tap key.
debug("Tapping: Start with interfering other tap.\n");
tapping_key = *keyp;
waiting_buffer_scan_tap();
debug_tapping_key();
return true;
} else {
// should none in buffer
// FIX: interrupted when other key is pressed
tapping_key.tap.interrupted = true;
process_action(keyp);
return true;
}
} else {
if (!IS_NOEVENT(event)) debug("Tapping: other key just after tap.\n");
process_action(keyp);
return true;
}
} else {
// FIX: process_aciton here?
// timeout. no sequential tap.
debug("Tapping: End(Timeout after releasing last tap): ");
debug_event(event); debug("\n");
tapping_key = (keyrecord_t){};
debug_tapping_key();
return false;
}
}
// not tapping state
else {
if (event.pressed && is_tap_key(event.key)) {
debug("Tapping: Start(Press tap key).\n");
tapping_key = *keyp;
waiting_buffer_scan_tap();
debug_tapping_key();
return true;
} else {
process_action(keyp);
return true;
}
}
}
/*
* Waiting buffer
*/
bool waiting_buffer_enq(keyrecord_t record)
{
if (IS_NOEVENT(record.event)) {
return true;
}
if ((waiting_buffer_head + 1) % WAITING_BUFFER_SIZE == waiting_buffer_tail) {
debug("waiting_buffer_enq: Over flow.\n");
return false;
}
waiting_buffer[waiting_buffer_head] = record;
waiting_buffer_head = (waiting_buffer_head + 1) % WAITING_BUFFER_SIZE;
debug("waiting_buffer_enq: "); debug_waiting_buffer();
return true;
}
void waiting_buffer_clear(void)
{
waiting_buffer_head = 0;
waiting_buffer_tail = 0;
}
bool waiting_buffer_typed(keyevent_t event)
{
for (uint8_t i = waiting_buffer_tail; i != waiting_buffer_head; i = (i + 1) % WAITING_BUFFER_SIZE) {
if (KEYEQ(event.key, waiting_buffer[i].event.key) && event.pressed != waiting_buffer[i].event.pressed) {
return true;
}
}
return false;
}
bool waiting_buffer_has_anykey_pressed(void)
{
for (uint8_t i = waiting_buffer_tail; i != waiting_buffer_head; i = (i + 1) % WAITING_BUFFER_SIZE) {
if (waiting_buffer[i].event.pressed) return true;
}
return false;
}
/* scan buffer for tapping */
void waiting_buffer_scan_tap(void)
{
// tapping already is settled
if (tapping_key.tap.count > 0) return;
// invalid state: tapping_key released && tap.count == 0
if (!tapping_key.event.pressed) return;
for (uint8_t i = waiting_buffer_tail; i != waiting_buffer_head; i = (i + 1) % WAITING_BUFFER_SIZE) {
if (IS_TAPPING_KEY(waiting_buffer[i].event.key) &&
!waiting_buffer[i].event.pressed &&
WITHIN_TAPPING_TERM(waiting_buffer[i].event)) {
tapping_key.tap.count = 1;
waiting_buffer[i].tap.count = 1;
process_action(&tapping_key);
debug("waiting_buffer_scan_tap: found at ["); debug_dec(i); debug("]\n");
debug_waiting_buffer();
return;
}
}
}
/*
* debug print
*/
static void debug_tapping_key(void)
{
debug("TAPPING_KEY="); debug_record(tapping_key); debug("\n");
}
static void debug_waiting_buffer(void)
{
debug("{ ");
for (uint8_t i = waiting_buffer_tail; i != waiting_buffer_head; i = (i + 1) % WAITING_BUFFER_SIZE) {
debug("["); debug_dec(i); debug("]="); debug_record(waiting_buffer[i]); debug(" ");
}
debug("}\n");
}
#endif

39
common/action_tapping.h Normal file
View file

@ -0,0 +1,39 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef ACTION_TAPPING_H
#define ACTION_TAPPING_H
/* period of tapping(ms) */
#ifndef TAPPING_TERM
#define TAPPING_TERM 200
#endif
/* tap count needed for toggling a feature */
#ifndef TAPPING_TOGGLE
#define TAPPING_TOGGLE 5
#endif
#define WAITING_BUFFER_SIZE 8
#ifndef NO_ACTION_TAPPING
void action_tapping_process(keyrecord_t record);
#endif
#endif

307
common/action_util.c Normal file
View file

@ -0,0 +1,307 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 "host.h"
#include "report.h"
#include "debug.h"
#include "action_util.h"
#include "timer.h"
static inline void add_key_byte(uint8_t code);
static inline void del_key_byte(uint8_t code);
#ifdef NKRO_ENABLE
static inline void add_key_bit(uint8_t code);
static inline void del_key_bit(uint8_t code);
#endif
static uint8_t real_mods = 0;
static uint8_t weak_mods = 0;
#ifdef USB_6KRO_ENABLE
#define RO_ADD(a, b) ((a + b) % KEYBOARD_REPORT_KEYS)
#define RO_SUB(a, b) ((a - b + KEYBOARD_REPORT_KEYS) % KEYBOARD_REPORT_KEYS)
#define RO_INC(a) RO_ADD(a, 1)
#define RO_DEC(a) RO_SUB(a, 1)
static int8_t cb_head = 0;
static int8_t cb_tail = 0;
static int8_t cb_count = 0;
#endif
// TODO: pointer variable is not needed
//report_keyboard_t keyboard_report = {};
report_keyboard_t *keyboard_report = &(report_keyboard_t){};
#ifndef NO_ACTION_ONESHOT
static int8_t oneshot_mods = 0;
#if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0))
static int16_t oneshot_time = 0;
#endif
#endif
void send_keyboard_report(void) {
keyboard_report->mods = real_mods;
keyboard_report->mods |= weak_mods;
#ifndef NO_ACTION_ONESHOT
if (oneshot_mods) {
#if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0))
if (TIMER_DIFF_16(timer_read(), oneshot_time) >= ONESHOT_TIMEOUT) {
dprintf("Oneshot: timeout\n");
clear_oneshot_mods();
}
#endif
keyboard_report->mods |= oneshot_mods;
if (has_anykey()) {
clear_oneshot_mods();
}
}
#endif
host_keyboard_send(keyboard_report);
}
/* key */
void add_key(uint8_t key)
{
#ifdef NKRO_ENABLE
if (keyboard_nkro) {
add_key_bit(key);
return;
}
#endif
add_key_byte(key);
}
void del_key(uint8_t key)
{
#ifdef NKRO_ENABLE
if (keyboard_nkro) {
del_key_bit(key);
return;
}
#endif
del_key_byte(key);
}
void clear_keys(void)
{
// not clear mods
for (int8_t i = 1; i < KEYBOARD_REPORT_SIZE; i++) {
keyboard_report->raw[i] = 0;
}
}
/* modifier */
uint8_t get_mods(void) { return real_mods; }
void add_mods(uint8_t mods) { real_mods |= mods; }
void del_mods(uint8_t mods) { real_mods &= ~mods; }
void set_mods(uint8_t mods) { real_mods = mods; }
void clear_mods(void) { real_mods = 0; }
/* weak modifier */
uint8_t get_weak_mods(void) { return weak_mods; }
void add_weak_mods(uint8_t mods) { weak_mods |= mods; }
void del_weak_mods(uint8_t mods) { weak_mods &= ~mods; }
void set_weak_mods(uint8_t mods) { weak_mods = mods; }
void clear_weak_mods(void) { weak_mods = 0; }
/* Oneshot modifier */
#ifndef NO_ACTION_ONESHOT
void set_oneshot_mods(uint8_t mods)
{
oneshot_mods = mods;
#if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0))
oneshot_time = timer_read();
#endif
}
void clear_oneshot_mods(void)
{
oneshot_mods = 0;
#if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0))
oneshot_time = 0;
#endif
}
#endif
/*
* inspect keyboard state
*/
uint8_t has_anykey(void)
{
uint8_t cnt = 0;
for (uint8_t i = 1; i < KEYBOARD_REPORT_SIZE; i++) {
if (keyboard_report->raw[i])
cnt++;
}
return cnt;
}
uint8_t has_anymod(void)
{
return bitpop(real_mods);
}
uint8_t get_first_key(void)
{
#ifdef NKRO_ENABLE
if (keyboard_nkro) {
uint8_t i = 0;
for (; i < KEYBOARD_REPORT_BITS && !keyboard_report->nkro.bits[i]; i++)
;
return i<<3 | biton(keyboard_report->nkro.bits[i]);
}
#endif
#ifdef USB_6KRO_ENABLE
uint8_t i = cb_head;
do {
if (keyboard_report->keys[i] != 0) {
break;
}
i = RO_INC(i);
} while (i != cb_tail);
return keyboard_report->keys[i];
#else
return keyboard_report->keys[0];
#endif
}
/* local functions */
static inline void add_key_byte(uint8_t code)
{
#ifdef USB_6KRO_ENABLE
int8_t i = cb_head;
int8_t empty = -1;
if (cb_count) {
do {
if (keyboard_report->keys[i] == code) {
return;
}
if (empty == -1 && keyboard_report->keys[i] == 0) {
empty = i;
}
i = RO_INC(i);
} while (i != cb_tail);
if (i == cb_tail) {
if (cb_tail == cb_head) {
// buffer is full
if (empty == -1) {
// pop head when has no empty space
cb_head = RO_INC(cb_head);
cb_count--;
}
else {
// left shift when has empty space
uint8_t offset = 1;
i = RO_INC(empty);
do {
if (keyboard_report->keys[i] != 0) {
keyboard_report->keys[empty] = keyboard_report->keys[i];
keyboard_report->keys[i] = 0;
empty = RO_INC(empty);
}
else {
offset++;
}
i = RO_INC(i);
} while (i != cb_tail);
cb_tail = RO_SUB(cb_tail, offset);
}
}
}
}
// add to tail
keyboard_report->keys[cb_tail] = code;
cb_tail = RO_INC(cb_tail);
cb_count++;
#else
int8_t i = 0;
int8_t empty = -1;
for (; i < KEYBOARD_REPORT_KEYS; i++) {
if (keyboard_report->keys[i] == code) {
break;
}
if (empty == -1 && keyboard_report->keys[i] == 0) {
empty = i;
}
}
if (i == KEYBOARD_REPORT_KEYS) {
if (empty != -1) {
keyboard_report->keys[empty] = code;
}
}
#endif
}
static inline void del_key_byte(uint8_t code)
{
#ifdef USB_6KRO_ENABLE
uint8_t i = cb_head;
if (cb_count) {
do {
if (keyboard_report->keys[i] == code) {
keyboard_report->keys[i] = 0;
cb_count--;
if (cb_count == 0) {
// reset head and tail
cb_tail = cb_head = 0;
}
if (i == RO_DEC(cb_tail)) {
// left shift when next to tail
do {
cb_tail = RO_DEC(cb_tail);
if (keyboard_report->keys[RO_DEC(cb_tail)] != 0) {
break;
}
} while (cb_tail != cb_head);
}
break;
}
i = RO_INC(i);
} while (i != cb_tail);
}
#else
for (uint8_t i = 0; i < KEYBOARD_REPORT_KEYS; i++) {
if (keyboard_report->keys[i] == code) {
keyboard_report->keys[i] = 0;
}
}
#endif
}
#ifdef NKRO_ENABLE
static inline void add_key_bit(uint8_t code)
{
if ((code>>3) < KEYBOARD_REPORT_BITS) {
keyboard_report->nkro.bits[code>>3] |= 1<<(code&7);
} else {
dprintf("add_key_bit: can't add: %02X\n", code);
}
}
static inline void del_key_bit(uint8_t code)
{
if ((code>>3) < KEYBOARD_REPORT_BITS) {
keyboard_report->nkro.bits[code>>3] &= ~(1<<(code&7));
} else {
dprintf("del_key_bit: can't del: %02X\n", code);
}
}
#endif

66
common/action_util.h Normal file
View file

@ -0,0 +1,66 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef ACTION_UTIL_H
#define ACTION_UTIL_H
#include <stdint.h>
#include "report.h"
#ifdef __cplusplus
extern "C" {
#endif
extern report_keyboard_t *keyboard_report;
void send_keyboard_report(void);
/* key */
void add_key(uint8_t key);
void del_key(uint8_t key);
void clear_keys(void);
/* modifier */
uint8_t get_mods(void);
void add_mods(uint8_t mods);
void del_mods(uint8_t mods);
void set_mods(uint8_t mods);
void clear_mods(void);
/* weak modifier */
uint8_t get_weak_mods(void);
void add_weak_mods(uint8_t mods);
void del_weak_mods(uint8_t mods);
void set_weak_mods(uint8_t mods);
void clear_weak_mods(void);
/* oneshot modifier */
void set_oneshot_mods(uint8_t mods);
void clear_oneshot_mods(void);
void oneshot_toggle(void);
void oneshot_enable(void);
void oneshot_disable(void);
/* inspect */
uint8_t has_anykey(void);
uint8_t has_anymod(void);
uint8_t get_first_key(void);
#ifdef __cplusplus
}
#endif
#endif

148
common/avr/bootloader.c Normal file
View file

@ -0,0 +1,148 @@
#include <stdint.h>
#include <stdbool.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <util/delay.h>
#include "bootloader.h"
#ifdef PROTOCOL_LUFA
#include <LUFA/Drivers/USB/USB.h>
#endif
/* Boot Section Size in *BYTEs*
* Teensy halfKay 512
* Teensy++ halfKay 1024
* Atmel DFU loader 4096
* LUFA bootloader 4096
* USBaspLoader 2048
*/
#ifndef BOOTLOADER_SIZE
#warning To use bootloader_jump() you need to define BOOTLOADER_SIZE in config.h.
#define BOOTLOADER_SIZE 4096
#endif
#define FLASH_SIZE (FLASHEND + 1L)
#define BOOTLOADER_START (FLASH_SIZE - BOOTLOADER_SIZE)
/*
* Entering the Bootloader via Software
* http://www.fourwalledcubicle.com/files/LUFA/Doc/120730/html/_page__software_bootloader_start.html
*/
#define BOOTLOADER_RESET_KEY 0xB007B007
uint32_t reset_key __attribute__ ((section (".noinit")));
/* initialize MCU status by watchdog reset */
void bootloader_jump(void) {
#ifdef PROTOCOL_LUFA
USB_Disable();
cli();
_delay_ms(2000);
#endif
#ifdef PROTOCOL_PJRC
cli();
UDCON = 1;
USBCON = (1<<FRZCLK);
UCSR1B = 0;
_delay_ms(5);
#endif
// watchdog reset
reset_key = BOOTLOADER_RESET_KEY;
wdt_enable(WDTO_250MS);
for (;;);
}
/* this runs before main() */
void bootloader_jump_after_watchdog_reset(void) __attribute__ ((used, naked, section (".init3")));
void bootloader_jump_after_watchdog_reset(void)
{
if ((MCUSR & (1<<WDRF)) && reset_key == BOOTLOADER_RESET_KEY) {
reset_key = 0;
// My custom USBasploader requires this to come up.
MCUSR = 0;
// Seems like Teensy halfkay loader requires clearing WDRF and disabling watchdog.
MCUSR &= ~(1<<WDRF);
wdt_disable();
// This is compled into 'icall', address should be in word unit, not byte.
((void (*)(void))(BOOTLOADER_START/2))();
}
}
#if 0
/* Jumping To The Bootloader
* http://www.pjrc.com/teensy/jump_to_bootloader.html
*
* This method doen't work when using LUFA. idk why.
* - needs to initialize more regisers or interrupt setting?
*/
void bootloader_jump(void) {
#ifdef PROTOCOL_LUFA
USB_Disable();
cli();
_delay_ms(2000);
#endif
#ifdef PROTOCOL_PJRC
cli();
UDCON = 1;
USBCON = (1<<FRZCLK);
UCSR1B = 0;
_delay_ms(5);
#endif
/*
* Initialize
*/
#if defined(__AVR_AT90USB162__)
EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0;
TIMSK0 = 0; TIMSK1 = 0; UCSR1B = 0;
DDRB = 0; DDRC = 0; DDRD = 0;
PORTB = 0; PORTC = 0; PORTD = 0;
#elif defined(__AVR_ATmega32U4__)
EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
TIMSK0 = 0; TIMSK1 = 0; TIMSK3 = 0; TIMSK4 = 0; UCSR1B = 0; TWCR = 0;
DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; TWCR = 0;
PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
#elif defined(__AVR_AT90USB646__)
EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
#elif defined(__AVR_AT90USB1286__)
EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
#endif
/*
* USBaspLoader
*/
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || defined(__AVR_ATmega328P__)
// This makes custom USBasploader come up.
MCUSR = 0;
// initialize ports
PORTB = 0; PORTC= 0; PORTD = 0;
DDRB = 0; DDRC= 0; DDRD = 0;
// disable interrupts
EIMSK = 0; EECR = 0; SPCR = 0;
ACSR = 0; SPMCSR = 0; WDTCSR = 0; PCICR = 0;
TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0;
ADCSRA = 0; TWCR = 0; UCSR0B = 0;
#endif
// This is compled into 'icall', address should be in word unit, not byte.
((void (*)(void))(BOOTLOADER_START/2))();
}
#endif

45
common/avr/eeconfig.c Normal file
View file

@ -0,0 +1,45 @@
#include <stdint.h>
#include <stdbool.h>
#include <avr/eeprom.h>
#include "eeconfig.h"
void eeconfig_init(void)
{
eeprom_write_word(EECONFIG_MAGIC, EECONFIG_MAGIC_NUMBER);
eeprom_write_byte(EECONFIG_DEBUG, 0);
eeprom_write_byte(EECONFIG_DEFAULT_LAYER, 0);
eeprom_write_byte(EECONFIG_KEYMAP, 0);
eeprom_write_byte(EECONFIG_MOUSEKEY_ACCEL, 0);
#ifdef BACKLIGHT_ENABLE
eeprom_write_byte(EECONFIG_BACKLIGHT, 0);
#endif
}
void eeconfig_enable(void)
{
eeprom_write_word(EECONFIG_MAGIC, EECONFIG_MAGIC_NUMBER);
}
void eeconfig_disable(void)
{
eeprom_write_word(EECONFIG_MAGIC, 0xFFFF);
}
bool eeconfig_is_enabled(void)
{
return (eeprom_read_word(EECONFIG_MAGIC) == EECONFIG_MAGIC_NUMBER);
}
uint8_t eeconfig_read_debug(void) { return eeprom_read_byte(EECONFIG_DEBUG); }
void eeconfig_write_debug(uint8_t val) { eeprom_write_byte(EECONFIG_DEBUG, val); }
uint8_t eeconfig_read_default_layer(void) { return eeprom_read_byte(EECONFIG_DEFAULT_LAYER); }
void eeconfig_write_default_layer(uint8_t val) { eeprom_write_byte(EECONFIG_DEFAULT_LAYER, val); }
uint8_t eeconfig_read_keymap(void) { return eeprom_read_byte(EECONFIG_KEYMAP); }
void eeconfig_write_keymap(uint8_t val) { eeprom_write_byte(EECONFIG_KEYMAP, val); }
#ifdef BACKLIGHT_ENABLE
uint8_t eeconfig_read_backlight(void) { return eeprom_read_byte(EECONFIG_BACKLIGHT); }
void eeconfig_write_backlight(uint8_t val) { eeprom_write_byte(EECONFIG_BACKLIGHT, val); }
#endif

122
common/avr/suspend.c Normal file
View file

@ -0,0 +1,122 @@
#include <stdbool.h>
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#include "matrix.h"
#include "action.h"
#include "backlight.h"
#include "suspend_avr.h"
#include "suspend.h"
#include "timer.h"
#ifdef PROTOCOL_LUFA
#include "lufa.h"
#endif
#define wdt_intr_enable(value) \
__asm__ __volatile__ ( \
"in __tmp_reg__,__SREG__" "\n\t" \
"cli" "\n\t" \
"wdr" "\n\t" \
"sts %0,%1" "\n\t" \
"out __SREG__,__tmp_reg__" "\n\t" \
"sts %0,%2" "\n\t" \
: /* no outputs */ \
: "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \
"r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \
"r" ((uint8_t) ((value & 0x08 ? _WD_PS3_MASK : 0x00) | \
_BV(WDIE) | (value & 0x07)) ) \
: "r0" \
)
void suspend_idle(uint8_t time)
{
cli();
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_enable();
sei();
sleep_cpu();
sleep_disable();
}
/* Power down MCU with watchdog timer
* wdto: watchdog timer timeout defined in <avr/wdt.h>
* WDTO_15MS
* WDTO_30MS
* WDTO_60MS
* WDTO_120MS
* WDTO_250MS
* WDTO_500MS
* WDTO_1S
* WDTO_2S
* WDTO_4S
* WDTO_8S
*/
static uint8_t wdt_timeout = 0;
static void power_down(uint8_t wdto)
{
#ifdef PROTOCOL_LUFA
if (USB_DeviceState == DEVICE_STATE_Configured) return;
#endif
wdt_timeout = wdto;
// Watchdog Interrupt Mode
wdt_intr_enable(wdto);
// TODO: more power saving
// See PicoPower application note
// - I/O port input with pullup
// - prescale clock
// - BOD disable
// - Power Reduction Register PRR
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sei();
sleep_cpu();
sleep_disable();
// Disable watchdog after sleep
wdt_disable();
}
void suspend_power_down(void)
{
power_down(WDTO_15MS);
}
bool suspend_wakeup_condition(void)
{
matrix_power_up();
matrix_scan();
matrix_power_down();
for (uint8_t r = 0; r < MATRIX_ROWS; r++) {
if (matrix_get_row(r)) return true;
}
return false;
}
// run immediately after wakeup
void suspend_wakeup_init(void)
{
// clear keyboard state
clear_keyboard();
#ifdef BACKLIGHT_ENABLE
backlight_init();
#endif
}
#ifndef NO_SUSPEND_POWER_DOWN
/* watchdog timeout */
ISR(WDT_vect)
{
// compensate timer for sleep
switch (wdt_timeout) {
case WDTO_15MS:
timer_count += 15 + 2; // WDTO_15MS + 2(from observation)
break;
default:
;
}
}
#endif

27
common/avr/suspend_avr.h Normal file
View file

@ -0,0 +1,27 @@
#ifndef SUSPEND_AVR_H
#define SUSPEND_AVR_H
#include <stdint.h>
#include <stdbool.h>
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#define wdt_intr_enable(value) \
__asm__ __volatile__ ( \
"in __tmp_reg__,__SREG__" "\n\t" \
"cli" "\n\t" \
"wdr" "\n\t" \
"sts %0,%1" "\n\t" \
"out __SREG__,__tmp_reg__" "\n\t" \
"sts %0,%2" "\n\t" \
: /* no outputs */ \
: "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \
"r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \
"r" ((uint8_t) ((value & 0x08 ? _WD_PS3_MASK : 0x00) | \
_BV(WDIE) | (value & 0x07)) ) \
: "r0" \
)
#endif

117
common/avr/timer.c Normal file
View file

@ -0,0 +1,117 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <avr/io.h>
#include <avr/interrupt.h>
#include <stdint.h>
#include "timer_avr.h"
#include "timer.h"
// counter resolution 1ms
// NOTE: union { uint32_t timer32; struct { uint16_t dummy; uint16_t timer16; }}
volatile uint32_t timer_count = 0;
void timer_init(void)
{
// Timer0 CTC mode
TCCR0A = 0x02;
#if TIMER_PRESCALER == 1
TCCR0B = 0x01;
#elif TIMER_PRESCALER == 8
TCCR0B = 0x02;
#elif TIMER_PRESCALER == 64
TCCR0B = 0x03;
#elif TIMER_PRESCALER == 256
TCCR0B = 0x04;
#elif TIMER_PRESCALER == 1024
TCCR0B = 0x05;
#else
# error "Timer prescaler value is NOT vaild."
#endif
OCR0A = TIMER_RAW_TOP;
TIMSK0 = (1<<OCIE0A);
}
inline
void timer_clear(void)
{
uint8_t sreg = SREG;
cli();
timer_count = 0;
SREG = sreg;
}
inline
uint16_t timer_read(void)
{
uint32_t t;
uint8_t sreg = SREG;
cli();
t = timer_count;
SREG = sreg;
return (t & 0xFFFF);
}
inline
uint32_t timer_read32(void)
{
uint32_t t;
uint8_t sreg = SREG;
cli();
t = timer_count;
SREG = sreg;
return t;
}
inline
uint16_t timer_elapsed(uint16_t last)
{
uint32_t t;
uint8_t sreg = SREG;
cli();
t = timer_count;
SREG = sreg;
return TIMER_DIFF_16((t & 0xFFFF), last);
}
inline
uint32_t timer_elapsed32(uint32_t last)
{
uint32_t t;
uint8_t sreg = SREG;
cli();
t = timer_count;
SREG = sreg;
return TIMER_DIFF_32(t, last);
}
// excecuted once per 1ms.(excess for just timer count?)
ISR(TIMER0_COMPA_vect)
{
timer_count++;
}

42
common/avr/timer_avr.h Normal file
View file

@ -0,0 +1,42 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef TIMER_AVR_H
#define TIMER_AVR_H 1
#include <stdint.h>
#ifndef TIMER_PRESCALER
# if F_CPU > 16000000
# define TIMER_PRESCALER 256
# elif F_CPU > 2000000
# define TIMER_PRESCALER 64
# elif F_CPU > 250000
# define TIMER_PRESCALER 8
# else
# define TIMER_PRESCALER 1
# endif
#endif
#define TIMER_RAW_FREQ (F_CPU/TIMER_PRESCALER)
#define TIMER_RAW TCNT0
#define TIMER_RAW_TOP (TIMER_RAW_FREQ/1000)
#if (TIMER_RAW_TOP > 255)
# error "Timer0 can't count 1ms at this clock freq. Use larger prescaler."
#endif
#endif

500
common/avr/xprintf.S Normal file
View file

@ -0,0 +1,500 @@
;---------------------------------------------------------------------------;
; Extended itoa, puts, printf and atoi (C)ChaN, 2011
;---------------------------------------------------------------------------;
// Base size is 152 bytes
#define CR_CRLF 0 // Convert \n to \r\n (+10 bytes)
#define USE_XPRINTF 1 // Enable xprintf function (+194 bytes)
#define USE_XSPRINTF 0 // Add xsprintf function (+78 bytes)
#define USE_XFPRINTF 0 // Add xfprintf function (+54 bytes)
#define USE_XATOI 0 // Enable xatoi function (+182 bytes)
#if FLASHEND > 0x1FFFF
#error xitoa module does not support 256K devices
#endif
.nolist
#include <avr/io.h> // Include device specific definitions.
.list
#ifdef SPM_PAGESIZE // Recent devices have "lpm Rd,Z+" and "movw".
.macro _LPMI reg
lpm \reg, Z+
.endm
.macro _MOVW dh,dl, sh,sl
movw \dl, \sl
.endm
#else // Earlier devices do not have "lpm Rd,Z+" nor "movw".
.macro _LPMI reg
lpm
mov \reg, r0
adiw ZL, 1
.endm
.macro _MOVW dh,dl, sh,sl
mov \dl, \sl
mov \dh, \sh
.endm
#endif
;---------------------------------------------------------------------------
; Stub function to forward to user output function
;
;Prototype: void xputc (char chr // a character to be output
; );
;Size: 12/12 words
.section .bss
.global xfunc_out ; xfunc_out must be initialized before using this module.
xfunc_out: .ds.w 1
.section .text
.func xputc
.global xputc
xputc:
#if CR_CRLF
cpi r24, 10 ;LF --> CRLF
brne 1f ;
ldi r24, 13 ;
rcall 1f ;
ldi r24, 10 ;/
1:
#endif
push ZH
push ZL
lds ZL, xfunc_out+0 ;Pointer to the registered output function.
lds ZH, xfunc_out+1 ;/
sbiw ZL, 0 ;Skip if null
breq 2f ;/
icall
2: pop ZL
pop ZH
ret
.endfunc
;---------------------------------------------------------------------------
; Direct ROM string output
;
;Prototype: void xputs (const char *str_p // rom string to be output
; );
.func xputs
.global xputs
xputs:
_MOVW ZH,ZL, r25,r24 ; Z = pointer to rom string
1: _LPMI r24
cpi r24, 0
breq 2f
rcall xputc
rjmp 1b
2: ret
.endfunc
;---------------------------------------------------------------------------
; Extended direct numeral string output (32bit version)
;
;Prototype: void xitoa (long value, // value to be output
; char radix, // radix
; char width); // minimum width
;
.func xitoa
.global xitoa
xitoa:
;r25:r22 = value, r20 = base, r18 = digits
clr r31 ;r31 = stack level
ldi r30, ' ' ;r30 = sign
ldi r19, ' ' ;r19 = filler
sbrs r20, 7 ;When base indicates signd format and the value
rjmp 0f ;is minus, add a '-'.
neg r20 ;
sbrs r25, 7 ;
rjmp 0f ;
ldi r30, '-' ;
com r22 ;
com r23 ;
com r24 ;
com r25 ;
adc r22, r1 ;
adc r23, r1 ;
adc r24, r1 ;
adc r25, r1 ;/
0: sbrs r18, 7 ;When digits indicates zero filled,
rjmp 1f ;filler is '0'.
neg r18 ;
ldi r19, '0' ;/
;----- string conversion loop
1: ldi r21, 32 ;r26 = r25:r22 % r20
clr r26 ;r25:r22 /= r20
2: lsl r22 ;
rol r23 ;
rol r24 ;
rol r25 ;
rol r26 ;
cp r26, r20 ;
brcs 3f ;
sub r26, r20 ;
inc r22 ;
3: dec r21 ;
brne 2b ;/
cpi r26, 10 ;r26 is a numeral digit '0'-'F'
brcs 4f ;
subi r26, -7 ;
4: subi r26, -'0' ;/
push r26 ;Stack it
inc r31 ;/
cp r22, r1 ;Repeat until r25:r22 gets zero
cpc r23, r1 ;
cpc r24, r1 ;
cpc r25, r1 ;
brne 1b ;/
cpi r30, '-' ;Minus sign if needed
brne 5f ;
push r30 ;
inc r31 ;/
5: cp r31, r18 ;Filler
brcc 6f ;
push r19 ;
inc r31 ;
rjmp 5b ;/
6: pop r24 ;Flush stacked digits and exit
rcall xputc ;
dec r31 ;
brne 6b ;/
ret
.endfunc
;---------------------------------------------------------------------------;
; Formatted string output (16/32bit version)
;
;Prototype:
; void __xprintf (const char *format_p, ...);
; void __xsprintf(char*, const char *format_p, ...);
; void __xfprintf(void(*func)(char), const char *format_p, ...);
;
#if USE_XPRINTF
.func xvprintf
xvprintf:
ld ZL, Y+ ;Z = pointer to format string
ld ZH, Y+ ;/
0: _LPMI r24 ;Get a format char
cpi r24, 0 ;End of format string?
breq 90f ;/
cpi r24, '%' ;Is format?
breq 20f ;/
1: rcall xputc ;Put a normal character
rjmp 0b ;/
90: ret
20: ldi r18, 0 ;r18: digits
clt ;T: filler
_LPMI r21 ;Get flags
cpi r21, '%' ;Is a %?
breq 1b ;/
cpi r21, '0' ;Zero filled?
brne 23f ;
set ;/
22: _LPMI r21 ;Get width
23: cpi r21, '9'+1 ;
brcc 24f ;
subi r21, '0' ;
brcs 90b ;
lsl r18 ;
mov r0, r18 ;
lsl r18 ;
lsl r18 ;
add r18, r0 ;
add r18, r21 ;
rjmp 22b ;/
24: brtc 25f ;get value (low word)
neg r18 ;
25: ld r24, Y+ ;
ld r25, Y+ ;/
cpi r21, 'c' ;Is type character?
breq 1b ;/
cpi r21, 's' ;Is type RAM string?
breq 50f ;/
cpi r21, 'S' ;Is type ROM string?
breq 60f ;/
_MOVW r23,r22,r25,r24 ;r25:r22 = value
clr r24 ;
clr r25 ;
clt ;/
cpi r21, 'l' ;Is long int?
brne 26f ;
ld r24, Y+ ;get value (high word)
ld r25, Y+ ;
set ;
_LPMI r21 ;/
26: cpi r21, 'd' ;Is type signed decimal?
brne 27f ;/
ldi r20, -10 ;
brts 40f ;
sbrs r23, 7 ;
rjmp 40f ;
ldi r24, -1 ;
ldi r25, -1 ;
rjmp 40f ;/
27: cpi r21, 'u' ;Is type unsigned decimal?
ldi r20, 10 ;
breq 40f ;/
cpi r21, 'X' ;Is type hexdecimal?
ldi r20, 16 ;
breq 40f ;/
cpi r21, 'b' ;Is type binary?
ldi r20, 2 ;
breq 40f ;/
ret ;abort
40: push ZH ;Output the value
push ZL ;
rcall xitoa ;
42: pop ZL ;
pop ZH ;
rjmp 0b ;/
50: push ZH ;Put a string on the RAM
push ZL
_MOVW ZH,ZL, r25,r24
51: ld r24, Z+
cpi r24, 0
breq 42b
rcall xputc
rjmp 51b
60: push ZH ;Put a string on the ROM
push ZL
rcall xputs
rjmp 42b
.endfunc
.func __xprintf
.global __xprintf
__xprintf:
push YH
push YL
in YL, _SFR_IO_ADDR(SPL)
#ifdef SPH
in YH, _SFR_IO_ADDR(SPH)
#else
clr YH
#endif
adiw YL, 5 ;Y = pointer to arguments
rcall xvprintf
pop YL
pop YH
ret
.endfunc
#if USE_XSPRINTF
.func __xsprintf
putram:
_MOVW ZH,ZL, r15,r14
st Z+, r24
_MOVW r15,r14, ZH,ZL
ret
.global __xsprintf
__xsprintf:
push YH
push YL
in YL, _SFR_IO_ADDR(SPL)
#ifdef SPH
in YH, _SFR_IO_ADDR(SPH)
#else
clr YH
#endif
adiw YL, 5 ;Y = pointer to arguments
lds ZL, xfunc_out+0 ;Save registered output function
lds ZH, xfunc_out+1 ;
push ZL ;
push ZH ;/
ldi ZL, lo8(pm(putram));Set local output function
ldi ZH, hi8(pm(putram));
sts xfunc_out+0, ZL ;
sts xfunc_out+1, ZH ;/
push r15 ;Initialize pointer to string buffer
push r14 ;
ld r14, Y+ ;
ld r15, Y+ ;/
rcall xvprintf
_MOVW ZH,ZL, r15,r14 ;Terminate string
st Z, r1 ;
pop r14 ;
pop r15 ;/
pop ZH ;Restore registered output function
pop ZL ;
sts xfunc_out+0, ZL ;
sts xfunc_out+1, ZH ;/
pop YL
pop YH
ret
.endfunc
#endif
#if USE_XFPRINTF
.func __xfprintf
.global __xfprintf
__xfprintf:
push YH
push YL
in YL, _SFR_IO_ADDR(SPL)
#ifdef SPH
in YH, _SFR_IO_ADDR(SPH)
#else
clr YH
#endif
adiw YL, 5 ;Y = pointer to arguments
lds ZL, xfunc_out+0 ;Save registered output function
lds ZH, xfunc_out+1 ;
push ZL ;
push ZH ;/
ld ZL, Y+ ;Set output function
ld ZH, Y+ ;
sts xfunc_out+0, ZL ;
sts xfunc_out+1, ZH ;/
rcall xvprintf
pop ZH ;Restore registered output function
pop ZL ;
sts xfunc_out+0, ZL ;
sts xfunc_out+1, ZH ;/
pop YL
pop YH
ret
.endfunc
#endif
#endif
;---------------------------------------------------------------------------
; Extended numeral string input
;
;Prototype:
; char xatoi ( /* 1: Successful, 0: Failed */
; const char **str, /* pointer to pointer to source string */
; long *res /* result */
; );
;
#if USE_XATOI
.func xatoi
.global xatoi
xatoi:
_MOVW r1, r0, r23, r22
_MOVW XH, XL, r25, r24
ld ZL, X+
ld ZH, X+
clr r18 ;r21:r18 = 0;
clr r19 ;
clr r20 ;
clr r21 ;/
clt ;T = 0;
ldi r25, 10 ;r25 = 10;
rjmp 41f ;/
40: adiw ZL, 1 ;Z++;
41: ld r22, Z ;r22 = *Z;
cpi r22, ' ' ;if(r22 == ' ') continue
breq 40b ;/
brcs 70f ;if(r22 < ' ') error;
cpi r22, '-' ;if(r22 == '-') {
brne 42f ; T = 1;
set ; continue;
rjmp 40b ;}
42: cpi r22, '9'+1 ;if(r22 > '9') error;
brcc 70f ;/
cpi r22, '0' ;if(r22 < '0') error;
brcs 70f ;/
brne 51f ;if(r22 > '0') cv_start;
ldi r25, 8 ;r25 = 8;
adiw ZL, 1 ;r22 = *(++Z);
ld r22, Z ;/
cpi r22, ' '+1 ;if(r22 <= ' ') exit;
brcs 80f ;/
cpi r22, 'b' ;if(r22 == 'b') {
brne 43f ; r25 = 2;
ldi r25, 2 ; cv_start;
rjmp 50f ;}
43: cpi r22, 'x' ;if(r22 != 'x') error;
brne 51f ;/
ldi r25, 16 ;r25 = 16;
50: adiw ZL, 1 ;Z++;
ld r22, Z ;r22 = *Z;
51: cpi r22, ' '+1 ;if(r22 <= ' ') break;
brcs 80f ;/
cpi r22, 'a' ;if(r22 >= 'a') r22 =- 0x20;
brcs 52f ;
subi r22, 0x20 ;/
52: subi r22, '0' ;if((r22 -= '0') < 0) error;
brcs 70f ;/
cpi r22, 10 ;if(r22 >= 10) {
brcs 53f ; r22 -= 7;
subi r22, 7 ; if(r22 < 10)
cpi r22, 10 ;
brcs 70f ;}
53: cp r22, r25 ;if(r22 >= r25) error;
brcc 70f ;/
60: ldi r24, 33 ;r21:r18 *= r25;
sub r23, r23 ;
61: brcc 62f ;
add r23, r25 ;
62: lsr r23 ;
ror r21 ;
ror r20 ;
ror r19 ;
ror r18 ;
dec r24 ;
brne 61b ;/
add r18, r22 ;r21:r18 += r22;
adc r19, r24 ;
adc r20, r24 ;
adc r21, r24 ;/
rjmp 50b ;repeat
70: ldi r24, 0
rjmp 81f
80: ldi r24, 1
81: brtc 82f
clr r22
com r18
com r19
com r20
com r21
adc r18, r22
adc r19, r22
adc r20, r22
adc r21, r22
82: st -X, ZH
st -X, ZL
_MOVW XH, XL, r1, r0
st X+, r18
st X+, r19
st X+, r20
st X+, r21
clr r1
ret
.endfunc
#endif

111
common/avr/xprintf.h Normal file
View file

@ -0,0 +1,111 @@
/*---------------------------------------------------------------------------
Extended itoa, puts and printf (C)ChaN, 2011
-----------------------------------------------------------------------------*/
#ifndef XPRINTF_H
#define XPRINTF_H
#include <inttypes.h>
#include <avr/pgmspace.h>
#ifdef __cplusplus
extern "C" {
#endif
extern void (*xfunc_out)(uint8_t);
#define xdev_out(func) xfunc_out = (void(*)(uint8_t))(func)
/* This is a pointer to user defined output function. It must be initialized
before using this modle.
*/
void xputc(char chr);
/* This is a stub function to forward outputs to user defined output function.
All outputs from this module are output via this function.
*/
/*-----------------------------------------------------------------------------*/
void xputs(const char *string_p);
/* The string placed in the ROM is forwarded to xputc() directly.
*/
/*-----------------------------------------------------------------------------*/
void xitoa(long value, char radix, char width);
/* Extended itoa().
value radix width output
100 10 6 " 100"
100 10 -6 "000100"
100 10 0 "100"
4294967295 10 0 "4294967295"
4294967295 -10 0 "-1"
655360 16 -8 "000A0000"
1024 16 0 "400"
0x55 2 -8 "01010101"
*/
/*-----------------------------------------------------------------------------*/
#define xprintf(format, ...) __xprintf(PSTR(format), ##__VA_ARGS__)
#define xsprintf(str, format, ...) __xsprintf(str, PSTR(format), ##__VA_ARGS__)
#define xfprintf(func, format, ...) __xfprintf(func, PSTR(format), ##__VA_ARGS__)
void __xprintf(const char *format_p, ...); /* Send formatted string to the registered device */
void __xsprintf(char*, const char *format_p, ...); /* Put formatted string to the memory */
void __xfprintf(void(*func)(uint8_t), const char *format_p, ...); /* Send formatted string to the specified device */
/* Format string is placed in the ROM. The format flags is similar to printf().
%[flag][width][size]type
flag
A '0' means filled with '0' when output is shorter than width.
' ' is used in default. This is effective only numeral type.
width
Minimum width in decimal number. This is effective only numeral type.
Default width is zero.
size
A 'l' means the argument is long(32bit). Default is short(16bit).
This is effective only numeral type.
type
'c' : Character, argument is the value
's' : String placed on the RAM, argument is the pointer
'S' : String placed on the ROM, argument is the pointer
'd' : Signed decimal, argument is the value
'u' : Unsigned decimal, argument is the value
'X' : Hexdecimal, argument is the value
'b' : Binary, argument is the value
'%' : '%'
*/
/*-----------------------------------------------------------------------------*/
char xatoi(char **str, long *ret);
/* Get value of the numeral string.
str
Pointer to pointer to source string
"0b11001010" binary
"0377" octal
"0xff800" hexdecimal
"1250000" decimal
"-25000" decimal
ret
Pointer to return value
*/
#ifdef __cplusplus
}
#endif
#endif

85
common/backlight.c Normal file
View file

@ -0,0 +1,85 @@
/*
Copyright 2013 Mathias Andersson <wraul@dbox.se>
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, either version 2 of the License, or
(at your option) any later version.
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 "backlight.h"
#include "eeconfig.h"
#include "debug.h"
backlight_config_t backlight_config;
void backlight_init(void)
{
/* check signature */
if (!eeconfig_is_enabled()) {
eeconfig_init();
}
backlight_config.raw = eeconfig_read_backlight();
backlight_set(backlight_config.enable ? backlight_config.level : 0);
}
void backlight_increase(void)
{
if(backlight_config.level < BACKLIGHT_LEVELS)
{
backlight_config.level++;
backlight_config.enable = 1;
eeconfig_write_backlight(backlight_config.raw);
}
dprintf("backlight increase: %u\n", backlight_config.level);
backlight_set(backlight_config.level);
}
void backlight_decrease(void)
{
if(backlight_config.level > 0)
{
backlight_config.level--;
backlight_config.enable = !!backlight_config.level;
eeconfig_write_backlight(backlight_config.raw);
}
dprintf("backlight decrease: %u\n", backlight_config.level);
backlight_set(backlight_config.level);
}
void backlight_toggle(void)
{
backlight_config.enable ^= 1;
eeconfig_write_backlight(backlight_config.raw);
dprintf("backlight toggle: %u\n", backlight_config.enable);
backlight_set(backlight_config.enable ? backlight_config.level : 0);
}
void backlight_step(void)
{
backlight_config.level++;
if(backlight_config.level > BACKLIGHT_LEVELS)
{
backlight_config.level = 0;
}
backlight_config.enable = !!backlight_config.level;
eeconfig_write_backlight(backlight_config.raw);
dprintf("backlight step: %u\n", backlight_config.level);
backlight_set(backlight_config.level);
}
void backlight_level(uint8_t level)
{
backlight_config.level ^= level;
backlight_config.enable = !!backlight_config.level;
eeconfig_write_backlight(backlight_config.raw);
backlight_set(backlight_config.level);
}

40
common/backlight.h Normal file
View file

@ -0,0 +1,40 @@
/*
Copyright 2013 Mathias Andersson <wraul@dbox.se>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef BACKLIGHT_H
#define BACKLIGHT_H
#include <stdint.h>
#include <stdbool.h>
typedef union {
uint8_t raw;
struct {
bool enable :1;
uint8_t level :7;
};
} backlight_config_t;
void backlight_init(void);
void backlight_increase(void);
void backlight_decrease(void);
void backlight_toggle(void);
void backlight_step(void);
void backlight_set(uint8_t level);
void backlight_level(uint8_t level);
#endif

25
common/bootloader.h Normal file
View file

@ -0,0 +1,25 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef BOOTLOADER_H
#define BOOTLOADER_H
/* give code for your bootloader to come up if needed */
void bootloader_jump(void);
#endif

128
common/bootmagic.c Normal file
View file

@ -0,0 +1,128 @@
#include <stdint.h>
#include <stdbool.h>
#include <util/delay.h>
#include "matrix.h"
#include "bootloader.h"
#include "debug.h"
#include "keymap.h"
#include "host.h"
#include "action_layer.h"
#include "eeconfig.h"
#include "bootmagic.h"
void bootmagic(void)
{
/* check signature */
if (!eeconfig_is_enabled()) {
eeconfig_init();
}
/* do scans in case of bounce */
print("boogmagic scan: ... ");
uint8_t scan = 100;
while (scan--) { matrix_scan(); _delay_ms(10); }
print("done.\n");
/* bootmagic skip */
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_SKIP)) {
return;
}
/* eeconfig clear */
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_EEPROM_CLEAR)) {
eeconfig_init();
}
/* bootloader */
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_BOOTLOADER)) {
bootloader_jump();
}
/* debug enable */
debug_config.raw = eeconfig_read_debug();
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEBUG_ENABLE)) {
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEBUG_MATRIX)) {
debug_config.matrix = !debug_config.matrix;
} else if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEBUG_KEYBOARD)) {
debug_config.keyboard = !debug_config.keyboard;
} else if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEBUG_MOUSE)) {
debug_config.mouse = !debug_config.mouse;
} else {
debug_config.enable = !debug_config.enable;
}
}
eeconfig_write_debug(debug_config.raw);
/* keymap config */
keymap_config.raw = eeconfig_read_keymap();
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_SWAP_CONTROL_CAPSLOCK)) {
keymap_config.swap_control_capslock = !keymap_config.swap_control_capslock;
}
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_CAPSLOCK_TO_CONTROL)) {
keymap_config.capslock_to_control = !keymap_config.capslock_to_control;
}
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_SWAP_LALT_LGUI)) {
keymap_config.swap_lalt_lgui = !keymap_config.swap_lalt_lgui;
}
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_SWAP_RALT_RGUI)) {
keymap_config.swap_ralt_rgui = !keymap_config.swap_ralt_rgui;
}
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_NO_GUI)) {
keymap_config.no_gui = !keymap_config.no_gui;
}
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_SWAP_GRAVE_ESC)) {
keymap_config.swap_grave_esc = !keymap_config.swap_grave_esc;
}
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_SWAP_BACKSLASH_BACKSPACE)) {
keymap_config.swap_backslash_backspace = !keymap_config.swap_backslash_backspace;
}
if (bootmagic_scan_keycode(BOOTMAGIC_HOST_NKRO)) {
keymap_config.nkro = !keymap_config.nkro;
}
eeconfig_write_keymap(keymap_config.raw);
#ifdef NKRO_ENABLE
keyboard_nkro = keymap_config.nkro;
#endif
/* default layer */
uint8_t default_layer = 0;
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_0)) { default_layer |= (1<<0); }
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_1)) { default_layer |= (1<<1); }
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_2)) { default_layer |= (1<<2); }
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_3)) { default_layer |= (1<<3); }
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_4)) { default_layer |= (1<<4); }
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_5)) { default_layer |= (1<<5); }
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_6)) { default_layer |= (1<<6); }
if (bootmagic_scan_keycode(BOOTMAGIC_KEY_DEFAULT_LAYER_7)) { default_layer |= (1<<7); }
if (default_layer) {
eeconfig_write_default_layer(default_layer);
default_layer_set((uint32_t)default_layer);
} else {
default_layer = eeconfig_read_default_layer();
default_layer_set((uint32_t)default_layer);
}
}
static bool scan_keycode(uint8_t keycode)
{
for (uint8_t r = 0; r < MATRIX_ROWS; r++) {
matrix_row_t matrix_row = matrix_get_row(r);
for (uint8_t c = 0; c < MATRIX_COLS; c++) {
if (matrix_row & ((matrix_row_t)1<<c)) {
if (keycode == keymap_key_to_keycode(0, (keypos_t){ .row = r, .col = c })) {
return true;
}
}
}
}
return false;
}
bool bootmagic_scan_keycode(uint8_t keycode)
{
if (!scan_keycode(BOOTMAGIC_KEY_SALT)) return false;
return scan_keycode(keycode);
}

100
common/bootmagic.h Normal file
View file

@ -0,0 +1,100 @@
#ifndef BOOTMAGIC_H
#define BOOTMAGIC_H
/* bootmagic salt key */
#ifndef BOOTMAGIC_KEY_SALT
#define BOOTMAGIC_KEY_SALT KC_SPACE
#endif
/* skip bootmagic and eeconfig */
#ifndef BOOTMAGIC_KEY_SKIP
#define BOOTMAGIC_KEY_SKIP KC_ESC
#endif
/* eeprom clear */
#ifndef BOOTMAGIC_KEY_EEPROM_CLEAR
#define BOOTMAGIC_KEY_EEPROM_CLEAR KC_BSPACE
#endif
/* kick up bootloader */
#ifndef BOOTMAGIC_KEY_BOOTLOADER
#define BOOTMAGIC_KEY_BOOTLOADER KC_B
#endif
/* debug enable */
#ifndef BOOTMAGIC_KEY_DEBUG_ENABLE
#define BOOTMAGIC_KEY_DEBUG_ENABLE KC_D
#endif
#ifndef BOOTMAGIC_KEY_DEBUG_MATRIX
#define BOOTMAGIC_KEY_DEBUG_MATRIX KC_X
#endif
#ifndef BOOTMAGIC_KEY_DEBUG_KEYBOARD
#define BOOTMAGIC_KEY_DEBUG_KEYBOARD KC_K
#endif
#ifndef BOOTMAGIC_KEY_DEBUG_MOUSE
#define BOOTMAGIC_KEY_DEBUG_MOUSE KC_M
#endif
/*
* keymap config
*/
#ifndef BOOTMAGIC_KEY_SWAP_CONTROL_CAPSLOCK
#define BOOTMAGIC_KEY_SWAP_CONTROL_CAPSLOCK KC_LCTRL
#endif
#ifndef BOOTMAGIC_KEY_CAPSLOCK_TO_CONTROL
#define BOOTMAGIC_KEY_CAPSLOCK_TO_CONTROL KC_CAPSLOCK
#endif
#ifndef BOOTMAGIC_KEY_SWAP_LALT_LGUI
#define BOOTMAGIC_KEY_SWAP_LALT_LGUI KC_LALT
#endif
#ifndef BOOTMAGIC_KEY_SWAP_RALT_RGUI
#define BOOTMAGIC_KEY_SWAP_RALT_RGUI KC_RALT
#endif
#ifndef BOOTMAGIC_KEY_NO_GUI
#define BOOTMAGIC_KEY_NO_GUI KC_LGUI
#endif
#ifndef BOOTMAGIC_KEY_SWAP_GRAVE_ESC
#define BOOTMAGIC_KEY_SWAP_GRAVE_ESC KC_GRAVE
#endif
#ifndef BOOTMAGIC_KEY_SWAP_BACKSLASH_BACKSPACE
#define BOOTMAGIC_KEY_SWAP_BACKSLASH_BACKSPACE KC_BSLASH
#endif
#ifndef BOOTMAGIC_HOST_NKRO
#define BOOTMAGIC_HOST_NKRO KC_N
#endif
/*
* change default layer
*/
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_0
#define BOOTMAGIC_KEY_DEFAULT_LAYER_0 KC_0
#endif
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_1
#define BOOTMAGIC_KEY_DEFAULT_LAYER_1 KC_1
#endif
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_2
#define BOOTMAGIC_KEY_DEFAULT_LAYER_2 KC_2
#endif
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_3
#define BOOTMAGIC_KEY_DEFAULT_LAYER_3 KC_3
#endif
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_4
#define BOOTMAGIC_KEY_DEFAULT_LAYER_4 KC_4
#endif
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_5
#define BOOTMAGIC_KEY_DEFAULT_LAYER_5 KC_5
#endif
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_6
#define BOOTMAGIC_KEY_DEFAULT_LAYER_6 KC_6
#endif
#ifndef BOOTMAGIC_KEY_DEFAULT_LAYER_7
#define BOOTMAGIC_KEY_DEFAULT_LAYER_7 KC_7
#endif
void bootmagic(void);
bool bootmagic_scan_keycode(uint8_t keycode);
#endif

644
common/command.c Normal file
View file

@ -0,0 +1,644 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <stdint.h>
#include <stdbool.h>
#include <util/delay.h>
#include "keycode.h"
#include "host.h"
#include "keymap.h"
#include "print.h"
#include "debug.h"
#include "util.h"
#include "timer.h"
#include "keyboard.h"
#include "bootloader.h"
#include "action_layer.h"
#include "action_util.h"
#include "eeconfig.h"
#include "sleep_led.h"
#include "led.h"
#include "command.h"
#include "backlight.h"
#ifdef MOUSEKEY_ENABLE
#include "mousekey.h"
#endif
#ifdef PROTOCOL_PJRC
# include "usb_keyboard.h"
# ifdef EXTRAKEY_ENABLE
# include "usb_extra.h"
# endif
#endif
#ifdef PROTOCOL_VUSB
# include "usbdrv.h"
#endif
static bool command_common(uint8_t code);
static void command_common_help(void);
static bool command_console(uint8_t code);
static void command_console_help(void);
#ifdef MOUSEKEY_ENABLE
static bool mousekey_console(uint8_t code);
static void mousekey_console_help(void);
#endif
static uint8_t numkey2num(uint8_t code);
static void switch_default_layer(uint8_t layer);
command_state_t command_state = ONESHOT;
bool command_proc(uint8_t code)
{
switch (command_state) {
case ONESHOT:
if (!IS_COMMAND())
return false;
return (command_extra(code) || command_common(code));
break;
case CONSOLE:
if (IS_COMMAND())
return (command_extra(code) || command_common(code));
else
return (command_console_extra(code) || command_console(code));
break;
#ifdef MOUSEKEY_ENABLE
case MOUSEKEY:
mousekey_console(code);
break;
#endif
default:
command_state = ONESHOT;
return false;
}
return true;
}
/* TODO: Refactoring is needed. */
/* This allows to define extra commands. return false when not processed. */
bool command_extra(uint8_t code) __attribute__ ((weak));
bool command_extra(uint8_t code)
{
return false;
}
bool command_console_extra(uint8_t code) __attribute__ ((weak));
bool command_console_extra(uint8_t code)
{
return false;
}
/***********************************************************
* Command common
***********************************************************/
static void command_common_help(void)
{
print("\n\n----- Command Help -----\n");
print("c: enter console mode\n");
print("d: toggle debug enable\n");
print("x: toggle matrix debug\n");
print("k: toggle keyboard debug\n");
print("m: toggle mouse debug\n");
#ifdef SLEEP_LED_ENABLE
print("z: toggle sleep LED test\n");
#endif
print("v: print device version & info\n");
print("t: print timer count\n");
print("s: print status\n");
print("e: print eeprom config\n");
#ifdef NKRO_ENABLE
print("n: toggle NKRO\n");
#endif
print("0/F10: switch to Layer0 \n");
print("1/F1: switch to Layer1 \n");
print("2/F2: switch to Layer2 \n");
print("3/F3: switch to Layer3 \n");
print("4/F4: switch to Layer4 \n");
print("PScr: power down/remote wake-up\n");
print("Caps: Lock Keyboard(Child Proof)\n");
print("Paus: jump to bootloader\n");
}
#ifdef BOOTMAGIC_ENABLE
static void print_eeconfig(void)
{
print("default_layer: "); print_dec(eeconfig_read_default_layer()); print("\n");
debug_config_t dc;
dc.raw = eeconfig_read_debug();
print("debug_config.raw: "); print_hex8(dc.raw); print("\n");
print(".enable: "); print_dec(dc.enable); print("\n");
print(".matrix: "); print_dec(dc.matrix); print("\n");
print(".keyboard: "); print_dec(dc.keyboard); print("\n");
print(".mouse: "); print_dec(dc.mouse); print("\n");
keymap_config_t kc;
kc.raw = eeconfig_read_keymap();
print("keymap_config.raw: "); print_hex8(kc.raw); print("\n");
print(".swap_control_capslock: "); print_dec(kc.swap_control_capslock); print("\n");
print(".capslock_to_control: "); print_dec(kc.capslock_to_control); print("\n");
print(".swap_lalt_lgui: "); print_dec(kc.swap_lalt_lgui); print("\n");
print(".swap_ralt_rgui: "); print_dec(kc.swap_ralt_rgui); print("\n");
print(".no_gui: "); print_dec(kc.no_gui); print("\n");
print(".swap_grave_esc: "); print_dec(kc.swap_grave_esc); print("\n");
print(".swap_backslash_backspace: "); print_dec(kc.swap_backslash_backspace); print("\n");
print(".nkro: "); print_dec(kc.nkro); print("\n");
#ifdef BACKLIGHT_ENABLE
backlight_config_t bc;
bc.raw = eeconfig_read_backlight();
print("backlight_config.raw: "); print_hex8(bc.raw); print("\n");
print(".enable: "); print_dec(bc.enable); print("\n");
print(".level: "); print_dec(bc.level); print("\n");
#endif
}
#endif
static bool command_common(uint8_t code)
{
static host_driver_t *host_driver = 0;
switch (code) {
#ifdef SLEEP_LED_ENABLE
case KC_Z:
// test breathing sleep LED
print("Sleep LED test\n");
sleep_led_toggle();
led_set(host_keyboard_leds());
break;
#endif
#ifdef BOOTMAGIC_ENABLE
case KC_E:
print("eeconfig:\n");
print_eeconfig();
break;
#endif
case KC_CAPSLOCK:
if (host_get_driver()) {
host_driver = host_get_driver();
clear_keyboard();
host_set_driver(0);
print("Locked.\n");
} else {
host_set_driver(host_driver);
print("Unlocked.\n");
}
break;
case KC_H:
case KC_SLASH: /* ? */
command_common_help();
break;
case KC_C:
debug_matrix = false;
debug_keyboard = false;
debug_mouse = false;
debug_enable = false;
command_console_help();
print("\nEnter Console Mode\n");
print("C> ");
command_state = CONSOLE;
break;
case KC_PAUSE:
clear_keyboard();
print("\n\nJump to bootloader... ");
_delay_ms(1000);
bootloader_jump(); // not return
print("not supported.\n");
break;
case KC_D:
if (debug_enable) {
print("\nDEBUG: disabled.\n");
debug_matrix = false;
debug_keyboard = false;
debug_mouse = false;
debug_enable = false;
} else {
print("\nDEBUG: enabled.\n");
debug_enable = true;
}
break;
case KC_X: // debug matrix toggle
debug_matrix = !debug_matrix;
if (debug_matrix) {
print("\nDEBUG: matrix enabled.\n");
debug_enable = true;
} else {
print("\nDEBUG: matrix disabled.\n");
}
break;
case KC_K: // debug keyboard toggle
debug_keyboard = !debug_keyboard;
if (debug_keyboard) {
print("\nDEBUG: keyboard enabled.\n");
debug_enable = true;
} else {
print("\nDEBUG: keyboard disabled.\n");
}
break;
case KC_M: // debug mouse toggle
debug_mouse = !debug_mouse;
if (debug_mouse) {
print("\nDEBUG: mouse enabled.\n");
debug_enable = true;
} else {
print("\nDEBUG: mouse disabled.\n");
}
break;
case KC_V: // print version & information
print("\n\n----- Version -----\n");
print("DESC: " STR(DESCRIPTION) "\n");
print("VID: " STR(VENDOR_ID) "(" STR(MANUFACTURER) ") "
"PID: " STR(PRODUCT_ID) "(" STR(PRODUCT) ") "
"VER: " STR(DEVICE_VER) "\n");
print("BUILD: " STR(VERSION) " (" __TIME__ " " __DATE__ ")\n");
/* build options */
print("OPTIONS:"
#ifdef PROTOCOL_PJRC
" PJRC"
#endif
#ifdef PROTOCOL_LUFA
" LUFA"
#endif
#ifdef PROTOCOL_VUSB
" VUSB"
#endif
#ifdef BOOTMAGIC_ENABLE
" BOOTMAGIC"
#endif
#ifdef MOUSEKEY_ENABLE
" MOUSEKEY"
#endif
#ifdef EXTRAKEY_ENABLE
" EXTRAKEY"
#endif
#ifdef CONSOLE_ENABLE
" CONSOLE"
#endif
#ifdef COMMAND_ENABLE
" COMMAND"
#endif
#ifdef NKRO_ENABLE
" NKRO"
#endif
#ifdef KEYMAP_SECTION_ENABLE
" KEYMAP_SECTION"
#endif
" " STR(BOOTLOADER_SIZE) "\n");
print("GCC: " STR(__GNUC__) "." STR(__GNUC_MINOR__) "." STR(__GNUC_PATCHLEVEL__)
" AVR-LIBC: " __AVR_LIBC_VERSION_STRING__
" AVR_ARCH: avr" STR(__AVR_ARCH__) "\n");
break;
case KC_T: // print timer
print_val_hex32(timer_count);
break;
case KC_S:
print("\n\n----- Status -----\n");
print_val_hex8(host_keyboard_leds());
print_val_hex8(keyboard_protocol);
print_val_hex8(keyboard_idle);
#ifdef PROTOCOL_PJRC
print_val_hex8(UDCON);
print_val_hex8(UDIEN);
print_val_hex8(UDINT);
print_val_hex8(usb_keyboard_leds);
print_val_hex8(usb_keyboard_idle_count);
#endif
#ifdef PROTOCOL_PJRC
# if USB_COUNT_SOF
print_val_hex8(usbSofCount);
# endif
#endif
break;
#ifdef NKRO_ENABLE
case KC_N:
clear_keyboard(); //Prevents stuck keys.
keyboard_nkro = !keyboard_nkro;
if (keyboard_nkro)
print("NKRO: enabled\n");
else
print("NKRO: disabled\n");
break;
#endif
#ifdef EXTRAKEY_ENABLE
case KC_PSCREEN:
// TODO: Power key should take this feature? otherwise any key during suspend.
#ifdef PROTOCOL_PJRC
if (suspend && remote_wakeup) {
usb_remote_wakeup();
} else {
host_system_send(SYSTEM_POWER_DOWN);
host_system_send(0);
_delay_ms(500);
}
#else
host_system_send(SYSTEM_POWER_DOWN);
_delay_ms(100);
host_system_send(0);
_delay_ms(500);
#endif
break;
#endif
case KC_ESC:
case KC_GRV:
case KC_0:
switch_default_layer(0);
break;
case KC_1 ... KC_9:
switch_default_layer((code - KC_1) + 1);
break;
case KC_F1 ... KC_F12:
switch_default_layer((code - KC_F1) + 1);
break;
default:
print("?");
return false;
}
return true;
}
/***********************************************************
* Command console
***********************************************************/
static void command_console_help(void)
{
print("\n\n----- Console Help -----\n");
print("ESC/q: quit\n");
#ifdef MOUSEKEY_ENABLE
print("m: mousekey\n");
#endif
}
static bool command_console(uint8_t code)
{
switch (code) {
case KC_H:
case KC_SLASH: /* ? */
command_console_help();
break;
case KC_Q:
case KC_ESC:
print("\nQuit Console Mode\n");
command_state = ONESHOT;
return false;
#ifdef MOUSEKEY_ENABLE
case KC_M:
mousekey_console_help();
print("\nEnter Mousekey Console\n");
print("M0>");
command_state = MOUSEKEY;
return true;
#endif
default:
print("?");
return false;
}
print("C> ");
return true;
}
#ifdef MOUSEKEY_ENABLE
/***********************************************************
* Mousekey console
***********************************************************/
static uint8_t mousekey_param = 0;
static void mousekey_param_print(void)
{
print("\n\n----- Mousekey Parameters -----\n");
print("1: mk_delay(*10ms): "); pdec(mk_delay); print("\n");
print("2: mk_interval(ms): "); pdec(mk_interval); print("\n");
print("3: mk_max_speed: "); pdec(mk_max_speed); print("\n");
print("4: mk_time_to_max: "); pdec(mk_time_to_max); print("\n");
print("5: mk_wheel_max_speed: "); pdec(mk_wheel_max_speed); print("\n");
print("6: mk_wheel_time_to_max: "); pdec(mk_wheel_time_to_max); print("\n");
}
#define PRINT_SET_VAL(v) print(#v " = "); print_dec(v); print("\n");
static void mousekey_param_inc(uint8_t param, uint8_t inc)
{
switch (param) {
case 1:
if (mk_delay + inc < UINT8_MAX)
mk_delay += inc;
else
mk_delay = UINT8_MAX;
PRINT_SET_VAL(mk_delay);
break;
case 2:
if (mk_interval + inc < UINT8_MAX)
mk_interval += inc;
else
mk_interval = UINT8_MAX;
PRINT_SET_VAL(mk_interval);
break;
case 3:
if (mk_max_speed + inc < UINT8_MAX)
mk_max_speed += inc;
else
mk_max_speed = UINT8_MAX;
PRINT_SET_VAL(mk_max_speed);
break;
case 4:
if (mk_time_to_max + inc < UINT8_MAX)
mk_time_to_max += inc;
else
mk_time_to_max = UINT8_MAX;
PRINT_SET_VAL(mk_time_to_max);
break;
case 5:
if (mk_wheel_max_speed + inc < UINT8_MAX)
mk_wheel_max_speed += inc;
else
mk_wheel_max_speed = UINT8_MAX;
PRINT_SET_VAL(mk_wheel_max_speed);
break;
case 6:
if (mk_wheel_time_to_max + inc < UINT8_MAX)
mk_wheel_time_to_max += inc;
else
mk_wheel_time_to_max = UINT8_MAX;
PRINT_SET_VAL(mk_wheel_time_to_max);
break;
}
}
static void mousekey_param_dec(uint8_t param, uint8_t dec)
{
switch (param) {
case 1:
if (mk_delay > dec)
mk_delay -= dec;
else
mk_delay = 0;
PRINT_SET_VAL(mk_delay);
break;
case 2:
if (mk_interval > dec)
mk_interval -= dec;
else
mk_interval = 0;
PRINT_SET_VAL(mk_interval);
break;
case 3:
if (mk_max_speed > dec)
mk_max_speed -= dec;
else
mk_max_speed = 0;
PRINT_SET_VAL(mk_max_speed);
break;
case 4:
if (mk_time_to_max > dec)
mk_time_to_max -= dec;
else
mk_time_to_max = 0;
PRINT_SET_VAL(mk_time_to_max);
break;
case 5:
if (mk_wheel_max_speed > dec)
mk_wheel_max_speed -= dec;
else
mk_wheel_max_speed = 0;
PRINT_SET_VAL(mk_wheel_max_speed);
break;
case 6:
if (mk_wheel_time_to_max > dec)
mk_wheel_time_to_max -= dec;
else
mk_wheel_time_to_max = 0;
PRINT_SET_VAL(mk_wheel_time_to_max);
break;
}
}
static void mousekey_console_help(void)
{
print("\n\n----- Mousekey Parameters Help -----\n");
print("ESC/q: quit\n");
print("1: select mk_delay(*10ms)\n");
print("2: select mk_interval(ms)\n");
print("3: select mk_max_speed\n");
print("4: select mk_time_to_max\n");
print("5: select mk_wheel_max_speed\n");
print("6: select mk_wheel_time_to_max\n");
print("p: print parameters\n");
print("d: set default values\n");
print("up: increase parameters(+1)\n");
print("down: decrease parameters(-1)\n");
print("pgup: increase parameters(+10)\n");
print("pgdown: decrease parameters(-10)\n");
print("\nspeed = delta * max_speed * (repeat / time_to_max)\n");
print("where delta: cursor="); pdec(MOUSEKEY_MOVE_DELTA);
print(", wheel="); pdec(MOUSEKEY_WHEEL_DELTA); print("\n");
print("See http://en.wikipedia.org/wiki/Mouse_keys\n");
}
static bool mousekey_console(uint8_t code)
{
switch (code) {
case KC_H:
case KC_SLASH: /* ? */
mousekey_console_help();
break;
case KC_Q:
case KC_ESC:
mousekey_param = 0;
print("\nQuit Mousekey Console\n");
print("C> ");
command_state = CONSOLE;
return false;
case KC_P:
mousekey_param_print();
break;
case KC_1:
case KC_2:
case KC_3:
case KC_4:
case KC_5:
case KC_6:
case KC_7:
case KC_8:
case KC_9:
case KC_0:
mousekey_param = numkey2num(code);
print("selected parameter: "); pdec(mousekey_param); print("\n");
break;
case KC_UP:
mousekey_param_inc(mousekey_param, 1);
break;
case KC_DOWN:
mousekey_param_dec(mousekey_param, 1);
break;
case KC_PGUP:
mousekey_param_inc(mousekey_param, 10);
break;
case KC_PGDN:
mousekey_param_dec(mousekey_param, 10);
break;
case KC_D:
mk_delay = MOUSEKEY_DELAY/10;
mk_interval = MOUSEKEY_INTERVAL;
mk_max_speed = MOUSEKEY_MAX_SPEED;
mk_time_to_max = MOUSEKEY_TIME_TO_MAX;
mk_wheel_max_speed = MOUSEKEY_WHEEL_MAX_SPEED;
mk_wheel_time_to_max = MOUSEKEY_WHEEL_TIME_TO_MAX;
print("set default values.\n");
break;
default:
print("?");
return false;
}
print("M"); pdec(mousekey_param); print("> ");
return true;
}
#endif
/***********************************************************
* Utilities
***********************************************************/
static uint8_t numkey2num(uint8_t code)
{
switch (code) {
case KC_1: return 1;
case KC_2: return 2;
case KC_3: return 3;
case KC_4: return 4;
case KC_5: return 5;
case KC_6: return 6;
case KC_7: return 7;
case KC_8: return 8;
case KC_9: return 9;
case KC_0: return 0;
}
return 0;
}
static void switch_default_layer(uint8_t layer)
{
print("switch_default_layer: "); print_dec(biton32(default_layer_state));
print(" to "); print_dec(layer); print("\n");
default_layer_set(1UL<<layer);
clear_keyboard();
}

35
common/command.h Normal file
View file

@ -0,0 +1,35 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef COMMAND_H
#define COMMAND
/* TODO: Refactoring */
typedef enum { ONESHOT, CONSOLE, MOUSEKEY } command_state_t;
extern command_state_t command_state;
/* This allows to extend commands. Return false when command is not processed. */
bool command_extra(uint8_t code);
bool command_console_extra(uint8_t code);
#ifdef COMMAND_ENABLE
bool command_proc(uint8_t code);
#else
#define command_proc(code) false
#endif
#endif

24
common/debug.c Normal file
View file

@ -0,0 +1,24 @@
#include <stdbool.h>
#include "debug.h"
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
debug_config_t debug_config = {
/* GCC Bug 10676 - Using unnamed fields in initializers
* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=10676 */
#if GCC_VERSION >= 40600
.enable = false,
.matrix = false,
.keyboard = false,
.mouse = false,
.reserved = 0
#else
{
false, // .enable
false, // .matrix
false, // .keyboard
false, // .mouse
0 // .reserved
}
#endif
};

117
common/debug.h Normal file
View file

@ -0,0 +1,117 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef DEBUG_H
#define DEBUG_H 1
#include <stdbool.h>
#include "print.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Debug output control
*/
typedef union {
struct {
bool enable:1;
bool matrix:1;
bool keyboard:1;
bool mouse:1;
uint8_t reserved:4;
};
uint8_t raw;
} debug_config_t;
extern debug_config_t debug_config;
#ifdef __cplusplus
}
#endif
/* for backward compatibility */
#define debug_enable (debug_config.enable)
#define debug_matrix (debug_config.matrix)
#define debug_keyboard (debug_config.keyboard)
#define debug_mouse (debug_config.mouse)
/*
* Debug print utils
*/
#ifndef NO_DEBUG
#define dprint(s) do { if (debug_enable) print(s); } while (0)
#define dprintln(s) do { if (debug_enable) println(s); } while (0)
#define dprintf(fmt, ...) do { if (debug_enable) xprintf(fmt, ##__VA_ARGS__); } while (0)
#define dmsg(s) dprintf("%s at %s: %S\n", __FILE__, __LINE__, PSTR(s))
/* Deprecated. DO NOT USE these anymore, use dprintf instead. */
#define debug(s) do { if (debug_enable) print(s); } while (0)
#define debugln(s) do { if (debug_enable) println(s); } while (0)
#define debug_msg(s) do { \
if (debug_enable) { \
print(__FILE__); print(" at "); print_dec(__LINE__); print(" in "); print(": "); print(s); \
} \
} while (0)
#define debug_dec(data) do { if (debug_enable) print_dec(data); } while (0)
#define debug_decs(data) do { if (debug_enable) print_decs(data); } while (0)
#define debug_hex4(data) do { if (debug_enable) print_hex4(data); } while (0)
#define debug_hex8(data) do { if (debug_enable) print_hex8(data); } while (0)
#define debug_hex16(data) do { if (debug_enable) print_hex16(data); } while (0)
#define debug_hex32(data) do { if (debug_enable) print_hex32(data); } while (0)
#define debug_bin8(data) do { if (debug_enable) print_bin8(data); } while (0)
#define debug_bin16(data) do { if (debug_enable) print_bin16(data); } while (0)
#define debug_bin32(data) do { if (debug_enable) print_bin32(data); } while (0)
#define debug_bin_reverse8(data) do { if (debug_enable) print_bin_reverse8(data); } while (0)
#define debug_bin_reverse16(data) do { if (debug_enable) print_bin_reverse16(data); } while (0)
#define debug_bin_reverse32(data) do { if (debug_enable) print_bin_reverse32(data); } while (0)
#define debug_hex(data) debug_hex8(data)
#define debug_bin(data) debug_bin8(data)
#define debug_bin_reverse(data) debug_bin8(data)
#else /* NO_DEBUG */
#define dprint(s)
#define dprintln(s)
#define dprintf(fmt, ...)
#define dmsg(s)
#define debug(s)
#define debugln(s)
#define debug_msg(s)
#define debug_dec(data)
#define debug_decs(data)
#define debug_hex4(data)
#define debug_hex8(data)
#define debug_hex16(data)
#define debug_hex32(data)
#define debug_bin8(data)
#define debug_bin16(data)
#define debug_bin32(data)
#define debug_bin_reverse8(data)
#define debug_bin_reverse16(data)
#define debug_bin_reverse32(data)
#define debug_hex(data)
#define debug_bin(data)
#define debug_bin_reverse(data)
#endif /* NO_DEBUG */
#endif

75
common/eeconfig.h Normal file
View file

@ -0,0 +1,75 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef EECONFIG_H
#define EECONFIG_H
#include <stdint.h>
#include <stdbool.h>
#define EECONFIG_MAGIC_NUMBER (uint16_t)0xFEED
/* eeprom parameteter address */
#define EECONFIG_MAGIC (uint16_t *)0
#define EECONFIG_DEBUG (uint8_t *)2
#define EECONFIG_DEFAULT_LAYER (uint8_t *)3
#define EECONFIG_KEYMAP (uint8_t *)4
#define EECONFIG_MOUSEKEY_ACCEL (uint8_t *)5
#define EECONFIG_BACKLIGHT (uint8_t *)6
/* debug bit */
#define EECONFIG_DEBUG_ENABLE (1<<0)
#define EECONFIG_DEBUG_MATRIX (1<<1)
#define EECONFIG_DEBUG_KEYBOARD (1<<2)
#define EECONFIG_DEBUG_MOUSE (1<<3)
/* keyconf bit */
#define EECONFIG_KEYMAP_SWAP_CONTROL_CAPSLOCK (1<<0)
#define EECONFIG_KEYMAP_CAPSLOCK_TO_CONTROL (1<<1)
#define EECONFIG_KEYMAP_SWAP_LALT_LGUI (1<<2)
#define EECONFIG_KEYMAP_SWAP_RALT_RGUI (1<<3)
#define EECONFIG_KEYMAP_NO_GUI (1<<4)
#define EECONFIG_KEYMAP_SWAP_GRAVE_ESC (1<<5)
#define EECONFIG_KEYMAP_SWAP_BACKSLASH_BACKSPACE (1<<6)
#define EECONFIG_KEYMAP_NKRO (1<<7)
bool eeconfig_is_enabled(void);
void eeconfig_init(void);
void eeconfig_enable(void);
void eeconfig_disable(void);
uint8_t eeconfig_read_debug(void);
void eeconfig_write_debug(uint8_t val);
uint8_t eeconfig_read_default_layer(void);
void eeconfig_write_default_layer(uint8_t val);
uint8_t eeconfig_read_keymap(void);
void eeconfig_write_keymap(uint8_t val);
#ifdef BACKLIGHT_ENABLE
uint8_t eeconfig_read_backlight(void);
void eeconfig_write_backlight(uint8_t val);
#endif
#endif

97
common/host.c Normal file
View file

@ -0,0 +1,97 @@
/*
Copyright 2011,2012 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <stdint.h>
//#include <avr/interrupt.h>
#include "keycode.h"
#include "host.h"
#include "util.h"
#include "debug.h"
#ifdef NKRO_ENABLE
bool keyboard_nkro = true;
#endif
static host_driver_t *driver;
static uint16_t last_system_report = 0;
static uint16_t last_consumer_report = 0;
void host_set_driver(host_driver_t *d)
{
driver = d;
}
host_driver_t *host_get_driver(void)
{
return driver;
}
uint8_t host_keyboard_leds(void)
{
if (!driver) return 0;
return (*driver->keyboard_leds)();
}
/* send report */
void host_keyboard_send(report_keyboard_t *report)
{
if (!driver) return;
(*driver->send_keyboard)(report);
if (debug_keyboard) {
dprint("keyboard_report: ");
for (uint8_t i = 0; i < KEYBOARD_REPORT_SIZE; i++) {
dprintf("%02X ", report->raw[i]);
}
dprint("\n");
}
}
void host_mouse_send(report_mouse_t *report)
{
if (!driver) return;
(*driver->send_mouse)(report);
}
void host_system_send(uint16_t report)
{
if (report == last_system_report) return;
last_system_report = report;
if (!driver) return;
(*driver->send_system)(report);
}
void host_consumer_send(uint16_t report)
{
if (report == last_consumer_report) return;
last_consumer_report = report;
if (!driver) return;
(*driver->send_consumer)(report);
}
uint16_t host_last_sysytem_report(void)
{
return last_system_report;
}
uint16_t host_last_consumer_report(void)
{
return last_consumer_report;
}

57
common/host.h Normal file
View file

@ -0,0 +1,57 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef HOST_H
#define HOST_H
#include <stdint.h>
#include <stdbool.h>
#include "report.h"
#include "host_driver.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef NKRO_ENABLE
extern bool keyboard_nkro;
#endif
extern uint8_t keyboard_idle;
extern uint8_t keyboard_protocol;
/* host driver */
void host_set_driver(host_driver_t *driver);
host_driver_t *host_get_driver(void);
/* host driver interface */
uint8_t host_keyboard_leds(void);
void host_keyboard_send(report_keyboard_t *report);
void host_mouse_send(report_mouse_t *report);
void host_system_send(uint16_t data);
void host_consumer_send(uint16_t data);
uint16_t host_last_sysytem_report(void);
uint16_t host_last_consumer_report(void);
#ifdef __cplusplus
}
#endif
#endif

33
common/host_driver.h Normal file
View file

@ -0,0 +1,33 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef HOST_DRIVER_H
#define HOST_DRIVER_H
#include <stdint.h>
#include "report.h"
typedef struct {
uint8_t (*keyboard_leds)(void);
void (*send_keyboard)(report_keyboard_t *);
void (*send_mouse)(report_mouse_t *);
void (*send_system)(uint16_t);
void (*send_consumer)(uint16_t);
} host_driver_t;
#endif

150
common/keyboard.c Normal file
View file

@ -0,0 +1,150 @@
/*
Copyright 2011,2012,2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <stdint.h>
#include "keyboard.h"
#include "matrix.h"
#include "keymap.h"
#include "host.h"
#include "led.h"
#include "keycode.h"
#include "timer.h"
#include "print.h"
#include "debug.h"
#include "command.h"
#include "util.h"
#include "sendchar.h"
#include "bootmagic.h"
#include "eeconfig.h"
#include "backlight.h"
#ifdef MOUSEKEY_ENABLE
# include "mousekey.h"
#endif
#ifdef PS2_MOUSE_ENABLE
# include "ps2_mouse.h"
#endif
#ifdef SERIAL_MOUSE_ENABLE
#include "serial_mouse.h"
#endif
#ifdef MATRIX_HAS_GHOST
static bool has_ghost_in_row(uint8_t row)
{
matrix_row_t matrix_row = matrix_get_row(row);
// No ghost exists when less than 2 keys are down on the row
if (((matrix_row - 1) & matrix_row) == 0)
return false;
// Ghost occurs when the row shares column line with other row
for (uint8_t i=0; i < MATRIX_ROWS; i++) {
if (i != row && (matrix_get_row(i) & matrix_row))
return true;
}
return false;
}
#endif
void keyboard_init(void)
{
timer_init();
matrix_init();
#ifdef PS2_MOUSE_ENABLE
ps2_mouse_init();
#endif
#ifdef SERIAL_MOUSE_ENABLE
serial_mouse_init();
#endif
#ifdef BOOTMAGIC_ENABLE
bootmagic();
#endif
#ifdef BACKLIGHT_ENABLE
backlight_init();
#endif
}
/*
* Do keyboard routine jobs: scan mantrix, light LEDs, ...
* This is repeatedly called as fast as possible.
*/
void keyboard_task(void)
{
static matrix_row_t matrix_prev[MATRIX_ROWS];
static uint8_t led_status = 0;
matrix_row_t matrix_row = 0;
matrix_row_t matrix_change = 0;
matrix_scan();
for (uint8_t r = 0; r < MATRIX_ROWS; r++) {
matrix_row = matrix_get_row(r);
matrix_change = matrix_row ^ matrix_prev[r];
if (matrix_change) {
if (debug_matrix) matrix_print();
#ifdef MATRIX_HAS_GHOST
if (has_ghost_in_row(r)) {
matrix_prev[r] = matrix_row;
continue;
}
#endif
for (uint8_t c = 0; c < MATRIX_COLS; c++) {
if (matrix_change & ((matrix_row_t)1<<c)) {
action_exec((keyevent_t){
.key = (keypos_t){ .row = r, .col = c },
.pressed = (matrix_row & ((matrix_row_t)1<<c)),
.time = (timer_read() | 1) /* time should not be 0 */
});
// record a processed key
matrix_prev[r] ^= ((matrix_row_t)1<<c);
// process a key per task call
goto MATRIX_LOOP_END;
}
}
}
}
// call with pseudo tick event when no real key event.
action_exec(TICK);
MATRIX_LOOP_END:
#ifdef MOUSEKEY_ENABLE
// mousekey repeat & acceleration
mousekey_task();
#endif
#ifdef PS2_MOUSE_ENABLE
ps2_mouse_task();
#endif
#ifdef SERIAL_MOUSE_ENABLE
serial_mouse_task();
#endif
// update LED
if (led_status != host_keyboard_leds()) {
led_status = host_keyboard_leds();
keyboard_set_leds(led_status);
}
}
void keyboard_set_leds(uint8_t leds)
{
if (debug_keyboard) { debug("keyboard_set_led: "); debug_hex8(leds); debug("\n"); }
led_set(leds);
}

72
common/keyboard.h Normal file
View file

@ -0,0 +1,72 @@
/*
Copyright 2011,2012,2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef KEYBOARD_H
#define KEYBOARD_H
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* key matrix position */
typedef struct {
uint8_t col;
uint8_t row;
} keypos_t;
/* key event */
typedef struct {
keypos_t key;
bool pressed;
uint16_t time;
} keyevent_t;
/* equivalent test of keypos_t */
#define KEYEQ(keya, keyb) ((keya).row == (keyb).row && (keya).col == (keyb).col)
/* Rules for No Event:
* 1) (time == 0) to handle (keyevent_t){} as empty event
* 2) Matrix(255, 255) to make TICK event available
*/
static inline bool IS_NOEVENT(keyevent_t event) { return event.time == 0 || (event.key.row == 255 && event.key.col == 255); }
static inline bool IS_PRESSED(keyevent_t event) { return (!IS_NOEVENT(event) && event.pressed); }
static inline bool IS_RELEASED(keyevent_t event) { return (!IS_NOEVENT(event) && !event.pressed); }
/* Tick event */
#define TICK (keyevent_t){ \
.key = (keypos_t){ .row = 255, .col = 255 }, \
.pressed = false, \
.time = (timer_read() | 1) \
}
void keyboard_init(void);
void keyboard_task(void);
void keyboard_set_leds(uint8_t leds);
__attribute__ ((weak)) void matrix_power_up(void) {}
__attribute__ ((weak)) void matrix_power_down(void) {}
#ifdef __cplusplus
}
#endif
#endif

489
common/keycode.h Normal file
View file

@ -0,0 +1,489 @@
/*
Copyright 2011,2012 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
/*
* Keycodes based on HID Usage Keyboard/Keypad Page(0x07) plus special codes
* http://www.usb.org/developers/devclass_docs/Hut1_12.pdf
*/
#ifndef KEYCODE_H
#define KEYCODE_H
#define IS_ERROR(code) (KC_ROLL_OVER <= (code) && (code) <= KC_UNDEFINED)
#define IS_ANY(code) (KC_A <= (code) && (code) <= 0xFF)
#define IS_KEY(code) (KC_A <= (code) && (code) <= KC_EXSEL)
#define IS_MOD(code) (KC_LCTRL <= (code) && (code) <= KC_RGUI)
#define IS_SPECIAL(code) ((0xA5 <= (code) && (code) <= 0xDF) || (0xE8 <= (code) && (code) <= 0xFF))
#define IS_SYSTEM(code) (KC_PWR <= (code) && (code) <= KC_WAKE)
#define IS_CONSUMER(code) (KC_MUTE <= (code) && (code) <= KC_WFAV)
#define IS_FN(code) (KC_FN0 <= (code) && (code) <= KC_FN31)
#define IS_MOUSEKEY(code) (KC_MS_UP <= (code) && (code) <= KC_MS_ACCEL2)
#define IS_MOUSEKEY_MOVE(code) (KC_MS_UP <= (code) && (code) <= KC_MS_RIGHT)
#define IS_MOUSEKEY_BUTTON(code) (KC_MS_BTN1 <= (code) && (code) <= KC_MS_BTN5)
#define IS_MOUSEKEY_WHEEL(code) (KC_MS_WH_UP <= (code) && (code) <= KC_MS_WH_RIGHT)
#define IS_MOUSEKEY_ACCEL(code) (KC_MS_ACCEL0 <= (code) && (code) <= KC_MS_ACCEL2)
#define MOD_BIT(code) (1<<MOD_INDEX(code))
#define MOD_INDEX(code) ((code) & 0x07)
#define FN_BIT(code) (1<<FN_INDEX(code))
#define FN_INDEX(code) ((code) - KC_FN0)
#define FN_MIN KC_FN0
#define FN_MAX KC_FN31
/*
* Short names for ease of definition of keymap
*/
#define KC_LCTL KC_LCTRL
#define KC_RCTL KC_RCTRL
#define KC_LSFT KC_LSHIFT
#define KC_RSFT KC_RSHIFT
#define KC_ESC KC_ESCAPE
#define KC_BSPC KC_BSPACE
#define KC_ENT KC_ENTER
#define KC_DEL KC_DELETE
#define KC_INS KC_INSERT
#define KC_CAPS KC_CAPSLOCK
#define KC_CLCK KC_CAPSLOCK
#define KC_RGHT KC_RIGHT
#define KC_PGDN KC_PGDOWN
#define KC_PSCR KC_PSCREEN
#define KC_SLCK KC_SCROLLLOCK
#define KC_PAUS KC_PAUSE
#define KC_BRK KC_PAUSE
#define KC_NLCK KC_NUMLOCK
#define KC_SPC KC_SPACE
#define KC_MINS KC_MINUS
#define KC_EQL KC_EQUAL
#define KC_GRV KC_GRAVE
#define KC_RBRC KC_RBRACKET
#define KC_LBRC KC_LBRACKET
#define KC_COMM KC_COMMA
#define KC_BSLS KC_BSLASH
#define KC_SLSH KC_SLASH
#define KC_SCLN KC_SCOLON
#define KC_QUOT KC_QUOTE
#define KC_APP KC_APPLICATION
#define KC_NUHS KC_NONUS_HASH
#define KC_NUBS KC_NONUS_BSLASH
#define KC_LCAP KC_LOCKING_CAPS
#define KC_LNUM KC_LOCKING_NUM
#define KC_LSCR KC_LOCKING_SCROLL
#define KC_ERAS KC_ALT_ERASE,
#define KC_CLR KC_CLEAR
/* Japanese specific */
#define KC_ZKHK KC_GRAVE
#define KC_RO KC_INT1
#define KC_KANA KC_INT2
#define KC_JYEN KC_INT3
#define KC_HENK KC_INT4
#define KC_MHEN KC_INT5
/* Keypad */
#define KC_P1 KC_KP_1
#define KC_P2 KC_KP_2
#define KC_P3 KC_KP_3
#define KC_P4 KC_KP_4
#define KC_P5 KC_KP_5
#define KC_P6 KC_KP_6
#define KC_P7 KC_KP_7
#define KC_P8 KC_KP_8
#define KC_P9 KC_KP_9
#define KC_P0 KC_KP_0
#define KC_PDOT KC_KP_DOT
#define KC_PCMM KC_KP_COMMA
#define KC_PSLS KC_KP_SLASH
#define KC_PAST KC_KP_ASTERISK
#define KC_PMNS KC_KP_MINUS
#define KC_PPLS KC_KP_PLUS
#define KC_PEQL KC_KP_EQUAL
#define KC_PENT KC_KP_ENTER
/* Mousekey */
#define KC_MS_U KC_MS_UP
#define KC_MS_D KC_MS_DOWN
#define KC_MS_L KC_MS_LEFT
#define KC_MS_R KC_MS_RIGHT
#define KC_BTN1 KC_MS_BTN1
#define KC_BTN2 KC_MS_BTN2
#define KC_BTN3 KC_MS_BTN3
#define KC_BTN4 KC_MS_BTN4
#define KC_BTN5 KC_MS_BTN5
#define KC_WH_U KC_MS_WH_UP
#define KC_WH_D KC_MS_WH_DOWN
#define KC_WH_L KC_MS_WH_LEFT
#define KC_WH_R KC_MS_WH_RIGHT
#define KC_ACL0 KC_MS_ACCEL0
#define KC_ACL1 KC_MS_ACCEL1
#define KC_ACL2 KC_MS_ACCEL2
/* Sytem Control */
#define KC_PWR KC_SYSTEM_POWER
#define KC_SLEP KC_SYSTEM_SLEEP
#define KC_WAKE KC_SYSTEM_WAKE
/* Consumer Page */
#define KC_MUTE KC_AUDIO_MUTE
#define KC_VOLU KC_AUDIO_VOL_UP
#define KC_VOLD KC_AUDIO_VOL_DOWN
#define KC_MNXT KC_MEDIA_NEXT_TRACK
#define KC_MPRV KC_MEDIA_PREV_TRACK
#define KC_MFFD KC_MEDIA_FAST_FORWARD
#define KC_MRWD KC_MEDIA_REWIND
#define KC_MSTP KC_MEDIA_STOP
#define KC_MPLY KC_MEDIA_PLAY_PAUSE
#define KC_MSEL KC_MEDIA_SELECT
#define KC_EJCT KC_MEDIA_EJECT
#define KC_MAIL KC_MAIL
#define KC_CALC KC_CALCULATOR
#define KC_MYCM KC_MY_COMPUTER
#define KC_WSCH KC_WWW_SEARCH
#define KC_WHOM KC_WWW_HOME
#define KC_WBAK KC_WWW_BACK
#define KC_WFWD KC_WWW_FORWARD
#define KC_WSTP KC_WWW_STOP
#define KC_WREF KC_WWW_REFRESH
#define KC_WFAV KC_WWW_FAVORITES
/* Transparent */
#define KC_TRANSPARENT 1
#define KC_TRNS KC_TRANSPARENT
/* USB HID Keyboard/Keypad Usage(0x07) */
enum hid_keyboard_keypad_usage {
KC_NO = 0x00,
KC_ROLL_OVER,
KC_POST_FAIL,
KC_UNDEFINED,
KC_A,
KC_B,
KC_C,
KC_D,
KC_E,
KC_F,
KC_G,
KC_H,
KC_I,
KC_J,
KC_K,
KC_L,
KC_M, /* 0x10 */
KC_N,
KC_O,
KC_P,
KC_Q,
KC_R,
KC_S,
KC_T,
KC_U,
KC_V,
KC_W,
KC_X,
KC_Y,
KC_Z,
KC_1,
KC_2,
KC_3, /* 0x20 */
KC_4,
KC_5,
KC_6,
KC_7,
KC_8,
KC_9,
KC_0,
KC_ENTER,
KC_ESCAPE,
KC_BSPACE,
KC_TAB,
KC_SPACE,
KC_MINUS,
KC_EQUAL,
KC_LBRACKET,
KC_RBRACKET, /* 0x30 */
KC_BSLASH, /* \ (and |) */
KC_NONUS_HASH, /* Non-US # and ~ */
KC_SCOLON, /* ; (and :) */
KC_QUOTE, /* ' and " */
KC_GRAVE, /* Grave accent and tilde */
KC_COMMA, /* , and < */
KC_DOT, /* . and > */
KC_SLASH, /* / and ? */
KC_CAPSLOCK,
KC_F1,
KC_F2,
KC_F3,
KC_F4,
KC_F5,
KC_F6,
KC_F7, /* 0x40 */
KC_F8,
KC_F9,
KC_F10,
KC_F11,
KC_F12,
KC_PSCREEN,
KC_SCROLLLOCK,
KC_PAUSE,
KC_INSERT,
KC_HOME,
KC_PGUP,
KC_DELETE,
KC_END,
KC_PGDOWN,
KC_RIGHT,
KC_LEFT, /* 0x50 */
KC_DOWN,
KC_UP,
KC_NUMLOCK,
KC_KP_SLASH,
KC_KP_ASTERISK,
KC_KP_MINUS,
KC_KP_PLUS,
KC_KP_ENTER,
KC_KP_1,
KC_KP_2,
KC_KP_3,
KC_KP_4,
KC_KP_5,
KC_KP_6,
KC_KP_7,
KC_KP_8, /* 0x60 */
KC_KP_9,
KC_KP_0,
KC_KP_DOT,
KC_NONUS_BSLASH, /* Non-US \ and | */
KC_APPLICATION,
KC_POWER,
KC_KP_EQUAL,
KC_F13,
KC_F14,
KC_F15,
KC_F16,
KC_F17,
KC_F18,
KC_F19,
KC_F20,
KC_F21, /* 0x70 */
KC_F22,
KC_F23,
KC_F24,
KC_EXECUTE,
KC_HELP,
KC_MENU,
KC_SELECT,
KC_STOP,
KC_AGAIN,
KC_UNDO,
KC_CUT,
KC_COPY,
KC_PASTE,
KC_FIND,
KC__MUTE,
KC__VOLUP, /* 0x80 */
KC__VOLDOWN,
KC_LOCKING_CAPS, /* locking Caps Lock */
KC_LOCKING_NUM, /* locking Num Lock */
KC_LOCKING_SCROLL, /* locking Scroll Lock */
KC_KP_COMMA,
KC_KP_EQUAL_AS400, /* equal sign on AS/400 */
KC_INT1,
KC_INT2,
KC_INT3,
KC_INT4,
KC_INT5,
KC_INT6,
KC_INT7,
KC_INT8,
KC_INT9,
KC_LANG1, /* 0x90 */
KC_LANG2,
KC_LANG3,
KC_LANG4,
KC_LANG5,
KC_LANG6,
KC_LANG7,
KC_LANG8,
KC_LANG9,
KC_ALT_ERASE,
KC_SYSREQ,
KC_CANCEL,
KC_CLEAR,
KC_PRIOR,
KC_RETURN,
KC_SEPARATOR,
KC_OUT, /* 0xA0 */
KC_OPER,
KC_CLEAR_AGAIN,
KC_CRSEL,
KC_EXSEL, /* 0xA4 */
/* NOTE: 0xA5-DF are used for internal special purpose */
#if 0
/* NOTE: Following codes(0xB0-DD) are not used. Leave them for reference. */
KC_KP_00 = 0xB0,
KC_KP_000,
KC_THOUSANDS_SEPARATOR,
KC_DECIMAL_SEPARATOR,
KC_CURRENCY_UNIT,
KC_CURRENCY_SUB_UNIT,
KC_KP_LPAREN,
KC_KP_RPAREN,
KC_KP_LCBRACKET, /* { */
KC_KP_RCBRACKET, /* } */
KC_KP_TAB,
KC_KP_BSPACE,
KC_KP_A,
KC_KP_B,
KC_KP_C,
KC_KP_D,
KC_KP_E, /* 0xC0 */
KC_KP_F,
KC_KP_XOR,
KC_KP_HAT,
KC_KP_PERC,
KC_KP_LT,
KC_KP_GT,
KC_KP_AND,
KC_KP_LAZYAND,
KC_KP_OR,
KC_KP_LAZYOR,
KC_KP_COLON,
KC_KP_HASH,
KC_KP_SPACE,
KC_KP_ATMARK,
KC_KP_EXCLAMATION,
KC_KP_MEM_STORE, /* 0xD0 */
KC_KP_MEM_RECALL,
KC_KP_MEM_CLEAR,
KC_KP_MEM_ADD,
KC_KP_MEM_SUB,
KC_KP_MEM_MUL,
KC_KP_MEM_DIV,
KC_KP_PLUS_MINUS,
KC_KP_CLEAR,
KC_KP_CLEAR_ENTRY,
KC_KP_BINARY,
KC_KP_OCTAL,
KC_KP_DECIMAL,
KC_KP_HEXADECIMAL, /* 0xDD */
#endif
/* Modifiers */
KC_LCTRL = 0xE0,
KC_LSHIFT,
KC_LALT,
KC_LGUI,
KC_RCTRL,
KC_RSHIFT,
KC_RALT,
KC_RGUI,
/* NOTE: 0xE8-FF are used for internal special purpose */
};
/* Special keycodes */
/* NOTE: 0xA5-DF and 0xE8-FF are used for internal special purpose */
enum internal_special_keycodes {
/* System Control */
KC_SYSTEM_POWER = 0xA5,
KC_SYSTEM_SLEEP,
KC_SYSTEM_WAKE,
/* Media Control */
KC_AUDIO_MUTE,
KC_AUDIO_VOL_UP,
KC_AUDIO_VOL_DOWN,
KC_MEDIA_NEXT_TRACK,
KC_MEDIA_PREV_TRACK,
KC_MEDIA_STOP,
KC_MEDIA_PLAY_PAUSE,
KC_MEDIA_SELECT,
KC_MEDIA_EJECT,
KC_MAIL,
KC_CALCULATOR,
KC_MY_COMPUTER,
KC_WWW_SEARCH,
KC_WWW_HOME,
KC_WWW_BACK,
KC_WWW_FORWARD,
KC_WWW_STOP,
KC_WWW_REFRESH,
KC_WWW_FAVORITES,
KC_MEDIA_FAST_FORWARD,
KC_MEDIA_REWIND, /* 0xBC */
/* Fn key */
KC_FN0 = 0xC0,
KC_FN1,
KC_FN2,
KC_FN3,
KC_FN4,
KC_FN5,
KC_FN6,
KC_FN7,
KC_FN8,
KC_FN9,
KC_FN10,
KC_FN11,
KC_FN12,
KC_FN13,
KC_FN14,
KC_FN15,
KC_FN16 = 0xD0,
KC_FN17,
KC_FN18,
KC_FN19,
KC_FN20,
KC_FN21,
KC_FN22,
KC_FN23,
KC_FN24,
KC_FN25,
KC_FN26,
KC_FN27,
KC_FN28,
KC_FN29,
KC_FN30,
KC_FN31, /* 0xDF */
/**************************************/
/* 0xE0-E7 for Modifiers. DO NOT USE. */
/**************************************/
/* Mousekey */
KC_MS_UP = 0xF0,
KC_MS_DOWN,
KC_MS_LEFT,
KC_MS_RIGHT,
KC_MS_BTN1,
KC_MS_BTN2,
KC_MS_BTN3,
KC_MS_BTN4,
KC_MS_BTN5, /* 0xF8 */
/* Mousekey wheel */
KC_MS_WH_UP,
KC_MS_WH_DOWN,
KC_MS_WH_LEFT,
KC_MS_WH_RIGHT, /* 0xFC */
/* Mousekey accel */
KC_MS_ACCEL0,
KC_MS_ACCEL1,
KC_MS_ACCEL2 /* 0xFF */
};
#endif /* KEYCODE_H */

185
common/keymap.c Normal file
View file

@ -0,0 +1,185 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 "keymap.h"
#include "report.h"
#include "keycode.h"
#include "action_layer.h"
#include "action.h"
#include "action_macro.h"
#include "debug.h"
static action_t keycode_to_action(uint8_t keycode);
/* converts key to action */
action_t action_for_key(uint8_t layer, keypos_t key)
{
uint8_t keycode = keymap_key_to_keycode(layer, key);
switch (keycode) {
case KC_FN0 ... KC_FN31:
return keymap_fn_to_action(keycode);
#ifdef BOOTMAGIC_ENABLE
case KC_CAPSLOCK:
case KC_LOCKING_CAPS:
if (keymap_config.swap_control_capslock || keymap_config.capslock_to_control) {
return keycode_to_action(KC_LCTL);
}
return keycode_to_action(keycode);
case KC_LCTL:
if (keymap_config.swap_control_capslock) {
return keycode_to_action(KC_CAPSLOCK);
}
return keycode_to_action(KC_LCTL);
case KC_LALT:
if (keymap_config.swap_lalt_lgui) {
if (keymap_config.no_gui) {
return keycode_to_action(ACTION_NO);
}
return keycode_to_action(KC_LGUI);
}
return keycode_to_action(KC_LALT);
case KC_LGUI:
if (keymap_config.swap_lalt_lgui) {
return keycode_to_action(KC_LALT);
}
if (keymap_config.no_gui) {
return keycode_to_action(ACTION_NO);
}
return keycode_to_action(KC_LGUI);
case KC_RALT:
if (keymap_config.swap_ralt_rgui) {
if (keymap_config.no_gui) {
return keycode_to_action(ACTION_NO);
}
return keycode_to_action(KC_RGUI);
}
return keycode_to_action(KC_RALT);
case KC_RGUI:
if (keymap_config.swap_ralt_rgui) {
return keycode_to_action(KC_RALT);
}
if (keymap_config.no_gui) {
return keycode_to_action(ACTION_NO);
}
return keycode_to_action(KC_RGUI);
case KC_GRAVE:
if (keymap_config.swap_grave_esc) {
return keycode_to_action(KC_ESC);
}
return keycode_to_action(KC_GRAVE);
case KC_ESC:
if (keymap_config.swap_grave_esc) {
return keycode_to_action(KC_GRAVE);
}
return keycode_to_action(KC_ESC);
case KC_BSLASH:
if (keymap_config.swap_backslash_backspace) {
return keycode_to_action(KC_BSPACE);
}
return keycode_to_action(KC_BSLASH);
case KC_BSPACE:
if (keymap_config.swap_backslash_backspace) {
return keycode_to_action(KC_BSLASH);
}
return keycode_to_action(KC_BSPACE);
#endif
default:
return keycode_to_action(keycode);
}
}
/* Macro */
__attribute__ ((weak))
const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt)
{
return MACRO_NONE;
}
/* Function */
__attribute__ ((weak))
void action_function(keyrecord_t *record, uint8_t id, uint8_t opt)
{
}
/* translates keycode to action */
static action_t keycode_to_action(uint8_t keycode)
{
action_t action;
switch (keycode) {
case KC_A ... KC_EXSEL:
case KC_LCTRL ... KC_RGUI:
action.code = ACTION_KEY(keycode);
break;
case KC_SYSTEM_POWER ... KC_SYSTEM_WAKE:
action.code = ACTION_USAGE_SYSTEM(KEYCODE2SYSTEM(keycode));
break;
case KC_AUDIO_MUTE ... KC_WWW_FAVORITES:
action.code = ACTION_USAGE_CONSUMER(KEYCODE2CONSUMER(keycode));
break;
case KC_MS_UP ... KC_MS_ACCEL2:
action.code = ACTION_MOUSEKEY(keycode);
break;
case KC_TRNS:
action.code = ACTION_TRANSPARENT;
break;
default:
action.code = ACTION_NO;
break;
}
return action;
}
#ifdef USE_LEGACY_KEYMAP
/*
* Legacy keymap support
* Consider using new keymap API instead.
*/
__attribute__ ((weak))
uint8_t keymap_key_to_keycode(uint8_t layer, keypos_t key)
{
return keymap_get_keycode(layer, key.row, key.col);
}
/* Legacy keymap support */
__attribute__ ((weak))
action_t keymap_fn_to_action(uint8_t keycode)
{
action_t action = { .code = ACTION_NO };
switch (keycode) {
case KC_FN0 ... KC_FN31:
{
uint8_t layer = keymap_fn_layer(FN_INDEX(keycode));
uint8_t key = keymap_fn_keycode(FN_INDEX(keycode));
if (key) {
action.code = ACTION_LAYER_TAP_KEY(layer, key);
} else {
action.code = ACTION_LAYER_MOMENTARY(layer);
}
}
return action;
default:
return action;
}
}
#endif

71
common/keymap.h Normal file
View file

@ -0,0 +1,71 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef KEYMAP_H
#define KEYMAP_H
#include <stdint.h>
#include <stdbool.h>
#include "action.h"
#ifdef BOOTMAGIC_ENABLE
/* NOTE: Not portable. Bit field order depends on implementation */
typedef union {
uint8_t raw;
struct {
bool swap_control_capslock:1;
bool capslock_to_control:1;
bool swap_lalt_lgui:1;
bool swap_ralt_rgui:1;
bool no_gui:1;
bool swap_grave_esc:1;
bool swap_backslash_backspace:1;
bool nkro:1;
};
} keymap_config_t;
keymap_config_t keymap_config;
#endif
/* translates key to keycode */
uint8_t keymap_key_to_keycode(uint8_t layer, keypos_t key);
/* translates Fn keycode to action */
action_t keymap_fn_to_action(uint8_t keycode);
#ifdef USE_LEGACY_KEYMAP
/*
* Legacy keymap
* Consider using new keymap API above instead.
*/
/* keycode of key */
__attribute__ ((deprecated))
uint8_t keymap_get_keycode(uint8_t layer, uint8_t row, uint8_t col);
/* layer to move during press Fn key */
__attribute__ ((deprecated))
uint8_t keymap_fn_layer(uint8_t fn_bits);
/* keycode to send when release Fn key without using */
__attribute__ ((deprecated))
uint8_t keymap_fn_keycode(uint8_t fn_bits);
#endif
#endif

33
common/led.h Normal file
View file

@ -0,0 +1,33 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef LED_H
#define LED_H
#include "stdint.h"
/* keyboard LEDs */
#define USB_LED_NUM_LOCK 0
#define USB_LED_CAPS_LOCK 1
#define USB_LED_SCROLL_LOCK 2
#define USB_LED_COMPOSE 3
#define USB_LED_KANA 4
void led_set(uint8_t usb_led);
#endif

68
common/matrix.h Normal file
View file

@ -0,0 +1,68 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef MATRIX_H
#define MATRIX_H
#include <stdint.h>
#include <stdbool.h>
#if (MATRIX_COLS <= 8)
typedef uint8_t matrix_row_t;
#elif (MATRIX_COLS <= 16)
typedef uint16_t matrix_row_t;
#elif (MATRIX_COLS <= 32)
typedef uint32_t matrix_row_t;
#else
#error "MATRIX_COLS: invalid value"
#endif
#define MATRIX_IS_ON(row, col) (matrix_get_row(row) && (1<<col))
#ifdef __cplusplus
extern "C" {
#endif
/* number of matrix rows */
uint8_t matrix_rows(void);
/* number of matrix columns */
uint8_t matrix_cols(void);
/* intialize matrix for scaning. should be called once. */
void matrix_init(void);
/* scan all key states on matrix */
uint8_t matrix_scan(void);
/* whether modified from previous scan. used after matrix_scan. */
bool matrix_is_modified(void) __attribute__ ((deprecated));
/* whether a swtich is on */
bool matrix_is_on(uint8_t row, uint8_t col);
/* matrix state on row */
matrix_row_t matrix_get_row(uint8_t row);
/* print matrix for debug */
void matrix_print(void);
/* power control */
void matrix_power_up(void);
void matrix_power_down(void);
#ifdef __cplusplus
}
#endif
#endif

4
common/mbed/bootloader.c Normal file
View file

@ -0,0 +1,4 @@
#include "bootloader.h"
void bootloader_jump(void) {}

6
common/mbed/suspend.c Normal file
View file

@ -0,0 +1,6 @@
#include <stdbool.h>
void suspend_power_down(void) {}
bool suspend_wakeup_condition(void) { return true; }
void suspend_wakeup_init(void) {}

41
common/mbed/timer.c Normal file
View file

@ -0,0 +1,41 @@
#include "cmsis.h"
#include "timer.h"
/* Mill second tick count */
volatile uint32_t timer_count = 0;
/* Timer interrupt handler */
void SysTick_Handler(void) {
timer_count++;
}
void timer_init(void)
{
timer_count = 0;
SysTick_Config(SystemCoreClock / 1000); /* 1ms tick */
}
void timer_clear(void)
{
timer_count = 0;
}
uint16_t timer_read(void)
{
return (uint16_t)(timer_count & 0xFFFF);
}
uint32_t timer_read32(void)
{
return timer_count;
}
uint16_t timer_elapsed(uint16_t last)
{
return TIMER_DIFF_16(timer_read(), last);
}
uint32_t timer_elapsed32(uint32_t last)
{
return TIMER_DIFF_32(timer_read32(), last);
}

51
common/mbed/xprintf.cpp Normal file
View file

@ -0,0 +1,51 @@
#include <cstdarg>
//#include <stdarg.h>
#include "mbed.h"
#include "mbed/xprintf.h"
#define STRING_STACK_LIMIT 120
//TODO
int xprintf(const char* format, ...) { return 0; }
#if 0
/* mbed Serial */
Serial ser(UART_TX, UART_RX);
/* TODO: Need small implementation for embedded */
int xprintf(const char* format, ...)
{
/* copy from mbed/common/RawSerial.cpp */
std::va_list arg;
va_start(arg, format);
int len = vsnprintf(NULL, 0, format, arg);
if (len < STRING_STACK_LIMIT) {
char temp[STRING_STACK_LIMIT];
vsprintf(temp, format, arg);
ser.puts(temp);
} else {
char *temp = new char[len + 1];
vsprintf(temp, format, arg);
ser.puts(temp);
delete[] temp;
}
va_end(arg);
return len;
/* Fail: __builtin_va_arg_pack?
* https://gcc.gnu.org/onlinedocs/gcc-4.3.5/gcc/Constructing-Calls.html#Constructing-Calls
void *arg = __builtin_apply_args();
void *ret = __builtin_apply((void*)(&(ser.printf)), arg, 100);
__builtin_return(ret)
*/
/* Fail: varargs can not be passed to printf
//int r = ser.printf("test %i\r\n", 123);
va_list arg;
va_start(arg, format);
int r = ser.printf(format, arg);
va_end(arg);
return r;
*/
}
#endif

17
common/mbed/xprintf.h Normal file
View file

@ -0,0 +1,17 @@
#ifndef XPRINTF_H
#define XPRINTF_H
//#define xprintf(format, ...) __xprintf(format, ##__VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
int xprintf(const char *format, ...);
#ifdef __cplusplus
}
#endif
#endif

196
common/mousekey.c Normal file
View file

@ -0,0 +1,196 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <stdint.h>
#include "keycode.h"
#include "host.h"
#include "timer.h"
#include "print.h"
#include "debug.h"
#include "mousekey.h"
static report_mouse_t mouse_report = {};
static uint8_t mousekey_repeat = 0;
static uint8_t mousekey_accel = 0;
static void mousekey_debug(void);
/*
* Mouse keys acceleration algorithm
* http://en.wikipedia.org/wiki/Mouse_keys
*
* speed = delta * max_speed * (repeat / time_to_max)**((1000+curve)/1000)
*/
/* milliseconds between the initial key press and first repeated motion event (0-2550) */
uint8_t mk_delay = MOUSEKEY_DELAY/10;
/* milliseconds between repeated motion events (0-255) */
uint8_t mk_interval = MOUSEKEY_INTERVAL;
/* steady speed (in action_delta units) applied each event (0-255) */
uint8_t mk_max_speed = MOUSEKEY_MAX_SPEED;
/* number of events (count) accelerating to steady speed (0-255) */
uint8_t mk_time_to_max = MOUSEKEY_TIME_TO_MAX;
/* ramp used to reach maximum pointer speed (NOT SUPPORTED) */
//int8_t mk_curve = 0;
/* wheel params */
uint8_t mk_wheel_max_speed = MOUSEKEY_WHEEL_MAX_SPEED;
uint8_t mk_wheel_time_to_max = MOUSEKEY_WHEEL_TIME_TO_MAX;
static uint16_t last_timer = 0;
static uint8_t move_unit(void)
{
uint16_t unit;
if (mousekey_accel & (1<<0)) {
unit = (MOUSEKEY_MOVE_DELTA * mk_max_speed)/4;
} else if (mousekey_accel & (1<<1)) {
unit = (MOUSEKEY_MOVE_DELTA * mk_max_speed)/2;
} else if (mousekey_accel & (1<<2)) {
unit = (MOUSEKEY_MOVE_DELTA * mk_max_speed);
} else if (mousekey_repeat == 0) {
unit = MOUSEKEY_MOVE_DELTA;
} else if (mousekey_repeat >= mk_time_to_max) {
unit = MOUSEKEY_MOVE_DELTA * mk_max_speed;
} else {
unit = (MOUSEKEY_MOVE_DELTA * mk_max_speed * mousekey_repeat) / mk_time_to_max;
}
return (unit > MOUSEKEY_MOVE_MAX ? MOUSEKEY_MOVE_MAX : (unit == 0 ? 1 : unit));
}
static uint8_t wheel_unit(void)
{
uint16_t unit;
if (mousekey_accel & (1<<0)) {
unit = (MOUSEKEY_WHEEL_DELTA * mk_wheel_max_speed)/4;
} else if (mousekey_accel & (1<<1)) {
unit = (MOUSEKEY_WHEEL_DELTA * mk_wheel_max_speed)/2;
} else if (mousekey_accel & (1<<2)) {
unit = (MOUSEKEY_WHEEL_DELTA * mk_wheel_max_speed);
} else if (mousekey_repeat == 0) {
unit = MOUSEKEY_WHEEL_DELTA;
} else if (mousekey_repeat >= mk_wheel_time_to_max) {
unit = MOUSEKEY_WHEEL_DELTA * mk_wheel_max_speed;
} else {
unit = (MOUSEKEY_WHEEL_DELTA * mk_wheel_max_speed * mousekey_repeat) / mk_wheel_time_to_max;
}
return (unit > MOUSEKEY_WHEEL_MAX ? MOUSEKEY_WHEEL_MAX : (unit == 0 ? 1 : unit));
}
void mousekey_task(void)
{
if (timer_elapsed(last_timer) < (mousekey_repeat ? mk_interval : mk_delay*10))
return;
if (mouse_report.x == 0 && mouse_report.y == 0 && mouse_report.v == 0 && mouse_report.h == 0)
return;
if (mousekey_repeat != UINT8_MAX)
mousekey_repeat++;
if (mouse_report.x > 0) mouse_report.x = move_unit();
if (mouse_report.x < 0) mouse_report.x = move_unit() * -1;
if (mouse_report.y > 0) mouse_report.y = move_unit();
if (mouse_report.y < 0) mouse_report.y = move_unit() * -1;
/* diagonal move [1/sqrt(2) = 0.7] */
if (mouse_report.x && mouse_report.y) {
mouse_report.x *= 0.7;
mouse_report.y *= 0.7;
}
if (mouse_report.v > 0) mouse_report.v = wheel_unit();
if (mouse_report.v < 0) mouse_report.v = wheel_unit() * -1;
if (mouse_report.h > 0) mouse_report.h = wheel_unit();
if (mouse_report.h < 0) mouse_report.h = wheel_unit() * -1;
mousekey_send();
}
void mousekey_on(uint8_t code)
{
if (code == KC_MS_UP) mouse_report.y = move_unit() * -1;
else if (code == KC_MS_DOWN) mouse_report.y = move_unit();
else if (code == KC_MS_LEFT) mouse_report.x = move_unit() * -1;
else if (code == KC_MS_RIGHT) mouse_report.x = move_unit();
else if (code == KC_MS_WH_UP) mouse_report.v = wheel_unit();
else if (code == KC_MS_WH_DOWN) mouse_report.v = wheel_unit() * -1;
else if (code == KC_MS_WH_LEFT) mouse_report.h = wheel_unit() * -1;
else if (code == KC_MS_WH_RIGHT) mouse_report.h = wheel_unit();
else if (code == KC_MS_BTN1) mouse_report.buttons |= MOUSE_BTN1;
else if (code == KC_MS_BTN2) mouse_report.buttons |= MOUSE_BTN2;
else if (code == KC_MS_BTN3) mouse_report.buttons |= MOUSE_BTN3;
else if (code == KC_MS_BTN4) mouse_report.buttons |= MOUSE_BTN4;
else if (code == KC_MS_BTN5) mouse_report.buttons |= MOUSE_BTN5;
else if (code == KC_MS_ACCEL0) mousekey_accel |= (1<<0);
else if (code == KC_MS_ACCEL1) mousekey_accel |= (1<<1);
else if (code == KC_MS_ACCEL2) mousekey_accel |= (1<<2);
}
void mousekey_off(uint8_t code)
{
if (code == KC_MS_UP && mouse_report.y < 0) mouse_report.y = 0;
else if (code == KC_MS_DOWN && mouse_report.y > 0) mouse_report.y = 0;
else if (code == KC_MS_LEFT && mouse_report.x < 0) mouse_report.x = 0;
else if (code == KC_MS_RIGHT && mouse_report.x > 0) mouse_report.x = 0;
else if (code == KC_MS_WH_UP && mouse_report.v > 0) mouse_report.v = 0;
else if (code == KC_MS_WH_DOWN && mouse_report.v < 0) mouse_report.v = 0;
else if (code == KC_MS_WH_LEFT && mouse_report.h < 0) mouse_report.h = 0;
else if (code == KC_MS_WH_RIGHT && mouse_report.h > 0) mouse_report.h = 0;
else if (code == KC_MS_BTN1) mouse_report.buttons &= ~MOUSE_BTN1;
else if (code == KC_MS_BTN2) mouse_report.buttons &= ~MOUSE_BTN2;
else if (code == KC_MS_BTN3) mouse_report.buttons &= ~MOUSE_BTN3;
else if (code == KC_MS_BTN4) mouse_report.buttons &= ~MOUSE_BTN4;
else if (code == KC_MS_BTN5) mouse_report.buttons &= ~MOUSE_BTN5;
else if (code == KC_MS_ACCEL0) mousekey_accel &= ~(1<<0);
else if (code == KC_MS_ACCEL1) mousekey_accel &= ~(1<<1);
else if (code == KC_MS_ACCEL2) mousekey_accel &= ~(1<<2);
if (mouse_report.x == 0 && mouse_report.y == 0 && mouse_report.v == 0 && mouse_report.h == 0)
mousekey_repeat = 0;
}
void mousekey_send(void)
{
mousekey_debug();
host_mouse_send(&mouse_report);
last_timer = timer_read();
}
void mousekey_clear(void)
{
mouse_report = (report_mouse_t){};
mousekey_repeat = 0;
mousekey_accel = 0;
}
static void mousekey_debug(void)
{
if (!debug_mouse) return;
print("mousekey [btn|x y v h](rep/acl): [");
phex(mouse_report.buttons); print("|");
print_decs(mouse_report.x); print(" ");
print_decs(mouse_report.y); print(" ");
print_decs(mouse_report.v); print(" ");
print_decs(mouse_report.h); print("](");
print_dec(mousekey_repeat); print("/");
print_dec(mousekey_accel); print(")\n");
}

77
common/mousekey.h Normal file
View file

@ -0,0 +1,77 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef MOUSEKEY_H
#define MOUSEKEY_H
#include <stdbool.h>
#include "host.h"
/* max value on report descriptor */
#define MOUSEKEY_MOVE_MAX 127
#define MOUSEKEY_WHEEL_MAX 127
#ifndef MOUSEKEY_MOVE_DELTA
#define MOUSEKEY_MOVE_DELTA 5
#endif
#ifndef MOUSEKEY_WHEEL_DELTA
#define MOUSEKEY_WHEEL_DELTA 1
#endif
#ifndef MOUSEKEY_DELAY
#define MOUSEKEY_DELAY 300
#endif
#ifndef MOUSEKEY_INTERVAL
#define MOUSEKEY_INTERVAL 50
#endif
#ifndef MOUSEKEY_MAX_SPEED
#define MOUSEKEY_MAX_SPEED 10
#endif
#ifndef MOUSEKEY_TIME_TO_MAX
#define MOUSEKEY_TIME_TO_MAX 20
#endif
#ifndef MOUSEKEY_WHEEL_MAX_SPEED
#define MOUSEKEY_WHEEL_MAX_SPEED 8
#endif
#ifndef MOUSEKEY_WHEEL_TIME_TO_MAX
#define MOUSEKEY_WHEEL_TIME_TO_MAX 40
#endif
#ifdef __cplusplus
extern "C" {
#endif
extern uint8_t mk_delay;
extern uint8_t mk_interval;
extern uint8_t mk_max_speed;
extern uint8_t mk_time_to_max;
extern uint8_t mk_wheel_max_speed;
extern uint8_t mk_wheel_time_to_max;
void mousekey_task(void);
void mousekey_on(uint8_t code);
void mousekey_off(uint8_t code);
void mousekey_clear(void);
void mousekey_send(void);
#ifdef __cplusplus
}
#endif
#endif

25
common/nodebug.h Normal file
View file

@ -0,0 +1,25 @@
/*
Copyright 2013 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef NODEBUG_H
#define NODEBUG_H 1
#define NO_DEBUG
#include "debug.h"
#undef NO_DEBUG
#endif

48
common/print.c Normal file
View file

@ -0,0 +1,48 @@
/* Copyright 2012,2013 Jun Wako <wakojun@gmail.com> */
/* Very basic print functions, intended to be used with usb_debug_only.c
* http://www.pjrc.com/teensy/
* Copyright (c) 2008 PJRC.COM, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdint.h>
#include "print.h"
#ifndef NO_PRINT
#if defined(__AVR__)
#define sendchar(c) xputc(c)
void print_set_sendchar(int8_t (*sendchar_func)(uint8_t))
{
xdev_out(sendchar_func);
}
#elif defined(__arm__)
// TODO
//void print_set_sendchar(int8_t (*sendchar_func)(uint8_t)) { }
#endif
#endif

137
common/print.h Normal file
View file

@ -0,0 +1,137 @@
/* Copyright 2012 Jun Wako <wakojun@gmail.com> */
/* Very basic print functions, intended to be used with usb_debug_only.c
* http://www.pjrc.com/teensy/
* Copyright (c) 2008 PJRC.COM, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef PRINT_H__
#define PRINT_H__ 1
#include <stdint.h>
#include <stdbool.h>
#include "util.h"
#ifndef NO_PRINT
#if defined(__AVR__)
#include "avr/xprintf.h"
#define print(s) xputs(PSTR(s))
#define println(s) xputs(PSTR(s "\r\n"))
#ifdef __cplusplus
extern "C"
#endif
/* function pointer of sendchar to be used by print utility */
void print_set_sendchar(int8_t (*print_sendchar_func)(uint8_t));
#elif defined(__arm__)
#include "mbed/xprintf.h"
#define print(s) xprintf(s)
#define println(s) xprintf(s "\r\n")
/* TODO: to select output destinations: UART/USBSerial */
#define print_set_sendchar(func)
#endif /* __AVR__ */
/* decimal */
#define print_dec(i) xprintf("%u", i)
#define print_decs(i) xprintf("%d", i)
/* hex */
#define print_hex4(i) xprintf("%X", i)
#define print_hex8(i) xprintf("%02X", i)
#define print_hex16(i) xprintf("%04X", i)
#define print_hex32(i) xprintf("%08lX", i)
/* binary */
#define print_bin4(i) xprintf("%04b", i)
#define print_bin8(i) xprintf("%08b", i)
#define print_bin16(i) xprintf("%016b", i)
#define print_bin32(i) xprintf("%032lb", i)
#define print_bin_reverse8(i) xprintf("%08b", bitrev(i))
#define print_bin_reverse16(i) xprintf("%016b", bitrev16(i))
#define print_bin_reverse32(i) xprintf("%032lb", bitrev32(i))
/* print value utility */
#define print_val_dec(v) xprintf(#v ": %u\n", v)
#define print_val_decs(v) xprintf(#v ": %d\n", v)
#define print_val_hex8(v) xprintf(#v ": %X\n", v)
#define print_val_hex16(v) xprintf(#v ": %02X\n", v)
#define print_val_hex32(v) xprintf(#v ": %04lX\n", v)
#define print_val_bin8(v) xprintf(#v ": %08b\n", v)
#define print_val_bin16(v) xprintf(#v ": %016b\n", v)
#define print_val_bin32(v) xprintf(#v ": %032lb\n", v)
#define print_val_bin_reverse8(v) xprintf(#v ": %08b\n", bitrev(v))
#define print_val_bin_reverse16(v) xprintf(#v ": %016b\n", bitrev16(v))
#define print_val_bin_reverse32(v) xprintf(#v ": %032lb\n", bitrev32(v))
#else /* NO_PRINT */
#define xprintf
#define print
#define println
#define print_set_sendchar(func)
#define print_dec(data)
#define print_decs(data)
#define print_hex4(data)
#define print_hex8(data)
#define print_hex16(data)
#define print_hex32(data)
#define print_bin4(data)
#define print_bin8(data)
#define print_bin16(data)
#define print_bin32(data)
#define print_bin_reverse8(data)
#define print_bin_reverse16(data)
#define print_bin_reverse32(data)
#define print_val_dec(v)
#define print_val_decs(v)
#define print_val_hex8(v)
#define print_val_hex16(v)
#define print_val_hex32(v)
#define print_val_bin8(v)
#define print_val_bin16(v)
#define print_val_bin32(v)
#define print_val_bin_reverse8(v)
#define print_val_bin_reverse16(v)
#define print_val_bin_reverse32(v)
#endif /* NO_PRINT */
/* Backward compatiblitly for old name */
#define pdec(data) print_dec(data)
#define pdec16(data) print_dec(data)
#define phex(data) print_hex8(data)
#define phex16(data) print_hex16(data)
#define pbin(data) print_bin8(data)
#define pbin16(data) print_bin16(data)
#define pbin_reverse(data) print_bin_reverse8(data)
#define pbin_reverse16(data) print_bin_reverse16(data)
#endif

12
common/progmem.h Normal file
View file

@ -0,0 +1,12 @@
#ifndef PROGMEM_H
#define PROGMEM_H 1
#if defined(__AVR__)
# include <avr/pgmspace.h>
#elif defined(__arm__)
# define PROGMEM
# define pgm_read_byte(p) *(p)
# define pgm_read_word(p) *(p)
#endif
#endif

183
common/report.h Normal file
View file

@ -0,0 +1,183 @@
/*
Copyright 2011,2012 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef REPORT_H
#define REPORT_H
#include <stdint.h>
#include "keycode.h"
/* report id */
#define REPORT_ID_MOUSE 1
#define REPORT_ID_SYSTEM 2
#define REPORT_ID_CONSUMER 3
/* mouse buttons */
#define MOUSE_BTN1 (1<<0)
#define MOUSE_BTN2 (1<<1)
#define MOUSE_BTN3 (1<<2)
#define MOUSE_BTN4 (1<<3)
#define MOUSE_BTN5 (1<<4)
/* Consumer Page(0x0C)
* following are supported by Windows: http://msdn.microsoft.com/en-us/windows/hardware/gg463372.aspx
*/
#define AUDIO_MUTE 0x00E2
#define AUDIO_VOL_UP 0x00E9
#define AUDIO_VOL_DOWN 0x00EA
#define TRANSPORT_NEXT_TRACK 0x00B5
#define TRANSPORT_PREV_TRACK 0x00B6
#define TRANSPORT_STOP 0x00B7
#define TRANSPORT_STOP_EJECT 0x00CC
#define TRANSPORT_PLAY_PAUSE 0x00CD
/* application launch */
#define AL_CC_CONFIG 0x0183
#define AL_EMAIL 0x018A
#define AL_CALCULATOR 0x0192
#define AL_LOCAL_BROWSER 0x0194
/* application control */
#define AC_SEARCH 0x0221
#define AC_HOME 0x0223
#define AC_BACK 0x0224
#define AC_FORWARD 0x0225
#define AC_STOP 0x0226
#define AC_REFRESH 0x0227
#define AC_BOOKMARKS 0x022A
/* supplement for Bluegiga iWRAP HID(not supported by Windows?) */
#define AL_LOCK 0x019E
#define TRANSPORT_RECORD 0x00B2
#define TRANSPORT_FAST_FORWARD 0x00B3
#define TRANSPORT_REWIND 0x00B4
#define TRANSPORT_EJECT 0x00B8
#define AC_MINIMIZE 0x0206
/* Generic Desktop Page(0x01) - system power control */
#define SYSTEM_POWER_DOWN 0x0081
#define SYSTEM_SLEEP 0x0082
#define SYSTEM_WAKE_UP 0x0083
/* key report size(NKRO or boot mode) */
#if defined(PROTOCOL_PJRC) && defined(NKRO_ENABLE)
# include "usb.h"
# define KEYBOARD_REPORT_SIZE KBD2_SIZE
# define KEYBOARD_REPORT_KEYS (KBD2_SIZE - 2)
# define KEYBOARD_REPORT_BITS (KBD2_SIZE - 1)
#elif defined(PROTOCOL_LUFA) && defined(NKRO_ENABLE)
# include "protocol/lufa/descriptor.h"
# define KEYBOARD_REPORT_SIZE NKRO_EPSIZE
# define KEYBOARD_REPORT_KEYS (NKRO_EPSIZE - 2)
# define KEYBOARD_REPORT_BITS (NKRO_EPSIZE - 1)
#else
# define KEYBOARD_REPORT_SIZE 8
# define KEYBOARD_REPORT_KEYS 6
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*
* keyboard report is 8-byte array retains state of 8 modifiers and 6 keys.
*
* byte |0 |1 |2 |3 |4 |5 |6 |7
* -----+--------+--------+--------+--------+--------+--------+--------+--------
* desc |mods |reserved|keys[0] |keys[1] |keys[2] |keys[3] |keys[4] |keys[5]
*
* It is exended to 16 bytes to retain 120keys+8mods when NKRO mode.
*
* byte |0 |1 |2 |3 |4 |5 |6 |7 ... |15
* -----+--------+--------+--------+--------+--------+--------+--------+-------- +--------
* desc |mods |bits[0] |bits[1] |bits[2] |bits[3] |bits[4] |bits[5] |bits[6] ... |bit[14]
*
* mods retains state of 8 modifiers.
*
* bit |0 |1 |2 |3 |4 |5 |6 |7
* -----+--------+--------+--------+--------+--------+--------+--------+--------
* desc |Lcontrol|Lshift |Lalt |Lgui |Rcontrol|Rshift |Ralt |Rgui
*
*/
typedef union {
uint8_t raw[KEYBOARD_REPORT_SIZE];
struct {
uint8_t mods;
uint8_t reserved;
uint8_t keys[KEYBOARD_REPORT_KEYS];
};
#ifdef NKRO_ENABLE
struct {
uint8_t mods;
uint8_t bits[KEYBOARD_REPORT_BITS];
} nkro;
#endif
} __attribute__ ((packed)) report_keyboard_t;
/*
typedef struct {
uint8_t mods;
uint8_t reserved;
uint8_t keys[REPORT_KEYS];
} __attribute__ ((packed)) report_keyboard_t;
*/
typedef struct {
uint8_t buttons;
int8_t x;
int8_t y;
int8_t v;
int8_t h;
} __attribute__ ((packed)) report_mouse_t;
/* keycode to system usage */
#define KEYCODE2SYSTEM(key) \
(key == KC_SYSTEM_POWER ? SYSTEM_POWER_DOWN : \
(key == KC_SYSTEM_SLEEP ? SYSTEM_SLEEP : \
(key == KC_SYSTEM_WAKE ? SYSTEM_WAKE_UP : 0)))
/* keycode to consumer usage */
#define KEYCODE2CONSUMER(key) \
(key == KC_AUDIO_MUTE ? AUDIO_MUTE : \
(key == KC_AUDIO_VOL_UP ? AUDIO_VOL_UP : \
(key == KC_AUDIO_VOL_DOWN ? AUDIO_VOL_DOWN : \
(key == KC_MEDIA_NEXT_TRACK ? TRANSPORT_NEXT_TRACK : \
(key == KC_MEDIA_PREV_TRACK ? TRANSPORT_PREV_TRACK : \
(key == KC_MEDIA_FAST_FORWARD ? TRANSPORT_FAST_FORWARD : \
(key == KC_MEDIA_REWIND ? TRANSPORT_REWIND : \
(key == KC_MEDIA_STOP ? TRANSPORT_STOP : \
(key == KC_MEDIA_EJECT ? TRANSPORT_STOP_EJECT : \
(key == KC_MEDIA_PLAY_PAUSE ? TRANSPORT_PLAY_PAUSE : \
(key == KC_MEDIA_SELECT ? AL_CC_CONFIG : \
(key == KC_MAIL ? AL_EMAIL : \
(key == KC_CALCULATOR ? AL_CALCULATOR : \
(key == KC_MY_COMPUTER ? AL_LOCAL_BROWSER : \
(key == KC_WWW_SEARCH ? AC_SEARCH : \
(key == KC_WWW_HOME ? AC_HOME : \
(key == KC_WWW_BACK ? AC_BACK : \
(key == KC_WWW_FORWARD ? AC_FORWARD : \
(key == KC_WWW_STOP ? AC_STOP : \
(key == KC_WWW_REFRESH ? AC_REFRESH : \
(key == KC_WWW_FAVORITES ? AC_BOOKMARKS : 0)))))))))))))))))))))
#ifdef __cplusplus
}
#endif
#endif

35
common/sendchar.h Normal file
View file

@ -0,0 +1,35 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef SENDCHAR_H
#define SENDCHAR_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* transmit a character. return 0 on success, -1 on error. */
int8_t sendchar(uint8_t c);
#ifdef __cplusplus
}
#endif
#endif

23
common/sendchar_null.c Normal file
View file

@ -0,0 +1,23 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 "sendchar.h"
int8_t sendchar(uint8_t c)
{
return 0;
}

25
common/sendchar_uart.c Normal file
View file

@ -0,0 +1,25 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 "uart.h"
#include "sendchar.h"
int8_t sendchar(uint8_t c)
{
uart_putchar(c);
return 0;
}

95
common/sleep_led.c Normal file
View file

@ -0,0 +1,95 @@
#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include "led.h"
#include "sleep_led.h"
/* Software PWM
* ______ ______ __
* | ON |___OFF___| ON |___OFF___| ....
* |<-------------->|<-------------->|<- ....
* PWM period PWM period
*
* 256 interrupts/period[resolution]
* 64 periods/second[frequency]
* 256*64 interrupts/second
* F_CPU/(256*64) clocks/interrupt
*/
#define SLEEP_LED_TIMER_TOP F_CPU/(256*64)
void sleep_led_init(void)
{
/* Timer1 setup */
/* CTC mode */
TCCR1B |= _BV(WGM12);
/* Clock selelct: clk/1 */
TCCR1B |= _BV(CS10);
/* Set TOP value */
uint8_t sreg = SREG;
cli();
OCR1AH = (SLEEP_LED_TIMER_TOP>>8)&0xff;
OCR1AL = SLEEP_LED_TIMER_TOP&0xff;
SREG = sreg;
}
void sleep_led_enable(void)
{
/* Enable Compare Match Interrupt */
TIMSK1 |= _BV(OCIE1A);
}
void sleep_led_disable(void)
{
/* Disable Compare Match Interrupt */
TIMSK1 &= ~_BV(OCIE1A);
}
void sleep_led_toggle(void)
{
/* Disable Compare Match Interrupt */
TIMSK1 ^= _BV(OCIE1A);
}
/* Breathing Sleep LED brighness(PWM On period) table
* (64[steps] * 4[duration]) / 64[PWM periods/s] = 4 second breath cycle
*
* http://www.wolframalpha.com/input/?i=%28sin%28+x%2F64*pi%29**8+*+255%2C+x%3D0+to+63
* (0..63).each {|x| p ((sin(x/64.0*PI)**8)*255).to_i }
*/
static const uint8_t breathing_table[64] PROGMEM = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 6, 10,
15, 23, 32, 44, 58, 74, 93, 113, 135, 157, 179, 199, 218, 233, 245, 252,
255, 252, 245, 233, 218, 199, 179, 157, 135, 113, 93, 74, 58, 44, 32, 23,
15, 10, 6, 4, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
ISR(TIMER1_COMPA_vect)
{
/* Software PWM
* timer:1111 1111 1111 1111
* \_____/\/ \_______/____ count(0-255)
* \ \______________ duration of step(4)
* \__________________ index of step table(0-63)
*/
static union {
uint16_t row;
struct {
uint8_t count:8;
uint8_t duration:2;
uint8_t index:6;
} pwm;
} timer = { .row = 0 };
timer.row++;
// LED on
if (timer.pwm.count == 0) {
led_set(1<<USB_LED_CAPS_LOCK);
}
// LED off
if (timer.pwm.count == pgm_read_byte(&breathing_table[timer.pwm.index])) {
led_set(0);
}
}

21
common/sleep_led.h Normal file
View file

@ -0,0 +1,21 @@
#ifndef SLEEP_LED_H
#define SLEEP_LED_H
#ifdef SLEEP_LED_ENABLE
void sleep_led_init(void);
void sleep_led_enable(void);
void sleep_led_disable(void);
void sleep_led_toggle(void);
#else
#define sleep_led_init()
#define sleep_led_enable()
#define sleep_led_disable()
#define sleep_led_toggle()
#endif
#endif

13
common/suspend.h Normal file
View file

@ -0,0 +1,13 @@
#ifndef SUSPEND_H
#define SUSPEND_H
#include <stdint.h>
#include <stdbool.h>
void suspend_idle(uint8_t timeout);
void suspend_power_down(void);
bool suspend_wakeup_condition(void);
void suspend_wakeup_init(void);
#endif

53
common/timer.h Normal file
View file

@ -0,0 +1,53 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef TIMER_H
#define TIMER_H 1
#include <stdint.h>
#if defined(__AVR__)
#include "avr/timer_avr.h"
#endif
#define TIMER_DIFF(a, b, max) ((a) >= (b) ? (a) - (b) : (max) - (b) + (a))
#define TIMER_DIFF_8(a, b) TIMER_DIFF(a, b, UINT8_MAX)
#define TIMER_DIFF_16(a, b) TIMER_DIFF(a, b, UINT16_MAX)
#define TIMER_DIFF_32(a, b) TIMER_DIFF(a, b, UINT32_MAX)
#define TIMER_DIFF_RAW(a, b) TIMER_DIFF_8(a, b)
#ifdef __cplusplus
extern "C" {
#endif
extern volatile uint32_t timer_count;
void timer_init(void);
void timer_clear(void);
uint16_t timer_read(void);
uint32_t timer_read32(void);
uint16_t timer_elapsed(uint16_t last);
uint32_t timer_elapsed32(uint32_t last);
#ifdef __cplusplus
}
#endif
#endif

129
common/uart.c Normal file
View file

@ -0,0 +1,129 @@
// TODO: Teensy support(ATMega32u4/AT90USB128)
// Fixed for Arduino Duemilanove ATmega168p by Jun Wako
/* UART Example for Teensy USB Development Board
* http://www.pjrc.com/teensy/
* Copyright (c) 2009 PJRC.COM, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// Version 1.0: Initial Release
// Version 1.1: Add support for Teensy 2.0, minor optimizations
#include <avr/io.h>
#include <avr/interrupt.h>
#include "uart.h"
// These buffers may be any size from 2 to 256 bytes.
#define RX_BUFFER_SIZE 64
#define TX_BUFFER_SIZE 40
static volatile uint8_t tx_buffer[TX_BUFFER_SIZE];
static volatile uint8_t tx_buffer_head;
static volatile uint8_t tx_buffer_tail;
static volatile uint8_t rx_buffer[RX_BUFFER_SIZE];
static volatile uint8_t rx_buffer_head;
static volatile uint8_t rx_buffer_tail;
// Initialize the UART
void uart_init(uint32_t baud)
{
cli();
UBRR0 = (F_CPU / 4 / baud - 1) / 2;
UCSR0A = (1<<U2X0);
UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0);
UCSR0C = (1<<UCSZ01) | (1<<UCSZ00);
tx_buffer_head = tx_buffer_tail = 0;
rx_buffer_head = rx_buffer_tail = 0;
sei();
}
// Transmit a byte
void uart_putchar(uint8_t c)
{
uint8_t i;
i = tx_buffer_head + 1;
if (i >= TX_BUFFER_SIZE) i = 0;
while (tx_buffer_tail == i) ; // wait until space in buffer
//cli();
tx_buffer[i] = c;
tx_buffer_head = i;
UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0) | (1<<UDRIE0);
//sei();
}
// Receive a byte
uint8_t uart_getchar(void)
{
uint8_t c, i;
while (rx_buffer_head == rx_buffer_tail) ; // wait for character
i = rx_buffer_tail + 1;
if (i >= RX_BUFFER_SIZE) i = 0;
c = rx_buffer[i];
rx_buffer_tail = i;
return c;
}
// Return the number of bytes waiting in the receive buffer.
// Call this before uart_getchar() to check if it will need
// to wait for a byte to arrive.
uint8_t uart_available(void)
{
uint8_t head, tail;
head = rx_buffer_head;
tail = rx_buffer_tail;
if (head >= tail) return head - tail;
return RX_BUFFER_SIZE + head - tail;
}
// Transmit Interrupt
ISR(USART_UDRE_vect)
{
uint8_t i;
if (tx_buffer_head == tx_buffer_tail) {
// buffer is empty, disable transmit interrupt
UCSR0B = (1<<RXEN0) | (1<<TXEN0) | (1<<RXCIE0);
} else {
i = tx_buffer_tail + 1;
if (i >= TX_BUFFER_SIZE) i = 0;
UDR0 = tx_buffer[i];
tx_buffer_tail = i;
}
}
// Receive Interrupt
ISR(USART_RX_vect)
{
uint8_t c, i;
c = UDR0;
i = rx_buffer_head + 1;
if (i >= RX_BUFFER_SIZE) i = 0;
if (i != rx_buffer_tail) {
rx_buffer[i] = c;
rx_buffer_head = i;
}
}

11
common/uart.h Normal file
View file

@ -0,0 +1,11 @@
#ifndef _uart_included_h_
#define _uart_included_h_
#include <stdint.h>
void uart_init(uint32_t baud);
void uart_putchar(uint8_t c);
uint8_t uart_getchar(void);
uint8_t uart_available(void);
#endif

101
common/util.c Normal file
View file

@ -0,0 +1,101 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 "util.h"
// bit population - return number of on-bit
uint8_t bitpop(uint8_t bits)
{
uint8_t c;
for (c = 0; bits; c++)
bits &= bits - 1;
return c;
/*
const uint8_t bit_count[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
return bit_count[bits>>4] + bit_count[bits&0x0F]
*/
}
uint8_t bitpop16(uint16_t bits)
{
uint8_t c;
for (c = 0; bits; c++)
bits &= bits - 1;
return c;
}
uint8_t bitpop32(uint32_t bits)
{
uint8_t c;
for (c = 0; bits; c++)
bits &= bits - 1;
return c;
}
// most significant on-bit - return highest location of on-bit
// NOTE: return 0 when bit0 is on or all bits are off
uint8_t biton(uint8_t bits)
{
uint8_t n = 0;
if (bits >> 4) { bits >>= 4; n += 4;}
if (bits >> 2) { bits >>= 2; n += 2;}
if (bits >> 1) { bits >>= 1; n += 1;}
return n;
}
uint8_t biton16(uint16_t bits)
{
uint8_t n = 0;
if (bits >> 8) { bits >>= 8; n += 8;}
if (bits >> 4) { bits >>= 4; n += 4;}
if (bits >> 2) { bits >>= 2; n += 2;}
if (bits >> 1) { bits >>= 1; n += 1;}
return n;
}
uint8_t biton32(uint32_t bits)
{
uint8_t n = 0;
if (bits >>16) { bits >>=16; n +=16;}
if (bits >> 8) { bits >>= 8; n += 8;}
if (bits >> 4) { bits >>= 4; n += 4;}
if (bits >> 2) { bits >>= 2; n += 2;}
if (bits >> 1) { bits >>= 1; n += 1;}
return n;
}
uint8_t bitrev(uint8_t bits)
{
bits = (bits & 0x0f)<<4 | (bits & 0xf0)>>4;
bits = (bits & 0b00110011)<<2 | (bits & 0b11001100)>>2;
bits = (bits & 0b01010101)<<1 | (bits & 0b10101010)>>1;
return bits;
}
uint16_t bitrev16(uint16_t bits)
{
bits = bitrev(bits & 0x00ff)<<8 | bitrev((bits & 0xff00)>>8);
return bits;
}
uint32_t bitrev32(uint32_t bits)
{
bits = (uint32_t)bitrev16(bits & 0x0000ffff)<<16 | bitrev16((bits & 0xffff0000)>>16);
return bits;
}

43
common/util.h Normal file
View file

@ -0,0 +1,43 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef UTIL_H
#define UTIL_H
#include <stdint.h>
// convert to L string
#define LSTR(s) XLSTR(s)
#define XLSTR(s) L ## #s
// convert to string
#define STR(s) XSTR(s)
#define XSTR(s) #s
uint8_t bitpop(uint8_t bits);
uint8_t bitpop16(uint16_t bits);
uint8_t bitpop32(uint32_t bits);
uint8_t biton(uint8_t bits);
uint8_t biton16(uint16_t bits);
uint8_t biton32(uint32_t bits);
uint8_t bitrev(uint8_t bits);
uint16_t bitrev16(uint16_t bits);
uint32_t bitrev32(uint32_t bits);
#endif

20
common/wait.h Normal file
View file

@ -0,0 +1,20 @@
#ifndef WAIT_H
#define WAIT_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__AVR__)
# include <util/delay.h>
# define wait_ms(ms) _delay_ms(ms)
# define wait_us(us) _delay_us(us)
#elif defined(__arm__)
# include "wait_api.h"
#endif
#ifdef __cplusplus
}
#endif
#endif

339
doc/COPYING.GPLv2 Normal file
View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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; either version 2 of the License, or
(at your option) any later version.
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

674
doc/COPYING.GPLv3 Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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, either version 3 of the License, or
(at your option) any later version.
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

40
doc/FUSE.txt Normal file
View file

@ -0,0 +1,40 @@
ATMega168P Fuse/Lock Bits
=========================
This configuration is from usbasploader's Makefile.
HFUSE 0xD6
LFUSE 0xDF
EFUSE 0x00
LOCK 0x3F(intact)
#---------------------------------------------------------------------
# ATMega168P
#---------------------------------------------------------------------
# Fuse extended byte:
# 0x00 = 0 0 0 0 0 0 0 0 <-- BOOTRST (boot reset vector at 0x1800)
# \+/
# +------- BOOTSZ (00 = 2k bytes)
# Fuse high byte:
# 0xd6 = 1 1 0 1 0 1 1 0
# ^ ^ ^ ^ ^ \-+-/
# | | | | | +------ BODLEVEL 0..2 (110 = 1.8 V)
# | | | | + --------- EESAVE (preserve EEPROM over chip erase)
# | | | +-------------- WDTON (if 0: watchdog always on)
# | | +---------------- SPIEN (allow serial programming)
# | +------------------ DWEN (debug wire enable)
# +-------------------- RSTDISBL (reset pin is enabled)
# Fuse low byte:
# 0xdf = 1 1 0 1 1 1 1 1
# ^ ^ \ / \--+--/
# | | | +------- CKSEL 3..0 (external >8M crystal)
# | | +--------------- SUT 1..0 (crystal osc, BOD enabled)
# | +------------------ CKOUT (if 0: Clock output enabled)
# +-------------------- CKDIV8 (if 0: divide by 8)
# Lock Bits
# 0x3f = - - 1 1 1 1 1 1
# \ / \-/ \-/
# | | +----- LB 2..1 (No memory lock features enabled)
# | +--------- BLB0 2..1 (No restrictions for SPM or LPM accessing the Application section)
# +--------------- BLB1 2..1 (No restrictions for SPM or LPM accessing the Boot Loader section)

62
doc/POWER.txt Normal file
View file

@ -0,0 +1,62 @@
Time to Sleep
=============
USB suspend no activity on USB line for 3ms
No Interaction no user interaction
matrix has no change
matrix has no switch on
AVR Power Management
====================
V-USB suspend
USB suspend
http://vusb.wikidot.com/examples
MCUSR MCU Status Register
WDRF Watchdog Reset Flag
BORF
EXTRF
PORF Power-on Reset Flag
SMCR Sleep Mode Control Register
SE Sleep Enable
SM2:0
#define set_sleep_mode(mode) \
#define SLEEP_MODE_IDLE (0)
#define SLEEP_MODE_ADC _BV(SM0)
#define SLEEP_MODE_PWR_DOWN _BV(SM1)
#define SLEEP_MODE_PWR_SAVE (_BV(SM0) | _BV(SM1))
#define SLEEP_MODE_STANDBY (_BV(SM1) | _BV(SM2))
#define SLEEP_MODE_EXT_STANDBY (_BV(SM0) | _BV(SM1) | _BV(SM2))
ACSR Analog Comparator Control and Status Register
To disable Analog Comparator
ACSR = 0x80;
or
ACSR &= ~_BV(ACIE);
ACSR |= _BV(ACD);
ACD: Analog Comparator Disable
When this bit is written logic one, the power to the Analog Comparator is
switched off. This bit can be set at any time to turn off the Analog
Comparator. This will reduce power consumption in Active and Idle mode.
When changing the ACD bit, the Analog Comparator Interrupt must be disabled
by clearing the ACIE bit in ACSR. Otherwise an interrupt can occur when
the bit is changed.
DIDR1 Digital Input Disable Register 1
AIN1D
AIN0D
When this bit is written logic one, the digital input buffer on the AIN1/0 pin is disabled. The corresponding PIN Register bit will always read as zero when this bit is set. When an analog signal is applied to the AIN1/0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer.
PRR Power Reduction Register
PRTWI
PRTIM2
PRTIM0
PRTIM1
PRSPI
PRUSART0
PRADC

160
doc/USB_NKRO.txt Normal file
View file

@ -0,0 +1,160 @@
USB NKRO MEMO
=============
2010/12/09
References
----------
USB - boot mode, NKRO, compatibility, etc...
http://geekhack.org/showthread.php?t=13162
NKey Rollover - Overview, Testing Methodology, and Results
http://geekhack.org/showwiki.php?title=NKey+Rollover+-+Overview+Testing+Methodology+and+Results
dfj's NKRO(2010/06)
http://geekhack.org/showpost.php?p=191195&postcount=251
http://geekhack.org/showthread.php?p=204389#post204389
Terminology
---------
NKRO
ghost
matrix
mechanical with diodes
membrane
OS Support Status
-----------------
USB NKRO is possible *without* a custom driver.
At least following OS's supports.
Windows7 64bit
WindowsXP
Windows2000 SP4
Ubuntu10.4(Linux 2.6)
MacOSX(To be tested)
Custom Driver for USB NKRO
--------------------------
NOT NEEDED
at least when using following report formats on Windows, Linux or MacOSX.
USB NKRO methods
----------------
1. Virtual keyboards
Keyboard can increase its KRO by using virtual keyboards with Standard or Extended report.
If the keyboard has 2 virtual keyboard with Standard report(6KRO), it gets 12KRO.
Using this method means the keyboard is a composite device.
2. Extended report
It needs large report size for this method to achieve NKRO.
If a keyboard has 101keys, it needs 103byte report. It seems to be inefficient.
3. Bitmap report
If the keyboard has less than 128keys, 16byte report will be enough for NKRO.
The 16byte report seems to be reasonable cost to get NKRO.
Report Format
-------------
Other report formats than followings are possible, though these format are typical one.
1. Standard 8bytes
modifiers(bitmap) 1byte
reserved 1byte(not used)
keys(array) 1byte*6
Standard report can send 6keys plus 8modifiers simultaneously.
Standard report is used by most keyboards in the marketplace.
Standard report is identical to boot protocol report.
Standard report is hard to suffer from compatibility problems.
2. Extended standard 16,32,64bytes
modifiers(bitmap) 1byte
reserved 1byte(not used)
keys(array) 1byte*(14,32,62)
Extended report can send N-keys by using N+2bytes.
Extended report is expected to be compatible with boot protocol.
3. Bitmap 16,32,64bytes
keys(bitmap) (16,32)bytes
Bitmap report can send at most 128keys by 16bytes and 256keys by 32bytes.
Bitmap report can achieve USB NKRO efficiently in terms of report size.
Bitmap report needs a deliberation for boot protocol implementation.
Bitmap report descriptor sample:
0x05, 0x01, // Usage Page (Generic Desktop),
0x09, 0x06, // Usage (Keyboard),
0xA1, 0x01, // Collection (Application),
// bitmap of modifiers
0x75, 0x01, // Report Size (1),
0x95, 0x08, // Report Count (8),
0x05, 0x07, // Usage Page (Key Codes),
0x19, 0xE0, // Usage Minimum (224),
0x29, 0xE7, // Usage Maximum (231),
0x15, 0x00, // Logical Minimum (0),
0x25, 0x01, // Logical Maximum (1),
0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte
// LED output report
0x95, 0x05, // Report Count (5),
0x75, 0x01, // Report Size (1),
0x05, 0x08, // Usage Page (LEDs),
0x19, 0x01, // Usage Minimum (1),
0x29, 0x05, // Usage Maximum (5),
0x91, 0x02, // Output (Data, Variable, Absolute),
0x95, 0x01, // Report Count (1),
0x75, 0x03, // Report Size (3),
0x91, 0x03, // Output (Constant),
// bitmap of keys
0x95, (REPORT_BYTES-1)*8, // Report Count (),
0x75, 0x01, // Report Size (1),
0x15, 0x00, // Logical Minimum (0),
0x25, 0x01, // Logical Maximum(1),
0x05, 0x07, // Usage Page (Key Codes),
0x19, 0x00, // Usage Minimum (0),
0x29, (REPORT_BYTES-1)*8-1, // Usage Maximum (),
0x81, 0x02, // Input (Data, Variable, Absolute),
0xc0 // End Collection
where REPORT_BYTES is a report size in bytes.
Considerations
--------------
Compatibility
boot protocol
minor/old system
Some BIOS doesn't send SET_PROTOCOL request, a keyboard can't switch to boot protocol mode.
This may cause a problem on a keyboard which uses other report than Standard.
Reactivity
USB polling time
OS/Driver processing time
Windows Problem
---------------
1. Windows accepts only 6keys in case of Standard report.
It should be able to send 6keys plus 8modifiers.
2. Windows accepts only 10keys in case of 16bytes Extended report.
It should be able to send 14keys plus 8modifiers.
3. Windows accepts only 18keys in case of 32bytes Extended report.
It should be able to send 30keys plus 8modifiers.
If keys are pressed in excess of the number, wrong keys are registered on Windows.
This problem will be reportedly fixed soon.(2010/12/05)
http://forums.anandtech.com/showpost.php?p=30873364&postcount=17
Tools for testing NKRO
----------------------
Browser App:
http://www.microsoft.com/appliedsciences/content/projects/KeyboardGhostingDemo.aspx
http://random.xem.us/rollover.html
Windows:
AquaKeyTest.exe http://geekhack.org/showthread.php?t=6643
Linux:
xkeycaps
xev
showkeys
EOF

186
doc/build.md Normal file
View file

@ -0,0 +1,186 @@
Build Firmware and Program Controller
=====================================
Download and Install
--------------------
### 1. Install Tools
1. **Toolchain** On Windows install [MHV AVR Tools][mhv] for AVR GCC compiler and [Cygwin][cygwin](or [MinGW][mingw]) for shell terminal. On Mac you can use [CrossPack][crosspack]. On Linux you can install AVR GCC with your favorite package manager.
2. **Programmer** On Windows install [Atmel FLIP][flip]. On Mac and Linux install [dfu-programmer][dfu-prog].
3. **Driver** On Windows you start DFU bootloader on the chip first time you will see 'Found New Hardware Wizard' to install driver. If you install device driver properly you can find chip name like 'ATmega32U4' under 'LibUSB-Win32 Devices' tree on 'Device Manager'. If not you shall need to update its driver on 'Device Manager'. You will find the driver in `FLIP` install directory like: C:\Program Files (x86)\Atmel\Flip 3.4.5\usb\. In case of `dfu-programmer` use its driver.
If you use PJRC Teensy you don't need step 2 and 3 above, just get [Teensy loader][teensy-loader].
### 2. Download source
You can find firmware source at github:
- <https://github.com/tmk/tmk_keyboard>
If you are familiar with `Git` tools you are recommended to use it but you can also download zip archive from:
- <https://github.com/tmk/tmk_keyboard/archive/master.zip>
Build firmware
--------------
### 1. Open terminal
Open terminal window to get access to commands. Use Cygwin(or MingGW) `shell terminal` in Windows or `Terminal.app` on Mac OSX. In Windows press `Windows` key and `R` then enter `cmd` in 'Run command' dialog showing up.
### 2. Change directory
Move to project directory in the firmware source.
cd tmk_keyboard/{'keyboard' or 'converter'}/<project>
### 3. Make
Build firmware using GNU `make` command. You'll see `<project>_<variant>.hex` file in that directory unless something unexpected occurs in build process.
make -f Makefile.<variant> clean
make -f Makefile.<variant>
Program Controller
------------------
Now you have **hex** file to program on current directory. This **hex** is only needed to program your controller, other files are used for development and you may leave and forget them.
### 1. Start bootloader
How to program controller depends on controller chip and its board design. To program AVR USB chips you'll need to start it up in bootloader mode. Most of boards with the chip have a push button to let bootloader come up. Consult with your controller board manual.
### 2. Program with DFU bootloader
Stock AVR USB chip including ATmega32U4 has DFU bootloader by factory default. `FLIP` is a DFU programmer on Windows offered by Atmel. Open source command line tool `dfu-programmer` also supports AVR chips, it runs on Linux, Mac OSX and even Windows.
To program AVR chip with DFU bootloader use `FLIP` or `dfu-programmer`.
If you have a proper program command in `Makefile` just type this.
`FLIP` has two version of tool, GUI app and command line program. If you want GUI see tutorial below.
To use command line tool run this command. Note that you need to set PATH variable properly.
$ make -f Makefile.<variant> flip
Or to program with `dfu-programmer` run:
$ make -f Makefile.<variant> dfu
#### FLIP GUI tutorial
1. On menu bar click Device -> Select, then. `ATmega32u4`.
2. On menu bar click Settings -> Communication -> USB, then click 'Open' button on 'USB Port Connection' dialog.
At this point you'll see grey-outed widgets on the app get colored and ready.
3. On menu bar click File -> Load HEX File, then select your firmware hex file on File Selector dialog.
4. On 'Operations Flow' panel click 'Run' button to load the firmware binary to the chip. Note that you should keep 'Erase', 'Blank Check', 'Program' and 'Verify' check boxes selected.
5. Re-plug USB cord or click 'Start Application' button to restart your controller.
Done.
See also these instructions if you need.
- <http://code.google.com/p/micropendous/wiki/LoadingFirmwareWithFLIP>
- <http://www.atmel.com/Images/doc7769.pdf>
### 3. Program with Teensy Loader
If you have PJRC Teensy see instruction of `Teensy Loader`.
- <http://www.pjrc.com/teensy/loader.html>
Or use this command if you have command line version of Teensy Loader installed.
$ make -f Makefile.<variant> teensy
### 4. Program with Other programmer
You may want to use other programmer like `avrdude` with AVRISPmkII, Arduino or USBasp. In that case you can still use make target `program` for build with configuring `PROGRAM_CMD` in Makefile.
$ make -f Makefile.<variant> program
[cygwin]: https://www.cygwin.com/
[mingw]: http://www.mingw.org/
[mhv]: https://infernoembedded.com/products/avr-tools
[winavr]: http://winavr.sourceforge.net/
[crosspack]: http://www.obdev.at/products/crosspack/index.html
[flip]: http://www.atmel.com/tools/FLIP.aspx
[dfu-prog]: http://dfu-programmer.sourceforge.net/
[teensy-loader]:http://www.pjrc.com/teensy/loader.html
Makefile Options
----------------
### 1. MCU and Frequency.
MCU = atmega32u4 # Teensy 2.0
#MCU = at90usb1286 # Teensy++ 2.0
F_CPU = 16000000
Set your MCU and its clock in Hz.
# Boot Section Size in *bytes*
# Teensy halfKay 512
# Atmel DFU loader 4096
# LUFA bootloader 4096
OPT_DEFS += -DBOOTLOADER_SIZE=4096
If you are using PJRC Teensy use `512` for `BOOTLOADER_SIZE`, otherwise use `4096` unless you are sure.
### 2. Features
Optional. Note that ***comment out*** with `#` to disable them.
BOOTMAGIC_ENABLE = yes # Virtual DIP switch configuration(+1000)
MOUSEKEY_ENABLE = yes # Mouse keys(+4700)
EXTRAKEY_ENABLE = yes # Audio control and System control(+450)
CONSOLE_ENABLE = yes # Console for debug(+400)
COMMAND_ENABLE = yes # Commands for debug and configuration
SLEEP_LED_ENABLE = yes # Breathing sleep LED during USB suspend
#NKRO_ENABLE = yes # USB Nkey Rollover - not yet supported in LUFA
#BACKLIGHT_ENABLE = yes # Enable keyboard backlight functionality
### 3. Programmer
Optional. Set proper command for your controller, bootloader and programmer. This command can be used with `make program`. Not needed if you use `FLIP`, `dfu-programmer` or `Teensy Loader`.
# avrdude with AVRISPmkII
PROGRAM_CMD = avrdude -p $(MCU) -c avrispmkII -P USB -U flash:w:$(TARGET).hex
# avrdude with USBaspLoader
PROGRAM_CMD = avrdude -p $(MCU) -c usbasp -U flash:w:$(TARGET).hex
# avrdude with arduino
PROGRAM_CMD = avrdude -p $(MCU) -c arduino -P COM1 -b 57600 -U flash:w:$(TARGET).hex
Config.h Options
----------------
### 1. Magic command key combination
#define IS_COMMAND() (keyboard_report->mods == (MOD_BIT(KB_LSHIFT) | MOD_BIT(KB_RSHIFT)))
### 2. Mechanical Locking Support for CapsLock
/* Mechanical locking CapsLock support. Use KC_LCAP instead of KC_CAPS in keymap */
#define CAPSLOCK_LOCKING_ENABLE
/* Locking CapsLock re-synchronize hack */
#define CAPSLOCK_LOCKING_RESYNC_ENABLE
### 3. Disable Debug and Print
/* disable debug print */
#define NO_DEBUG
/* disable print */
#define NO_PRINT
### 4. Disable Action Features
#define NO_ACTION_LAYER
#define NO_ACTION_TAPPING
#define NO_ACTION_ONESHOT
#define NO_ACTION_MACRO
#define NO_ACTION_FUNCTION
***TBD***

261
doc/keycode.txt Normal file
View file

@ -0,0 +1,261 @@
Keycode Symbol Table
====================
Keycodes are defined in `common/keycode.h`.
Range of 00-A4 and E0-E7 are identical with HID Usage:
<http://www.usb.org/developers/devclass_docs/Hut1_11.pdf>
Virtual keycodes are defined out of above range to support special actions.
Keycode Symbol Short name Description
--------------------------------------------------------------------------------
KC_NO 00 Reserved (no event indicated)
KC_ROLL_OVER 01 Keyboard ErrorRollOver
KC_POST_FAIL 02 Keyboard POSTFail
KC_UNDEFINED 03 Keyboard ErrorUndefined
KC_A 04 Keyboard a and A
KC_B 05 Keyboard b and B
KC_C 06 Keyboard c and C
KC_D 07 Keyboard d and D
KC_E 08 Keyboard e and E
KC_F 09 Keyboard f and F
KC_G 0A Keyboard g and G
KC_H 0B Keyboard h and H
KC_I 0C Keyboard i and I
KC_J 0D Keyboard j and J
KC_K 0E Keyboard k and K
KC_L 0F Keyboard l and L
KC_M 10 Keyboard m and M
KC_N 11 Keyboard n and N
KC_O 12 Keyboard o and O
KC_P 13 Keyboard p and P
KC_Q 14 Keyboard q and Q
KC_R 15 Keyboard r and R
KC_S 16 Keyboard s and S
KC_T 17 Keyboard t and T
KC_U 18 Keyboard u and U
KC_V 19 Keyboard v and V
KC_W 1A Keyboard w and W
KC_X 1B Keyboard x and X
KC_Y 1C Keyboard y and Y
KC_Z 1D Keyboard z and Z
KC_1 1E Keyboard 1 and !
KC_2 1F Keyboard 2 and @
KC_3 20 Keyboard 3 and #
KC_4 21 Keyboard 4 and $
KC_5 22 Keyboard 5 and %
KC_6 23 Keyboard 6 and ^
KC_7 24 Keyboard 7 and &
KC_8 25 Keyboard 8 and *
KC_9 26 Keyboard 9 and (
KC_0 27 Keyboard 0 and )
KC_ENTER KC_ENT 28 Keyboard Return (ENTER)
KC_ESCAPE KC_ESC 29 Keyboard ESCAPE
KC_BSPACE KC_BSPC 2A Keyboard DELETE (Backspace)
KC_TAB 2B Keyboard Tab
KC_SPACE KC_SPC 2C Keyboard Spacebar
KC_MINUS KC_MINS 2D Keyboard - and (underscore)
KC_EQUAL KC_EQL 2E Keyboard = and +
KC_LBRACKET KC_LBRC 2F Keyboard [ and {
KC_RBRACKET KC_RBRC 30 Keyboard ] and }
KC_BSLASH KC_BSLS 31 Keyboard \ and |
KC_NONUS_HASH KC_NUHS 32 Keyboard Non-US # and ~
KC_SCOLON KC_SCLN 33 Keyboard ; and :
KC_QUOTE KC_QUOT 34 Keyboard and “
KC_GRAVE KC_GRV 35 Keyboard Grave Accent and Tilde
KC_COMMA KC_COMM 36 Keyboard, and <
KC_DOT 37 Keyboard . and >
KC_SLASH KC_SLSH 38 Keyboard / and ?
KC_CAPSLOCK KC_CAPS 39 Keyboard Caps Lock
KC_F1 3A Keyboard F1
KC_F2 3B Keyboard F2
KC_F3 3C Keyboard F3
KC_F4 3D Keyboard F4
KC_F5 3E Keyboard F5
KC_F6 3F Keyboard F6
KC_F7 40 Keyboard F7
KC_F8 41 Keyboard F8
KC_F9 42 Keyboard F9
KC_F10 43 Keyboard F10
KC_F11 44 Keyboard F11
KC_F12 45 Keyboard F12
KC_PSCREEN KC_PSCR 46 Keyboard PrintScreen1
KC_SCKLOCK KC_SLCK 47 Keyboard Scroll Lock11
KC_PAUSE KC_PAUS 48 Keyboard Pause1
KC_INSERT KC_INS 49 Keyboard Insert1
KC_HOME 4A Keyboard Home1
KC_PGUP 4B Keyboard PageUp1
KC_DELETE KC_DELETE 4C Keyboard Delete Forward
KC_END 4D Keyboard End1
KC_PGDOWN KC_PGDN 4E Keyboard PageDown1
KC_RIGHT KC_RGHT 4F Keyboard RightArrow1
KC_LEFT 50 Keyboard LeftArrow1
KC_DOWN 51 Keyboard DownArrow1
KC_UP 52 Keyboard UpArrow1
KC_NUMLOCK KC_NLCK 53 Keypad Num Lock and Clear11
KC_KP_SLASH KC_PSLS 54 Keypad /1
KC_KP_ASTERISK KC_PAST 55 Keypad *
KC_KP_MINUS KC_PMNS 56 Keypad -
KC_KP_PLUS KC_PPLS 57 Keypad +
KC_KP_ENTER KC_PENT 58 Keypad ENTER5
KC_KP_1 KC_P1 59 Keypad 1 and End
KC_KP_2 KC_P2 5A Keypad 2 and Down Arrow
KC_KP_3 KC_P3 5B Keypad 3 and PageDn
KC_KP_4 KC_P4 5C Keypad 4 and Left Arrow
KC_KP_5 KC_P5 5D Keypad 5
KC_KP_6 KC_P6 5E Keypad 6 and Right Arrow
KC_KP_7 KC_P7 5F Keypad 7 and Home
KC_KP_8 KC_P8 60 Keypad 8 and Up Arrow
KC_KP_9 KC_P9 61 Keypad 9 and PageUp
KC_KP_0 KC_P0 62 Keypad 0 and Insert
KC_KP_DOT KC_PDOT 63 Keypad . and Delete
KC_NONUS_BSLASH KC_NUBS 64 Keyboard Non-US \ and |
KC_APPLICATION KC_APP 65 Keyboard Application10
KC_POWER 66 Keyboard Power9
KC_KP_EQUAL KC_PEQL 67 Keypad =
KC_F13 68 Keyboard F13
KC_F14 69 Keyboard F14
KC_F15 6A Keyboard F15
KC_F16 6B Keyboard F16
KC_F17 6C Keyboard F17
KC_F18 6D Keyboard F18
KC_F19 6E Keyboard F19
KC_F20 6F Keyboard F20
KC_F21 70 Keyboard F21
KC_F22 71 Keyboard F22
KC_F23 72 Keyboard F23
KC_F24 73 Keyboard F24
KC_EXECUTE 74 Keyboard Execute
KC_HELP 75 Keyboard Help
KC_MENU 76 Keyboard Menu
KC_SELECT 77 Keyboard Select
KC_STOP 78 Keyboard Stop
KC_AGAIN 79 Keyboard Again
KC_UNDO 7A Keyboard Undo
KC_CUT 7B Keyboard Cut
KC_COPY 7C Keyboard Copy
KC_PASTE 7D Keyboard Paste
KC_FIND 7E Keyboard Find
KC__MUTE 7F Keyboard Mute
KC__VOLUP 80 Keyboard Volume Up
KC__VOLDOWN 81 Keyboard Volume Down
KC_LOCKING_CAPS 82 Keyboard Locking Caps Lock12
KC_LOCKING_NUM 83 Keyboard Locking Num Lock12
KC_LOCKING_SCROLL 84 Keyboard Locking Scroll Lock12
KC_KP_COMMA KC_PCMM 85 Keypad Comma27
KC_KP_EQUAL_AS400 86 Keypad Equal Sign29
KC_INT1 KC_RO 87 Keyboard International115,28
KC_INT2 KC_KANA 88 Keyboard International216
KC_INT3 KC_JYEN 89 Keyboard International317
KC_INT4 KC_HENK 8A Keyboard International418
KC_INT5 KC_MHEN 8B Keyboard International519
KC_INT6 8C Keyboard International620
KC_INT7 8D Keyboard International721
KC_INT8 8E Keyboard International822
KC_INT9 8F Keyboard International922
KC_LANG1 90 Keyboard LANG125
KC_LANG2 91 Keyboard LANG226
KC_LANG3 92 Keyboard LANG330
KC_LANG4 93 Keyboard LANG431
KC_LANG5 94 Keyboard LANG532
KC_LANG6 95 Keyboard LANG68
KC_LANG7 96 Keyboard LANG78
KC_LANG8 97 Keyboard LANG88
KC_LANG9 98 Keyboard LANG98
KC_ALT_ERASE 99 Keyboard Alternate Erase7
KC_SYSREQ 9A Keyboard SysReq/Attention1
KC_CANCEL 9B Keyboard Cancel
KC_CLEAR 9C Keyboard Clear
KC_PRIOR 9D Keyboard Prior
KC_RETURN 9E Keyboard Return
KC_SEPARATOR 9F Keyboard Separator
KC_OUT A0 Keyboard Out
KC_OPER A1 Keyboard Oper
KC_CLEAR_AGAIN A2 Keyboard Clear/Again
KC_CRSEL A3 Keyboard CrSel/Props
KC_EXSEL A4 Keyboard ExSel
/* Modifiers */
KC_LCTRL KC_LCTRL E0 Keyboard LeftControl
KC_LSHIFT KC_LSFT E1 Keyboard LeftShift
KC_LALT E2 Keyboard LeftAlt
KC_LGUI E3 Keyboard Left GUI(Windows/Apple/Meta key)
KC_RCTRL KC_RCTL E4 Keyboard RightControl
KC_RSHIFT KC_RSFT E5 Keyboard RightShift
KC_RALT E6 Keyboard RightAlt
KC_RGUI E7 Keyboard Right GUI(Windows/Apple/Meta key)
/*
* Virtual keycodes
*/
/* System Control */
KC_SYSTEM_POWER KC_PWR System Power Down
KC_SYSTEM_SLEEP KC_SLEP System Sleep
KC_SYSTEM_WAKE KC_WAKE System Wake
/* Consumer Page */
KC_AUDIO_MUTE KC_MUTE
KC_AUDIO_VOL_UP KC_VOLU
KC_AUDIO_VOL_DOWN KC_VOLD
KC_MEDIA_NEXT_TRACK KC_MNXT
KC_MEDIA_PREV_TRACK KC_MPRV
KC_MEDIA_STOP KC_MSTP
KC_MEDIA_PLAY_PAUSE KC_MPLY
KC_MEDIA_SELECT KC_MSEL
KC_MAIL KC_MAIL
KC_CALCULATOR KC_CALC
KC_MY_COMPUTER KC_MYCM
KC_WWW_SEARCH KC_WSCH
KC_WWW_HOME KC_WHOM
KC_WWW_BACK KC_WBAK
KC_WWW_FORWARD KC_WFWD
KC_WWW_STOP KC_WSTP
KC_WWW_REFRESH KC_WREF
KC_WWW_FAVORITES KC_WFAV
/* Mousekey */
KC_MS_UP KC_MS_U Mouse Cursor Up
KC_MS_DOWN KC_MS_D Mouse Cursor Down
KC_MS_LEFT KC_MS_L Mouse Cursor Left
KC_MS_RIGHT KC_MS_R Mouse Cursor Right
KC_MS_BTN1 KC_BTN1 Mouse Button 1
KC_MS_BTN2 KC_BTN2 Mouse Button 2
KC_MS_BTN3 KC_BTN3 Mouse Button 3
KC_MS_BTN4 KC_BTN4 Mouse Button 4
KC_MS_BTN5 KC_BTN5 Mouse Button 5
KC_MS_WH_UP KC_WH_U Mouse Wheel Up
KC_MS_WH_DOWN KC_WH_D Mouse Wheel Down
KC_MS_WH_LEFT KC_WH_L Mouse Wheel Left
KC_MS_WH_RIGHT KC_WH_R Mouse Wheel Right
KC_MS_ACCEL0 KC_ACL0 Mouse Acceleration 0
KC_MS_ACCEL1 KC_ACL1 Mouse Acceleration 1
KC_MS_ACCEL2 KC_ACL2 Mouse Acceleration 2
/* Fn key */
KC_FN0
KC_FN1
KC_FN2
KC_FN3
KC_FN4
KC_FN5
KC_FN6
KC_FN7
KC_FN8
KC_FN9
KC_FN10
KC_FN11
KC_FN12
KC_FN13
KC_FN14
KC_FN15
KC_FN16
KC_FN17
KC_FN18
KC_FN19
KC_FN20
KC_FN21
KC_FN22
KC_FN23
KC_FN24
KC_FN25
KC_FN26
KC_FN27
KC_FN28
KC_FN29
KC_FN30
KC_FN31

593
doc/keymap.md Normal file
View file

@ -0,0 +1,593 @@
Keymap framework - how to define your keymap
============================================
***NOTE: This is not final version, may be inconsistent with source code and changed occasionally for a while.***
## 0. Keymap and layers
**Keymap** is comprised of multiple layers of key layout, you can define **32 layers** at most.
**Layer** is an array of **keycodes** to define **actions** for each physical keys.
respective layers can be validated simultaneously. Layers are indexed with 0 to 31 and higher layer has precedence.
Keymap: 32 Layers Layer: Keycode matrix
----------------- ---------------------
stack of layers array_of_keycode[row][column]
____________ precedence _______________________
/ / | high / ESC / F1 / F2 / F3 ....
31 /___________// | /-----/-----/-----/-----
30 /___________// | / TAB / Q / W / E ....
29 /___________/ | /-----/-----/-----/-----
: _:_:_:_:_:__ | : /LCtrl/ A / S / D ....
: / : : : : : / | : / : : : :
2 /___________// | 2 `--------------------------
1 /___________// | 1 `--------------------------
0 /___________/ V low 0 `--------------------------
### 0.1 Keymap status
Keymap has its state in two parameters:
**`default_layer`** indicates a base keymap layer(0-31) which is always valid and to be referred, **`keymap_stat`** is 16bit variable which has current on/off status of layers on its each bit.
Keymap layer '0' is usually `default_layer` and which is the only valid layer and other layers is initially off after boot up firmware, though, you can configured them in `config.h`.
To change `default_layer` will be useful when you switch key layout completely, say you want Colmak instead of Qwerty.
Initial state of Keymap Change base layout
----------------------- ------------------
31 31
30 30
29 29
: :
: : ____________
2 ____________ 2 / /
1 / / ,->1 /___________/
,->0 /___________/ | 0
| |
`--- default_layer = 0 `--- default_layer = 1
layer_state = 0x00000001 layer_state = 0x00000002
On the other hand, you shall change `layer_state` to overlay base layer with some layers for feature such as navigation keys, function key(F1-F12), media keys or special actions.
Overlay feature layer
--------------------- bit|status
____________ ---+------
31 / / 31 | 0
30 /___________// -----> 30 | 1
29 /___________/ -----> 29 | 1
: : | :
: ____________ : | :
2 / / 2 | 0
,->1 /___________/ -----> 1 | 1
| 0 0 | 0
| +
`--- default_layer = 1 |
layer_state = 0x60000002 <-'
### 0.2 Layer Precedence and Transparency
Note that ***higher layer has higher priority on stack of layers***, namely firmware falls down from top layer to bottom to look up keycode. Once it spots keycode other than **`KC_TRNS`**(transparent) on a layer it stops searching and lower layers aren't referred.
You can place `KC_TRNS` on overlay layer changes just part of layout to fall back on lower or base layer.
Key with `KC_TRANS` doesn't has its own keycode and refers to lower valid layers for keycode, instead.
See example below.
### 0.3 Keymap Example
Keymap is **`keymaps[]`** C array in fact and you can define layers in it with **`KEYMAP()`** C macro and keycodes. To use complex actions you need to define `Fn` keycode in **`fn_actions[]`** array.
This is a keymap example for [HHKB](http://en.wikipedia.org/wiki/Happy_Hacking_Keyboard) keyboard.
This example has three layers, 'Qwerty' as base layer, 'Cursor' and 'Mousekey'.
In this example,
`Fn0` is a **momentary layer switching** key, you can use keys on Cursor layer while holding the key.
`Fn1` is a momentary layer switching key with tapping feature, you can get semicolon **';'** with taping the key and switch layers while holding the key. The word **'tap'** or **'tapping'** mean to press and release a key quickly.
`Fn2` is a **toggle layer switch** key, you can stay switched layer after releasing the key unlike momentary switching.
You can find other keymap definitions in file `keymap.c` located on project directories.
static const uint8_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
/* 0: Qwerty
* ,-----------------------------------------------------------.
* |Esc| 1| 2| 3| 4| 5| 6| 7| 8| 9| 0| -| =| \| `|
* |-----------------------------------------------------------|
* |Tab | Q| W| E| R| T| Y| U| I| O| P| [| ]|Backs|
* |-----------------------------------------------------------|
* |Contro| A| S| D| F| G| H| J| K| L|Fn1| '|Enter |
* |-----------------------------------------------------------|
* |Shift | Z| X| C| V| B| N| M| ,| .| /|Shift |Fn0|
* `-----------------------------------------------------------'
* |Gui|Alt |Space |Alt |Fn2|
* `-------------------------------------------'
*/
KEYMAP(ESC, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, MINS,EQL, BSLS,GRV, \
TAB, Q, W, E, R, T, Y, U, I, O, P, LBRC,RBRC,BSPC, \
LCTL,A, S, D, F, G, H, J, K, L, FN1, QUOT,ENT, \
LSFT,Z, X, C, V, B, N, M, COMM,DOT, SLSH,RSFT,FN0, \
LGUI,LALT, SPC, RALT,FN2),
/* 1: Cursor(HHKB mode)
* ,-----------------------------------------------------------.
* |Pwr| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Caps | | | | | | | |Psc|Slk|Pus|Up | |Backs|
* |-----------------------------------------------------------|
* |Contro|VoD|VoU|Mut| | | *| /|Hom|PgU|Lef|Rig|Enter |
* |-----------------------------------------------------------|
* |Shift | | | | | | +| -|End|PgD|Dow|Shift | |
* `-----------------------------------------------------------'
* |Gui |Alt |Space |Alt |Gui|
* `--------------------------------------------'
*/
KEYMAP(PWR, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, INS, DEL, \
CAPS,TRNS,TRNS,TRNS,TRNS,TRNS,TRNS,TRNS,PSCR,SLCK,PAUS,UP, TRNS,BSPC, \
LCTL,VOLD,VOLU,MUTE,TRNS,TRNS,PAST,PSLS,HOME,PGUP,LEFT,RGHT,ENT, \
LSFT,TRNS,TRNS,TRNS,TRNS,TRNS,PPLS,PMNS,END, PGDN,DOWN,RSFT,TRNS, \
LGUI,LALT, SPC, RALT,RGUI),
/* 2: Mousekey
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Tab | | | | | |MwL|MwD|MwU|MwR| | | |Backs|
* |-----------------------------------------------------------|
* |Contro| | | | | |McL|McD|McU|McR| | |Return |
* |-----------------------------------------------------------|
* |Shift | | | | |Mb3|Mb2|Mb1|Mb4|Mb5| |Shift | |
* `-----------------------------------------------------------'
* |Gui |Alt |Mb1 |Alt | |
* `--------------------------------------------'
* Mc: Mouse Cursor / Mb: Mouse Button / Mw: Mouse Wheel
*/
KEYMAP(ESC, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, INS, DEL, \
TAB, TRNS,TRNS,TRNS,TRNS,TRNS,WH_L,WH_D,WH_U,WH_R,TRNS,TRNS,TRNS,BSPC, \
LCTL,TRNS,ACL0,ACL1,ACL2,TRNS,MS_L,MS_D,MS_U,MS_R,TRNS,QUOT,ENT, \
LSFT,TRNS,TRNS,TRNS,TRNS,BTN3,BTN2,BTN1,BTN4,BTN5,SLSH,RSFT,TRNS, \
LGUI,LALT, BTN1, RALT,TRNS),
};
static const uint16_t PROGMEM fn_actions[] = {
ACTION_LAYER_MOMENTARY(1), // FN0
ACTION_LAYER_TAP_KEY(2, KC_SCLN), // FN1
ACTION_LAYER_TOGGLE(2), // FN2
};
## 1. Keycode
See [`common/keycode.h`](../common/keycode.h) or keycode table below for the detail. Keycode is internal **8bit code** to indicate action performed on key in keymap. Keycode has `KC_` prefixed symbol respectively. Most of keycodes like `KC_A` have simple action registers key to host on press and unregister on release, while some of other keycodes has some special actions like `Fn` keys, Media control keys, System control keys and Mousekeys.
***In `KEYMAP()` macro you should omit prefix part `KC_` of keycode to keep keymap compact.*** For example, just use `A` instead you place `KC_A` in `KEYMAP()`. Some keycodes has 4-letter **short name** in addition to descriptive name, you'll prefer short one in `KEYMAP()`.
### 1.0 Other key
- `KC_NO` for no action
- `KC_TRNS` for layer transparency (See above)
### 1.1 Normal key
- `KC_A` to `KC_Z`, `KC_1` to `KC_0` for alpha numeric key
- `KC_MINS`, `KC_EQL`, `KC_GRV`, `KC_RBRC`, `KC_LBRC`, `KC_COMM`, `KC_DOT`, `KC_BSLS`, `KC_SLSH`, `KC_SCLN`, `KC_QUOT`
- `KC_ESC`, `KC_TAB`, `KC_SPC`, `KC_BSPC`, `KC_ENT`, `KC_DEL`, `KC_INS`
- `KC_UP`, `KC_DOWN`, `KC_RGHT`, `KC_LEFT`, `KC_PGUP`, `KC_PGDN`, `KC_HOME`, `KC_END`
- `KC_CAPS`, `KC_NLCK`, `KC_SLCK`, `KC_PSCR`, `KC_PAUS`, `KC_APP`, `KC_F1` to `KC_F24`
- `KC_P1` to `KC_P0`, `KC_PDOT`, `KC_PCMM`, `KC_PSLS`, `KC_PAST`, `KC_PMNS`, `KC_PPLS`, `KC_PEQL`, `KC_PENT` for keypad.
### 1.2 Modifier
There are 8 modifiers which has discrimination between left and right.
- `KC_LCTL` and `KC_RCTL` for Control
- `KC_LSFT` and `KC_RSFT` for Shift
- `KC_LALT` and `KC_RALT` for Alt
- `KC_LGUI` and `KC_RGUI` for Windows key or Command key in Mac
### 1.3 Mousekey
- `KC_MS_U`, `KC_MS_D`, `KC_MS_L`, `KC_MS_R` for mouse cursor
- `KC_WH_U`, `KC_WH_D`, `KC_WH_L`, `KC_WH_R` for mouse wheel
- `KC_BTN1`, `KC_BTN2`, `KC_BTN3`, `KC_BTN4`, `KC_BTN5` for mouse buttons
### 1.4 System & Media key
- `KC_PWR`, `KC_SLEP`, `KC_WAKE` for Power, Sleep, Wake
- `KC_MUTE`, `KC_VOLU`, `KC_VOLD` for audio volume control
- `KC_MNXT`, `KC_MPRV`, `KC_MSTP`, `KC_MPLY`, `KC_MSEL` for media control
- `KC_MAIL`, `KC_CALC`, `KC_MYCM` for application launch
- `KC_WSCH`, `KC_WHOM`, `KC_WBAK`, `KC_WFWD`, `KC_WSTP`, `KC_WREF`, `KC_WFAV` for web browser operation
### 1.5 Fn key
`KC_FNnn` are keycodes for `Fn` key which not given any actions at the beginning unlike most of keycodes has its own inborn action. To use these keycodes in `KEYMAP()` you need to assign action you want at first. Action of `Fn` key is defined in `fn_actions[]` and its index of the array is identical with number part of `KC_FNnn`. Thus `KC_FN0` keycode indicates the action defined in first element of the array. ***32 `Fn` keys can be defined at most.***
### 1.6 Keycode Table
See keycode table in [`doc/keycode.txt`](./keycode.txt) for description of keycodes.
In regard to implementation side most of keycodes are identical with [HID usage][HID_usage](pdf) sent to host for real and some virtual keycodes are defined to support special actions.
[HID_usage]: http://www.usb.org/developers/devclass_docs/Hut1_11.pdf
## 2. Action
See [`common/action_code.h`](../common/action_code.h). Action is a **16bit code** and defines function to perform on events of a key like press, release, holding and tapping.
Most of keys just register 8bit scancode to host, but to support other complex features needs 16bit extended action codes internally. However, using 16bit action codes in keymap results in double size in memory compared to using just keycodes. To avoid this waste 8bit keycodes are used in `KEYMAP()` instead of action codes.
***You can just use keycodes of `Normal key`, `Modifier`, `Mousekey` and `System & Media key` in keymap*** to indicate corresponding actions instead of using action codes. While ***to use other special actions you should use keycode of `Fn` key defined in `fn_actions[]`.***
### 2.1 Key Action
This is a simple action that registers scancodes(HID usage in fact) to host on press event of key and unregister on release.
#### Parameters
+ **mods**: { ` MOD_LCTL`, ` MOD_LSFT`, ` MOD_LALT`, ` MOD_LGUI`,
` MOD_RCTL`, ` MOD_RSFT`, ` MOD_RALT`, ` MOD_RGUI` }
+ **key**: keycode
#### 2.1.1 Normal key and Modifier
***This action usually won't be used expressly in keymap*** because you can just use keycodes in `KEYMAP()` instead.
You can define these actions on *'A'* key and *'left shift'* modifier with:
ACTION_KEY(KC_A)
ACTION_KEY(KC_LSFT)
#### 2.1.2 Modified key
This action is comprised of strokes of modifiers and a key. `Macro` action is needed if you want more complex key strokes.
Say you want to assign a key to `Shift + 1` to get character *'!'* or `Alt + Tab` to switch application windows.
ACTION_MODS_KEY(MOD_LSFT, KC_1)
ACTION_MODS_KEY(MOD_LALT, KC_TAB)
Or `Alt,Shift + Tab` can be defined. `ACTION_MODS_KEY(mods, key)` requires **4-bit modifier state** and a **keycode** as arguments. See `keycode.h` for `MOD_BIT()` macro.
ACTION_MODS_KEY(MOD_LALT | MOD_LSFT, KC_TAB)
#### 2.1.3 Multiple Modifiers
Registers multiple modifiers with pressing a key. To specify multiple modifiers use `|`.
ACTION_MODS(MOD_ALT | MOD_LSFT)
#### 2.1.3 Modifier with Tap key([Dual role][dual_role])
Works as a modifier key while holding, but registers a key on tap(press and release quickly).
ACTION_MODS_TAP_KEY(MOD_RCTL, KC_ENT)
### 2.2 Layer Action
These actions operate layers of keymap.
#### Parameters
You can specify a **target layer** of action and **when the action is executed**. Some actions take a **bit value** for bitwise operation.
+ **layer**: `0`-`31`
+ **on**: { `ON_PRESS` | `ON_RELEASE` | `ON_BOTH` }
+ **bits**: 4-bit value and 1-bit mask bit
#### 2.2.1 Default Layer
Default Layer is a layer which always is valid and referred to when actions is not defined on other overlay layers.
This sets Default Layer to given parameter `layer` and activate it.
ACTION_DEFAULT_LAYER_SET(layer)
#### 2.2.2 Momentary
Turns on `layer` momentarily while holding, in other words it activates when key is pressed and deactivate when released.
ACTION_LAYER_MOMENTARY(layer)
#### 2.2.3 Toggle Switch
Turns on `layer` with first type(press and release) and turns off with next.
ACTION_LAYER_TOGGLE(layer)
#### 2.2.4 Momentary Switch with tap key
Turns on `layer` momentary while holding, but registers key on tap(press and release quickly).
ACTION_LAYER_TAP_KEY(layer, key)
#### 2.2.5 Momentary Switch with tap toggle
Turns on `layer` momentary while holding and toggles it with serial taps.
ACTION_LAYER_TAP_TOGGLE(layer)
#### 2.2.6 Invert state of layer
Inverts current state of `layer`. If the layer is on it becomes off with this action.
ACTION_LAYER_INVERT(layer, on)
#### 2.2.7 Turn On layer
Turns on layer state.
ACTION_LAYER_ON(layer, on)
Turns on layer state on press and turns off on release.
ACTION_LAYER_ON_OFF(layer)
#### 2.2.8 Turn Off layer
Turns off layer state.
ACTION_LAYER_OFF(layer, on)
Turns off layer state on press and activates on release.
ACTION_LAYER_OFF_ON(layer)
#### 2.2.9 Set layer
Turn on layer only.
`layer_state = (1<<layer) [layer: 0-31]`
ACTION_LAYER_SET(layer, on)
Turns on layer only and clear all layer on release..
ACTION_LAYER_SET_CLEAR(layer)
#### 2.2.10 Bitwise operation
**part** indicates which part of 32bit layer state(0-7). **bits** is 5-bit value. **on** indicates when the action is executed.
ACTION_LAYER_BIT_AND(part, bits, on)
ACTION_LAYER_BIT_OR(part, bits, on)
ACTION_LAYER_BIT_XOR(part, bits, on)
ACTION_LAYER_BIT_SET(part, bits, on)
These actions works with parameters as following code.
uint8_t shift = part*4;
uint32_t mask = (bits&0x10) ? ~(0xf<<shift) : 0;
uint32_t layer_state = layer_state <bitop> ((bits<<shift)|mask);
Default Layer also has bitwise operations, they are executed when key is released.
ACTION_DEFAULT_LAYER_BIT_AND(part, bits)
ACTION_DEFAULT_LAYER_BIT_OR(part, bits)
ACTION_DEFAULT_LAYER_BIT_XOR(part, bits)
ACTION_DEFAULT_LAYER_BIT_SET(part, bits)
### 2.3 Macro action
***TBD***
`Macro` action indicates complex key strokes.
MACRO( D(LSHIFT), D(D), END )
MACRO( U(D), U(LSHIFT), END )
MACRO( I(255), T(H), T(E), T(L), T(L), W(255), T(O), END )
#### 2.3.1 Macro Commands
- **I()** change interval of stroke.
- **D()** press key
- **U()** release key
- **T()** type key(press and release)
- **W()** wait
- **END** end mark
#### 2.3.2 Examples
***TODO: sample implementation***
See `keyboard/hhkb/keymap.c` for sample.
### 2.4 Function action
***TBD***
There are two type of action, normal `Function` and tappable `Function`.
These actions call user defined function with `id`, `opt`, and key event information as arguments.
#### 2.4.1 Function
To define normal `Function` action in keymap use this.
ACTION_FUNCTION(id, opt)
#### 2.4.2 Function with tap
To define tappable `Function` action in keymap use this.
ACTION_FUNCTION_TAP(id, opt)
#### 2.4.3 Implement user function
`Function` actions can be defined freely with C by user in callback function:
void keymap_call_function(keyrecord_t *event, uint8_t id, uint8_t opt)
This C function is called every time key is operated, argument `id` selects action to be performed and `opt` can be used for option. Function `id` can be 0-255 and `opt` can be 0-15.
`keyrecord_t` is comprised of key event and tap count. `keyevent_t` indicates which and when key is pressed or released. From `tap_count` you can know tap state, 0 means no tap. These information will be used in user function to decide how action of key is performed.
typedef struct {
keyevent_t event;
uint8_t tap_count;
} keyrecord_t;
typedef struct {
key_t key;
bool pressed;
uint16_t time;
} keyevent_t;
typedef struct {
uint8_t col;
uint8_t row;
} key_t;
***TODO: sample implementation***
See `keyboard/hhkb/keymap.c` for sample.
### 2.5 Backlight Action
These actions control the backlight.
#### 2.5.1 Change backlight level
Increase backlight level.
ACTION_BACKLIGHT_INCREASE()
Decrease backlight level.
ACTION_BACKLIGHT_DECREASE()
Step through backlight levels.
ACTION_BACKLIGHT_STEP()
Turn a specific backlight level on or off.
ACTION_BACKLIGHT_LEVEL(1)
#### 2.5.2 Turn on / off backlight
Turn the backlight on and off without changing level.
ACTION_BACKLIGHT_TOGGLE()
## 3. Layer switching Example
There are some ways to switch layer with 'Layer' actions.
### 3.1 Momentary switching
Momentary switching changes layer only while holding Fn key.
This action makes 'Layer 1' active(valid) on key press event and inactive on release event. Namely you can overlay a layer on lower layers or default layer temporarily with this action.
ACTION_LAYER_MOMENTARY(1)
Note that after switching on press the actions on destination layer(Layer 1) are performed.
***Thus you shall need to place an action to go back on destination layer***, or you will be stuck in destination layer without way to get back. Usually you need to place same action or 'KC_TRNS` on destination layer to get back.
### 3.2 Toggle switching
Toggle switching performed after releasing a key. With this action you can keep staying on the destination layer until you type the key again to return.
This performs toggle switching action of 'Layer 2'.
ACTION_LAYER_TOGGLE(2)
### 3.3 Momentary switching with Tap key
These actions switch a layer only while holding a key but register the key on tap. **Tap** means to press and release a key quickly.
ACTION_LAYER_TAP_KEY(2, KC_SCLN)
With this you can place a layer switching action on normal key like ';' without losing its original key register function. This action allows you to have layer switching action without necessity of a dedicated key. It means you can have it even on home row of keyboard.
### 3.4 Momentary switching with Tap Toggle
This switches layer only while holding a key but toggle layer with several taps. **Tap** means to press and release key quickly.
ACTION_LAYER_TAP_TOGGLE(1)
Number of taps can be configured with `TAPPING_TOGGLE` in `config.h`, `5` by default.
### 3.5 Momentary switching with Modifiers
This registers modifier key(s) simultaneously with layer switching.
ACTION_LAYER_MODS(2, MOD_LSFT | MOD_LALT)
## 4. Tapping
Tapping is to press and release a key quickly. Tapping speed is determined with setting of `TAPPING_TERM`, which can be defined in `config.h`, 200ms by default.
### 4.1 Tap Key
This is a feature to assign normal key action and modifier including layer switching to just same one physical key. This is a kind of [Dual role key][dual_role]. It works as modifier when holding the key but registers normal key when tapping.
Modifier with tap key:
ACTION_MODS_TAP_KEY(MOD_RSFT, KC_GRV)
Layer switching with tap key:
ACTION_LAYER_TAP_KEY(2, KC_SCLN)
[dual_role]: http://en.wikipedia.org/wiki/Modifier_key#Dual-role_keys
### 4.2 Tap Toggle
This is a feature to assign both toggle layer and momentary switch layer action to just same one physical key. It works as momentary layer switch when holding a key but toggle switch with several taps.
ACTION_LAYER_TAP_TOGGLE(1)
### 4.3 Oneshot Modifier
This runs onetime effects which modify only on just one following key. It works as normal modifier key when holding down while oneshot modifier when tapping.
ACTION_MODS_ONESHOT(MOD_LSFT)
Say you want to type 'The', you have to push and hold Shift key before type 't' then release it before type 'h' and 'e', otherwise you'll get 'THe' or 'the' unintentionally. With Oneshot Modifier you can tap Shift then type 't', 'h' and 'e' normally, you don't need to holding Shift key properly here. This mean you can release Shift before 't' is pressed down.
Oneshot effect is cancel unless following key is pressed down within `ONESHOT_TIMEOUT` of `config.h`. No timeout when it is `0` or not defined.
### 4.4 Tap Toggle Mods
Similar to layer tap toggle, this works as a momentary modifier when holding, but toggles on with several taps. A single tap will 'unstick' the modifier again.
ACTION_MODS_TAP_TOGGLE(MOD_LSFT)
## 5. Legacy Keymap
This was used in prior version and still works due to legacy support code in `common/keymap.c`. Legacy keymap doesn't support many of features that new keymap offers. ***It is not recommended to use Legacy Keymap for new project.***
To enable Legacy Keymap support define this macro in `config.h`.
#define USE_LEGACY_KEYMAP
Legacy Keymap uses two arrays `fn_layer[]` and `fn_keycode[]` to define Fn key. The index of arrays corresponds with postfix number of `Fn` key. Array `fn_layer[]` indicates destination layer to switch and `fn_keycode[]` has keycodes to send when tapping `Fn` key.
In following setting example, `Fn0`, `Fn1` and `Fn2` switch layer to 1, 2 and 2 respectively. `Fn2` registers `Space` key when tapping while `Fn0` and `Fn1` doesn't send any key.
static const uint8_t PROGMEM fn_layer[] = {
1, // Fn0
2, // Fn1
2, // Fn2
};
static const uint8_t PROGMEM fn_keycode[] = {
KC_NO, // Fn0
KC_NO, // Fn1
KC_SPC, // Fn2
};
## 6. Terminology
***TBD***
### keymap
is comprised of multiple layers.
### layer
is matrix of keycodes.
### key
is physical button on keyboard or logical switch on software.
### keycode
is codes used on firmware.
### action
is a function assigned on a key.
### layer transparency
Using transparent keycode one layer can refer key definition on other lower layer.
### layer precedence
Top layer has higher precedence than lower layers.
### tapping
is to press and release a key quickly.
### Fn key
is key which executes a special action like layer switching, mouse key, macro or etc.
### dual role key
<http://en.wikipedia.org/wiki/Modifier_key#Dual-role_keys>

62
doc/other_projects.md Normal file
View file

@ -0,0 +1,62 @@
Other Keyboard Firmware Projects
================================
## PJRC USB Keyboard/Mouse Example[USB][PJRC][Teensy][AVR]
- <http://www.pjrc.com/teensy/usb_keyboard.html>
- <http://www.pjrc.com/teensy/usb_mouse.html>
## kbupgrade[USB][V-USB][AVR]
- <http://github.com/rhomann/kbupgrade>
- <http://geekhack.org/showwiki.php?title=Island:8406>
## c64key[USB][V-USB][AVR]
- <http://symlink.dk/projects/c64key/>
## rump[USB][V-USB][AVR]
- <http://mg8.org/rump/>
- <http://github.com/clee/rump>
## dulcimer[USB][V-USB][AVR]
- <http://www.schatenseite.de/dulcimer.html>
## humblehacker-keyboard[USB][LUFA][AVR][Ergo]
- <http://github.com/humblehacker>
- <http://www.humblehacker.com/keyboard/>
- <http://geekhack.org/showwiki.php?title=Island:6292>
## ps2avr[PS/2][AVR]
- <http://sourceforge.net/projects/ps2avr/>
## ErgoDox[Ergo][Split][USB][AVR]
- <http://geekhack.org/index.php?topic=22780.0>
- <https://github.com/benblazak/ergodox-firmware>
- <https://github.com/cub-uanic/tmk_keyboard>
## Suka's keyboard collection[Ergo][Split][3DPrinting][USB][AVR]
- <http://deskthority.net/workshop-f7/my-diy-keyboard-collection-or-how-i-became-a-kb-geek-t2534.html>
- <https://github.com/frobiac/adnw>
## bpiphany's AVR-Keyboard[PJRC][AVR][USB]
- <https://github.com/BathroomEpiphanies/AVR-Keyboard>
- <http://deskthority.net/wiki/HID_Liberation_Device_-_DIY_Instructions>
- <http://deskthority.net/wiki/Phantom>
## USB-USB keyboard remapper[converter][USB-USB][AVR][Arduino]
- <http://forum.colemak.com/viewtopic.php?pid=10837>
- <https://github.com/darkytoothpaste/keymapper>
## USB-USB converter threads[converter][USB-USB]
- <http://deskthority.net/workshop-f7/is-remapping-a-usb-keyboard-using-teensy-possible-t2841-30.html>
- <http://geekhack.org/index.php?topic=19458.0>
## kbdbabel.org[converter][vintage][protocol][8051]
Great resource of vintage keyboard protocol information and code
- <http://www.kbdbabel.org/>
## Haata's kiibohd Controller[converter][vintage][protocol][AVR][PJRC][Cortex]
A lots of vintage keyboard protocol supports
- <http://gitorious.org/kiibohd-controller>
## Kinesis ergonomic keyboard firmware replacement[V-USB][LUFA][Ergo]
- <https://github.com/chrisandreae/kinesis-firmware>

268
ldscript_keymap_avr5.x Normal file
View file

@ -0,0 +1,268 @@
/*
* linker script for configurable keymap
*
* This adds keymap section which places keymap at fixed address and
* is based on binutils-avr ldscripts(/usr/lib/ldscripts/avr5.x).
*/
OUTPUT_FORMAT("elf32-avr","elf32-avr","elf32-avr")
OUTPUT_ARCH(avr:5)
MEMORY
{
/* With keymap section
*
* Flash Map of ATMega32U4(32KB)
* +------------+ 0x0000
* | .vectors |
* | .progmem |
* | .init0-9 | > text region
* | .text |
* | .fini9-0 |
* | |
* |------------| _etext
* | .data |
* | .bss | > data region
* | .noinit |
* | |
* |------------| 0x6800
* | .keymap | > keymap region(2KB)
* |------------| 0x7000
* | bootloader | 4KB
* +------------+ 0x7FFF
*/
text (rx) : ORIGIN = 0, LENGTH = 128K
keymap (rw!x) : ORIGIN = 0x6800, LENGTH = 2K
data (rw!x) : ORIGIN = 0x800060, LENGTH = 0xffa0
eeprom (rw!x) : ORIGIN = 0x810000, LENGTH = 64K
fuse (rw!x) : ORIGIN = 0x820000, LENGTH = 1K
lock (rw!x) : ORIGIN = 0x830000, LENGTH = 1K
signature (rw!x) : ORIGIN = 0x840000, LENGTH = 1K
}
SECTIONS
{
/* Read-only sections, merged into text segment: */
.hash : { *(.hash) }
.dynsym : { *(.dynsym) }
.dynstr : { *(.dynstr) }
.gnu.version : { *(.gnu.version) }
.gnu.version_d : { *(.gnu.version_d) }
.gnu.version_r : { *(.gnu.version_r) }
.rel.init : { *(.rel.init) }
.rela.init : { *(.rela.init) }
.rel.text :
{
*(.rel.text)
*(.rel.text.*)
*(.rel.gnu.linkonce.t*)
}
.rela.text :
{
*(.rela.text)
*(.rela.text.*)
*(.rela.gnu.linkonce.t*)
}
.rel.fini : { *(.rel.fini) }
.rela.fini : { *(.rela.fini) }
.rel.rodata :
{
*(.rel.rodata)
*(.rel.rodata.*)
*(.rel.gnu.linkonce.r*)
}
.rela.rodata :
{
*(.rela.rodata)
*(.rela.rodata.*)
*(.rela.gnu.linkonce.r*)
}
.rel.data :
{
*(.rel.data)
*(.rel.data.*)
*(.rel.gnu.linkonce.d*)
}
.rela.data :
{
*(.rela.data)
*(.rela.data.*)
*(.rela.gnu.linkonce.d*)
}
.rel.ctors : { *(.rel.ctors) }
.rela.ctors : { *(.rela.ctors) }
.rel.dtors : { *(.rel.dtors) }
.rela.dtors : { *(.rela.dtors) }
.rel.got : { *(.rel.got) }
.rela.got : { *(.rela.got) }
.rel.bss : { *(.rel.bss) }
.rela.bss : { *(.rela.bss) }
.rel.plt : { *(.rel.plt) }
.rela.plt : { *(.rela.plt) }
/* Internal text space or external memory. */
.text :
{
*(.vectors)
KEEP(*(.vectors))
/* For data that needs to reside in the lower 64k of progmem. */
*(.progmem.gcc*)
*(.progmem*)
. = ALIGN(2);
__trampolines_start = . ;
/* The jump trampolines for the 16-bit limited relocs will reside here. */
*(.trampolines)
*(.trampolines*)
__trampolines_end = . ;
/* For future tablejump instruction arrays for 3 byte pc devices.
We don't relax jump/call instructions within these sections. */
*(.jumptables)
*(.jumptables*)
/* For code that needs to reside in the lower 128k progmem. */
*(.lowtext)
*(.lowtext*)
__ctors_start = . ;
*(.ctors)
__ctors_end = . ;
__dtors_start = . ;
*(.dtors)
__dtors_end = . ;
KEEP(SORT(*)(.ctors))
KEEP(SORT(*)(.dtors))
/* From this point on, we don't bother about wether the insns are
below or above the 16 bits boundary. */
*(.init0) /* Start here after reset. */
KEEP (*(.init0))
*(.init1)
KEEP (*(.init1))
*(.init2) /* Clear __zero_reg__, set up stack pointer. */
KEEP (*(.init2))
*(.init3)
KEEP (*(.init3))
*(.init4) /* Initialize data and BSS. */
KEEP (*(.init4))
*(.init5)
KEEP (*(.init5))
*(.init6) /* C++ constructors. */
KEEP (*(.init6))
*(.init7)
KEEP (*(.init7))
*(.init8)
KEEP (*(.init8))
*(.init9) /* Call main(). */
KEEP (*(.init9))
*(.text)
. = ALIGN(2);
*(.text.*)
. = ALIGN(2);
*(.fini9) /* _exit() starts here. */
KEEP (*(.fini9))
*(.fini8)
KEEP (*(.fini8))
*(.fini7)
KEEP (*(.fini7))
*(.fini6) /* C++ destructors. */
KEEP (*(.fini6))
*(.fini5)
KEEP (*(.fini5))
*(.fini4)
KEEP (*(.fini4))
*(.fini3)
KEEP (*(.fini3))
*(.fini2)
KEEP (*(.fini2))
*(.fini1)
KEEP (*(.fini1))
*(.fini0) /* Infinite loop after program termination. */
KEEP (*(.fini0))
_etext = . ;
} > text
.data : AT (ADDR (.text) + SIZEOF (.text))
{
PROVIDE (__data_start = .) ;
*(.data)
*(.data*)
*(.rodata) /* We need to include .rodata here if gcc is used */
*(.rodata*) /* with -fdata-sections. */
*(.gnu.linkonce.d*)
. = ALIGN(2);
_edata = . ;
PROVIDE (__data_end = .) ;
} > data
.bss : AT (ADDR (.bss))
{
PROVIDE (__bss_start = .) ;
*(.bss)
*(.bss*)
*(COMMON)
PROVIDE (__bss_end = .) ;
} > data
__data_load_start = LOADADDR(.data);
__data_load_end = __data_load_start + SIZEOF(.data);
/* Global data not cleared after reset. */
.noinit :
{
PROVIDE (__noinit_start = .) ;
*(.noinit*)
PROVIDE (__noinit_end = .) ;
_end = . ;
PROVIDE (__heap_start = .) ;
} > data
/* keymap region is located at end of flash
* .fn_actions Fn actions definitions
* .keymaps Mapping layers
*/
.keymap :
{
PROVIDE(__keymap_start = .) ;
*(.keymap.fn_actions) /* 32*actions = 64bytes */
. = ALIGN(0x40);
*(.keymap.keymaps) /* rest of .keymap section */
*(.keymap*)
/* . = ALIGN(0x800); */ /* keymap section takes 2KB- */
} > keymap = 0x00 /* zero fill */
.eeprom :
{
*(.eeprom*)
__eeprom_end = . ;
} > eeprom
.fuse :
{
KEEP(*(.fuse))
KEEP(*(.lfuse))
KEEP(*(.hfuse))
KEEP(*(.efuse))
} > fuse
.lock :
{
KEEP(*(.lock*))
} > lock
.signature :
{
KEEP(*(.signature*))
} > signature
/* Stabs debugging sections. */
.stab 0 : { *(.stab) }
.stabstr 0 : { *(.stabstr) }
.stab.excl 0 : { *(.stab.excl) }
.stab.exclstr 0 : { *(.stab.exclstr) }
.stab.index 0 : { *(.stab.index) }
.stab.indexstr 0 : { *(.stab.indexstr) }
.comment 0 : { *(.comment) }
/* DWARF debug sections.
Symbols in the DWARF debugging sections are relative to the beginning
of the section so we begin them at 0. */
/* DWARF 1 */
.debug 0 : { *(.debug) }
.line 0 : { *(.line) }
/* GNU DWARF 1 extensions */
.debug_srcinfo 0 : { *(.debug_srcinfo) }
.debug_sfnames 0 : { *(.debug_sfnames) }
/* DWARF 1.1 and DWARF 2 */
.debug_aranges 0 : { *(.debug_aranges) }
.debug_pubnames 0 : { *(.debug_pubnames) }
/* DWARF 2 */
.debug_info 0 : { *(.debug_info) *(.gnu.linkonce.wi.*) }
.debug_abbrev 0 : { *(.debug_abbrev) }
.debug_line 0 : { *(.debug_line) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
}

50
protocol.mk Normal file
View file

@ -0,0 +1,50 @@
PROTOCOL_DIR = protocol
ifdef PS2_MOUSE_ENABLE
SRC += $(PROTOCOL_DIR)/ps2_mouse.c
OPT_DEFS += -DPS2_MOUSE_ENABLE
OPT_DEFS += -DMOUSE_ENABLE
endif
ifdef PS2_USE_BUSYWAIT
SRC += protocol/ps2_busywait.c
SRC += protocol/ps2_io_avr.c
OPT_DEFS += -DPS2_USE_BUSYWAIT
endif
ifdef PS2_USE_INT
SRC += protocol/ps2_interrupt.c
SRC += protocol/ps2_io_avr.c
OPT_DEFS += -DPS2_USE_INT
endif
ifdef PS2_USE_USART
SRC += protocol/ps2_usart.c
SRC += protocol/ps2_io_avr.c
OPT_DEFS += -DPS2_USE_USART
endif
ifdef SERIAL_MOUSE_MICROSOFT_ENABLE
SRC += $(PROTOCOL_DIR)/serial_mouse_microsoft.c
OPT_DEFS += -DSERIAL_MOUSE_ENABLE -DSERIAL_MOUSE_MICROSOFT \
-DMOUSE_ENABLE
endif
ifdef SERIAL_MOUSE_MOUSESYSTEMS_ENABLE
SRC += $(PROTOCOL_DIR)/serial_mouse_mousesystems.c
OPT_DEFS += -DSERIAL_MOUSE_ENABLE -DSERIAL_MOUSE_MOUSESYSTEMS \
-DMOUSE_ENABLE
endif
ifdef SERIAL_MOUSE_USE_SOFT
SRC += $(PROTOCOL_DIR)/serial_soft.c
endif
ifdef SERIAL_MOUSE_USE_UART
SRC += $(PROTOCOL_DIR)/serial_uart.c
endif
# Search Path
VPATH += $(TMK_DIR)/protocol

456
protocol/adb.c Normal file
View file

@ -0,0 +1,456 @@
/*
Copyright 2011 Jun WAKO <wakojun@gmail.com>
Copyright 2013 Shay Green <gblargg@gmail.com>
This software is licensed with a Modified BSD License.
All of this is supposed to be Free Software, Open Source, DFSG-free,
GPL-compatible, and OK to use in both free and proprietary applications.
Additions and corrections to this file are welcome.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdbool.h>
#include <util/delay.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "adb.h"
// GCC doesn't inline functions normally
#define data_lo() (ADB_DDR |= (1<<ADB_DATA_BIT))
#define data_hi() (ADB_DDR &= ~(1<<ADB_DATA_BIT))
#define data_in() (ADB_PIN & (1<<ADB_DATA_BIT))
#ifdef ADB_PSW_BIT
static inline void psw_lo(void);
static inline void psw_hi(void);
static inline bool psw_in(void);
#endif
static inline void attention(void);
static inline void place_bit0(void);
static inline void place_bit1(void);
static inline void send_byte(uint8_t data);
static inline uint16_t wait_data_lo(uint16_t us);
static inline uint16_t wait_data_hi(uint16_t us);
void adb_host_init(void)
{
ADB_PORT &= ~(1<<ADB_DATA_BIT);
data_hi();
#ifdef ADB_PSW_BIT
psw_hi();
#endif
}
#ifdef ADB_PSW_BIT
bool adb_host_psw(void)
{
return psw_in();
}
#endif
/*
* Don't call this in a row without the delay, otherwise it makes some of poor controllers
* overloaded and misses strokes. Recommended interval is 12ms.
*
* Thanks a lot, blargg!
* <http://geekhack.org/index.php?topic=14290.msg1068919#msg1068919>
* <http://geekhack.org/index.php?topic=14290.msg1070139#msg1070139>
*/
// ADB Bit Cells
//
// bit cell time: 70-130us
// low part of bit0: 60-70% of bit cell
// low part of bit1: 30-40% of bit cell
//
// bit cell time 70us 130us
// --------------------------------------------
// low part of bit0 42-49 78-91
// high part of bit0 21-28 39-52
// low part of bit1 21-28 39-52
// high part of bit1 42-49 78-91
//
//
// bit0:
// 70us bit cell:
// ____________~~~~~~
// 42-49 21-28
//
// 130us bit cell:
// ____________~~~~~~
// 78-91 39-52
//
// bit1:
// 70us bit cell:
// ______~~~~~~~~~~~~
// 21-28 42-49
//
// 130us bit cell:
// ______~~~~~~~~~~~~
// 39-52 78-91
//
// [from Apple IIgs Hardware Reference Second Edition]
uint16_t adb_host_kbd_recv(void)
{
uint16_t data = 0;
cli();
attention();
send_byte(0x2C); // Addr:Keyboard(0010), Cmd:Talk(11), Register0(00)
place_bit0(); // Stopbit(0)
if (!wait_data_hi(500)) { // Service Request(310us Adjustable Keyboard): just ignored
sei();
return -30; // something wrong
}
if (!wait_data_lo(500)) { // Tlt/Stop to Start(140-260us)
sei();
return 0; // No data to send
}
uint8_t n = 17; // start bit + 16 data bits
do {
uint8_t lo = (uint8_t) wait_data_hi(130);
if (!lo)
goto error;
uint8_t hi = (uint8_t) wait_data_lo(lo);
if (!hi)
goto error;
hi = lo - hi;
lo = 130 - lo;
data <<= 1;
if (lo < hi) {
data |= 1;
}
else if (n == 17) {
sei();
return -20;
}
}
while ( --n );
// Stop bit can't be checked normally since it could have service request lenghtening
// and its high state never goes low.
if (!wait_data_hi(351) || wait_data_lo(91)) {
sei();
return -21;
}
sei();
return data;
error:
sei();
return -n;
}
void adb_host_listen(uint8_t cmd, uint8_t data_h, uint8_t data_l)
{
cli();
attention();
send_byte(cmd);
place_bit0(); // Stopbit(0)
_delay_us(200); // Tlt/Stop to Start
place_bit1(); // Startbit(1)
send_byte(data_h);
send_byte(data_l);
place_bit0(); // Stopbit(0);
sei();
}
// send state of LEDs
void adb_host_kbd_led(uint8_t led)
{
// Addr:Keyboard(0010), Cmd:Listen(10), Register2(10)
// send upper byte (not used)
// send lower byte (bit2: ScrollLock, bit1: CapsLock, bit0:
adb_host_listen(0x2A,0,led&0x07);
}
#ifdef ADB_PSW_BIT
static inline void psw_lo()
{
ADB_DDR |= (1<<ADB_PSW_BIT);
ADB_PORT &= ~(1<<ADB_PSW_BIT);
}
static inline void psw_hi()
{
ADB_PORT |= (1<<ADB_PSW_BIT);
ADB_DDR &= ~(1<<ADB_PSW_BIT);
}
static inline bool psw_in()
{
ADB_PORT |= (1<<ADB_PSW_BIT);
ADB_DDR &= ~(1<<ADB_PSW_BIT);
return ADB_PIN&(1<<ADB_PSW_BIT);
}
#endif
static inline void attention(void)
{
data_lo();
_delay_us(800-35); // bit1 holds lo for 35 more
place_bit1();
}
static inline void place_bit0(void)
{
data_lo();
_delay_us(65);
data_hi();
_delay_us(35);
}
static inline void place_bit1(void)
{
data_lo();
_delay_us(35);
data_hi();
_delay_us(65);
}
static inline void send_byte(uint8_t data)
{
for (int i = 0; i < 8; i++) {
if (data&(0x80>>i))
place_bit1();
else
place_bit0();
}
}
// These are carefully coded to take 6 cycles of overhead.
// inline asm approach became too convoluted
static inline uint16_t wait_data_lo(uint16_t us)
{
do {
if ( !data_in() )
break;
_delay_us(1 - (6 * 1000000.0 / F_CPU));
}
while ( --us );
return us;
}
static inline uint16_t wait_data_hi(uint16_t us)
{
do {
if ( data_in() )
break;
_delay_us(1 - (6 * 1000000.0 / F_CPU));
}
while ( --us );
return us;
}
/*
ADB Protocol
============
Resources
---------
ADB - The Untold Story: Space Aliens Ate My Mouse
http://developer.apple.com/legacy/mac/library/#technotes/hw/hw_01.html
ADB Manager
http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Devices/ADB_Manager.pdf
Service request(5-17)
Apple IIgs Hardware Reference Second Edition [Chapter6 p121]
ftp://ftp.apple.asimov.net/pub/apple_II/documentation/Apple%20IIgs%20Hardware%20Reference.pdf
ADB Keycode
http://72.0.193.250/Documentation/macppc/adbkeycodes/
http://m0115.web.fc2.com/m0115.jpg
[Inside Macintosh volume V, pages 191-192]
http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-421.18.3/IOHIDFamily/Cosmo_USB2ADB.c
ADB Signaling
http://kbdbabel.sourceforge.net/doc/kbd_signaling_pcxt_ps2_adb.pdf
ADB Overview & History
http://en.wikipedia.org/wiki/Apple_Desktop_Bus
Microchip Application Note: ADB device(with code for PIC16C)
http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1824&appnote=en011062
AVR ATtiny2131 ADB to PS/2 converter(Japanese)
http://hp.vector.co.jp/authors/VA000177/html/KeyBoardA5DEA5CBA5A2II.html
Pinouts
-------
ADB female socket from the front:
__________
| | <--- top
| 4o o3 |
|2o o1|
| == |
|________| <--- bottom
| | <--- 4pins
ADB female socket from bottom:
========== <--- front
| |
| |
|2o o1|
|4o o3|
---------- <--- back
1: Data
2: Power SW(low when press Power key)
3: Vcc(5V)
4: GND
Commands
--------
ADB command is 1byte and consists of 4bit-address, 2bit-command
type and 2bit-register. The commands are always sent by Host.
Command format:
7 6 5 4 3 2 1 0
| | | |------------ address
| |-------- command type
| |---- register
bits commands
------------------------------------------------------
- - - - 0 0 0 0 Send Request(reset all devices)
A A A A 0 0 0 1 Flush(reset a device)
- - - - 0 0 1 0 Reserved
- - - - 0 0 1 1 Reserved
- - - - 0 1 - - Reserved
A A A A 1 0 R R Listen(write to a device)
A A A A 1 1 R R Talk(read from a device)
The command to read keycodes from keyboard is 0x2C which
consist of keyboard address 2 and Talk against register 0.
Address:
2: keyboard
3: mice
Registers:
0: application(keyboard uses this to store its data.)
1: application
2: application(keyboard uses this for LEDs and state of modifiers)
3: status and command
Communication
-------------
This is a minimum information for keyboard communication.
See "Resources" for detail.
Signaling:
~~~~____________~~||||||||||||__~~~~~_~~|||||||||||||||__~~~~
|800us | |7 Command 0| | | |15-64 Data 0|Stopbit(0)
+Attention | | | +Startbit(1)
+Startbit(1) | +Tlt(140-260us)
+stopbit(0)
Bit cells:
bit0: ______~~~
65 :35us
bit1: ___~~~~~~
35 :65us
bit0 low time: 60-70% of bit cell(42-91us)
bit1 low time: 30-40% of bit cell(21-52us)
bit cell time: 70-130us
[from Apple IIgs Hardware Reference Second Edition]
Criterion for bit0/1:
After 55us if line is low/high then bit is 0/1.
Attention & start bit:
Host asserts low in 560-1040us then places start bit(1).
Tlt(Stop to Start):
Bus stays high in 140-260us then device places start bit(1).
Global reset:
Host asserts low in 2.8-5.2ms. All devices are forced to reset.
Service request from device(Srq):
Device can request to send at commad(Global only?) stop bit.
Requesting device keeps low for 140-260us at stop bit of command.
Keyboard Data(Register0)
This 16bit data can contains two keycodes and two released flags.
First keycode is palced in upper byte. When one keyocode is sent,
lower byte is 0xFF.
Release flag is 1 when key is released.
1514 . . . . . 8 7 6 . . . . . 0
| | | | | | | | | +-+-+-+-+-+-+- Keycode2
| | | | | | | | +--------------- Released2(1 when the key is released)
| +-+-+-+-+-+-+----------------- Keycode1
+------------------------------- Released1(1 when the key is released)
Keycodes:
Scancode consists of 7bit keycode and 1bit release flag.
Device can send two keycodes at once. If just one keycode is sent
keycode1 contains it and keyocode2 is 0xFF.
Power switch:
You can read the state from PSW line(active low) however
the switch has a special scancode 0x7F7F, so you can
also read from Data line. It uses 0xFFFF for release scancode.
Keyboard LEDs & state of keys(Register2)
This register hold current state of three LEDs and nine keys.
The state of LEDs can be changed by sending Listen command.
1514 . . . . . . 7 6 5 . 3 2 1 0
| | | | | | | | | | | | | | | +- LED1(NumLock)
| | | | | | | | | | | | | | +--- LED2(CapsLock)
| | | | | | | | | | | | | +----- LED3(ScrollLock)
| | | | | | | | | | +-+-+------- Reserved
| | | | | | | | | +------------- ScrollLock
| | | | | | | | +--------------- NumLock
| | | | | | | +----------------- Apple/Command
| | | | | | +------------------- Option
| | | | | +--------------------- Shift
| | | | +----------------------- Control
| | | +------------------------- Reset/Power
| | +--------------------------- CapsLock
| +----------------------------- Delete
+------------------------------- Reserved
END_OF_ADB
*/

62
protocol/adb.h Normal file
View file

@ -0,0 +1,62 @@
/*
Copyright 2011 Jun WAKO <wakojun@gmail.com>
This software is licensed with a Modified BSD License.
All of this is supposed to be Free Software, Open Source, DFSG-free,
GPL-compatible, and OK to use in both free and proprietary applications.
Additions and corrections to this file are welcome.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ADB_H
#define ADB_H
#include <stdint.h>
#include <stdbool.h>
#if !(defined(ADB_PORT) && \
defined(ADB_PIN) && \
defined(ADB_DDR) && \
defined(ADB_DATA_BIT))
# error "ADB port setting is required in config.h"
#endif
#define ADB_POWER 0x7F
#define ADB_CAPS 0x39
// ADB host
void adb_host_init(void);
bool adb_host_psw(void);
uint16_t adb_host_kbd_recv(void);
void adb_host_listen(uint8_t cmd, uint8_t data_h, uint8_t data_l);
void adb_host_kbd_led(uint8_t led);
#endif

27
protocol/bluefruit.mk Normal file
View file

@ -0,0 +1,27 @@
BLUEFRUIT_DIR = protocol/bluefruit
PJRC_DIR = protocol/pjrc
SRC += $(BLUEFRUIT_DIR)/main.c \
$(BLUEFRUIT_DIR)/bluefruit.c \
serial_uart.c \
$(PJRC_DIR)/pjrc.c \
$(PJRC_DIR)/usb_keyboard.c \
$(PJRC_DIR)/usb_debug.c \
$(PJRC_DIR)/usb.c
# Option modules
ifdef $(or MOUSEKEY_ENABLE, PS2_MOUSE_ENABLE)
SRC += $(PJRC_DIR)/usb_mouse.c
endif
ifdef EXTRAKEY_ENABLE
SRC += $(PJRC_DIR)/usb_extra.c
endif
# Search Path
VPATH += $(TMK_DIR)/$(BLUEFRUIT_DIR)
#VPATH += $(TMK_DIR)/$(BLUEFRUIT_DIR)/usb_debug_only
VPATH += $(TMK_DIR)/$(PJRC_DIR)
OPT_DEFS += -DPROTOCOL_BLUEFRUIT
OPT_DEFS += -DPROTOCOL_PJRC

View file

@ -0,0 +1,202 @@
/*
Bluefruit Protocol for TMK firmware
Author: Benjamin Gould, 2013
Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <stdint.h>
#include "host.h"
#include "report.h"
#include "print.h"
#include "debug.h"
#include "host_driver.h"
#include "serial.h"
#include "bluefruit.h"
#define BLUEFRUIT_TRACE_SERIAL 1
static uint8_t bluefruit_keyboard_leds = 0;
static void bluefruit_serial_send(uint8_t);
void bluefruit_keyboard_print_report(report_keyboard_t *report)
{
if (!debug_keyboard) return;
dprintf("keys: "); for (int i = 0; i < KEYBOARD_REPORT_KEYS; i++) { debug_hex8(report->keys[i]); dprintf(" "); }
dprintf(" mods: "); debug_hex8(report->mods);
dprintf(" reserved: "); debug_hex8(report->reserved);
dprintf("\n");
}
#ifdef BLUEFRUIT_TRACE_SERIAL
static void bluefruit_trace_header()
{
dprintf("+------------------------------------+\n");
dprintf("| HID report to Bluefruit via serial |\n");
dprintf("+------------------------------------+\n|");
}
static void bluefruit_trace_footer()
{
dprintf("|\n+------------------------------------+\n\n");
}
#endif
static void bluefruit_serial_send(uint8_t data)
{
#ifdef BLUEFRUIT_TRACE_SERIAL
dprintf(" ");
debug_hex8(data);
dprintf(" ");
#endif
serial_send(data);
}
/*------------------------------------------------------------------*
* Host driver
*------------------------------------------------------------------*/
static uint8_t keyboard_leds(void);
static void send_keyboard(report_keyboard_t *report);
static void send_mouse(report_mouse_t *report);
static void send_system(uint16_t data);
static void send_consumer(uint16_t data);
static host_driver_t driver = {
keyboard_leds,
send_keyboard,
send_mouse,
send_system,
send_consumer
};
host_driver_t *bluefruit_driver(void)
{
return &driver;
}
static uint8_t keyboard_leds(void) {
return bluefruit_keyboard_leds;
}
static void send_keyboard(report_keyboard_t *report)
{
#ifdef BLUEFRUIT_TRACE_SERIAL
bluefruit_trace_header();
#endif
bluefruit_serial_send(0xFD);
for (uint8_t i = 0; i < KEYBOARD_REPORT_SIZE; i++) {
bluefruit_serial_send(report->raw[i]);
}
#ifdef BLUEFRUIT_TRACE_SERIAL
bluefruit_trace_footer();
#endif
}
static void send_mouse(report_mouse_t *report)
{
#ifdef BLUEFRUIT_TRACE_SERIAL
bluefruit_trace_header();
#endif
bluefruit_serial_send(0xFD);
bluefruit_serial_send(0x00);
bluefruit_serial_send(0x03);
bluefruit_serial_send(report->buttons);
bluefruit_serial_send(report->x);
bluefruit_serial_send(report->y);
bluefruit_serial_send(report->v); // should try sending the wheel v here
bluefruit_serial_send(report->h); // should try sending the wheel h here
bluefruit_serial_send(0x00);
#ifdef BLUEFRUIT_TRACE_SERIAL
bluefruit_trace_footer();
#endif
}
static void send_system(uint16_t data)
{
}
/*
+-----------------+-------------------+-------+
| Consumer Key | Bit Map | Hex |
+-----------------+-------------------+-------+
| Home | 00000001 00000000 | 01 00 |
| KeyboardLayout | 00000010 00000000 | 02 00 |
| Search | 00000100 00000000 | 04 00 |
| Snapshot | 00001000 00000000 | 08 00 |
| VolumeUp | 00010000 00000000 | 10 00 |
| VolumeDown | 00100000 00000000 | 20 00 |
| Play/Pause | 01000000 00000000 | 40 00 |
| Fast Forward | 10000000 00000000 | 80 00 |
| Rewind | 00000000 00000001 | 00 01 |
| Scan Next Track | 00000000 00000010 | 00 02 |
| Scan Prev Track | 00000000 00000100 | 00 04 |
| Random Play | 00000000 00001000 | 00 08 |
| Stop | 00000000 00010000 | 00 10 |
+-------------------------------------+-------+
*/
#define CONSUMER2BLUEFRUIT(usage) \
(usage == AUDIO_MUTE ? 0x0000 : \
(usage == AUDIO_VOL_UP ? 0x1000 : \
(usage == AUDIO_VOL_DOWN ? 0x2000 : \
(usage == TRANSPORT_NEXT_TRACK ? 0x0002 : \
(usage == TRANSPORT_PREV_TRACK ? 0x0004 : \
(usage == TRANSPORT_STOP ? 0x0010 : \
(usage == TRANSPORT_STOP_EJECT ? 0x0000 : \
(usage == TRANSPORT_PLAY_PAUSE ? 0x4000 : \
(usage == AL_CC_CONFIG ? 0x0000 : \
(usage == AL_EMAIL ? 0x0000 : \
(usage == AL_CALCULATOR ? 0x0000 : \
(usage == AL_LOCAL_BROWSER ? 0x0000 : \
(usage == AC_SEARCH ? 0x0400 : \
(usage == AC_HOME ? 0x0100 : \
(usage == AC_BACK ? 0x0000 : \
(usage == AC_FORWARD ? 0x0000 : \
(usage == AC_STOP ? 0x0000 : \
(usage == AC_REFRESH ? 0x0000 : \
(usage == AC_BOOKMARKS ? 0x0000 : 0)))))))))))))))))))
static void send_consumer(uint16_t data)
{
static uint16_t last_data = 0;
if (data == last_data) return;
last_data = data;
uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
#ifdef BLUEFRUIT_TRACE_SERIAL
dprintf("\nData: ");
debug_hex16(data);
dprintf("; bitmap: ");
debug_hex16(bitmap);
dprintf("\n");
bluefruit_trace_header();
#endif
bluefruit_serial_send(0xFD);
bluefruit_serial_send(0x00);
bluefruit_serial_send(0x02);
bluefruit_serial_send((bitmap>>8)&0xFF);
bluefruit_serial_send(bitmap&0xFF);
bluefruit_serial_send(0x00);
bluefruit_serial_send(0x00);
bluefruit_serial_send(0x00);
bluefruit_serial_send(0x00);
#ifdef BLUEFRUIT_TRACE_SERIAL
bluefruit_trace_footer();
#endif
}

View file

@ -0,0 +1,28 @@
/*
Bluefruit Protocol for TMK firmware
Author: Benjamin Gould, 2013
Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef VUSB_H
#define VUSB_H
#include "host_driver.h"
host_driver_t *bluefruit_driver(void);
#endif

116
protocol/bluefruit/main.c Normal file
View file

@ -0,0 +1,116 @@
/*
Bluefruit Protocol for TMK firmware
Author: Benjamin Gould, 2013
Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <stdint.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <avr/sleep.h>
#include <util/delay.h>
#include "serial.h"
#include "keyboard.h"
#include "usb.h"
#include "host.h"
#include "timer.h"
#include "print.h"
#include "debug.h"
#include "sendchar.h"
#include "suspend.h"
#include "bluefruit.h"
#include "pjrc.h"
#define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
#define HOST_DRIVER_NOT_SET 0
#define BLUEFRUIT_HOST_DRIVER 1
#define PJRC_HOST_DRIVER 2
int main(void)
{
CPU_PRESCALE(0);
DDRD = _BV(PD5);
DDRB = _BV(PB0);
PORTD = _BV(PD5);
PORTB = _BV(PB0);
print_set_sendchar(sendchar);
usb_init();
_delay_ms(2000);
// while (!usb_configured()) /* wait */
dprintf("Initializing keyboard...\n");
keyboard_init();
// This implementation is pretty simplistic... if the USB connection
// is not configured, choose the Bluefruit, otherwise use USB
// Definitely would prefer to have this driven by an input pin and make
// it switch dynamically - BCG
if (!usb_configured()) {
// Send power to Bluefruit... Adafruit says it takes 27 mA, I think
// the pins should provide 40 mA, but just in case I switch the
// Bluefruit using a transistor - BCG
DDRB = _BV(PB6);
PORTB |= _BV(PB6);
dprintf("Setting host driver to bluefruit...\n");
host_set_driver(bluefruit_driver());
dprintf("Initializing serial...\n");
serial_init();
// wait an extra second for the PC's operating system
// to load drivers and do whatever it does to actually
// be ready for input
_delay_ms(1000);
PORTD = ~_BV(PD5);
dprintf("Starting main loop");
while (1) {
keyboard_task();
}
} else {
// I'm not smart enough to get this done with LUFA - BCG
dprintf("Setting host driver to PJRC...\n");
host_set_driver(pjrc_driver());
#ifdef SLEEP_LED_ENABLE
sleep_led_init();
#endif
// wait an extra second for the PC's operating system
// to load drivers and do whatever it does to actually
// be ready for input
_delay_ms(1000);
PORTB = ~_BV(PB0);
dprintf("Starting main loop");
while (1) {
while (suspend) {
suspend_power_down();
if (remote_wakeup && suspend_wakeup_condition()) {
usb_remote_wakeup();
}
}
keyboard_task();
}
}
}

169
protocol/ibm4704.c Normal file
View file

@ -0,0 +1,169 @@
/*
Copyright 2010,2011,2012,2013 Jun WAKO <wakojun@gmail.com>
*/
#include <stdbool.h>
#include <util/delay.h>
#include "debug.h"
#include "ibm4704.h"
#define WAIT(stat, us, err) do { \
if (!wait_##stat(us)) { \
ibm4704_error = err; \
goto ERROR; \
} \
} while (0)
uint8_t ibm4704_error = 0;
void ibm4704_init(void)
{
inhibit();
}
/*
Host to Keyboard
----------------
Data bits are LSB first and Parity is odd. Clock has around 60us high and 30us low part.
____ __ __ __ __ __ __ __ __ __ ________
Clock \______/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
^ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___
Data ____|__/ X____X____X____X____X____X____X____X____X____X \___
| Start 0 1 2 3 4 5 6 7 P Stop
Request by host
Start bit: can be long as 300-350us.
Request: Host pulls Clock line down to request to send a command.
Timing: After Request keyboard pull up Data and down Clock line to low for start bit.
After request host release Clock line once Data line becomes hi.
Host writes a bit while Clock is hi and Keyboard reads while low.
Stop bit: Host releases or pulls up Data line to hi after 9th clock and waits for keyboard pull down the line to lo.
*/
uint8_t ibm4704_send(uint8_t data)
{
bool parity = true; // odd parity
ibm4704_error = 0;
/* Request to send */
idle();
clock_lo();
/* wait for Start bit(Clock:lo/Data:hi) */
WAIT(data_hi, 300, 0x30);
/* Data bit */
for (uint8_t i = 0; i < 8; i++) {
WAIT(clock_hi, 100, 0x40+i);
//_delay_us(5);
if (data&(1<<i)) {
parity = !parity;
data_hi();
} else {
data_lo();
}
WAIT(clock_lo, 100, 0x48+i);
}
/* Parity bit */
WAIT(clock_hi, 100, 0x34);
if (parity) { data_hi(); } else { data_lo(); }
WAIT(clock_lo, 100, 0x35);
/* Stop bit */
WAIT(clock_hi, 100, 0x34);
data_hi();
/* End */
WAIT(data_lo, 100, 0x36);
inhibit();
_delay_us(200); // wait to recover clock to hi
return 0;
ERROR:
inhibit();
if (ibm4704_error >= 0x30) {
xprintf("x%02X ", ibm4704_error);
}
_delay_us(200); // wait to recover clock to hi
return -1;
}
/* receive data when host want else inhibit communication */
uint8_t ibm4704_recv_response(void)
{
// 250 * 100us(wait start bit in ibm4704_recv)
uint8_t data = 0;
uint8_t try = 250;
do {
data = ibm4704_recv();
} while (try-- && ibm4704_error);
return data;
}
/*
Keyboard to Host
----------------
Data bits are LSB first and Parity is odd. Clock has around 60us high and 30us low part.
____ __ __ __ __ __ __ __ __ __ ________
Clock \____/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
____ ____ ____ ____ ____ ____ ____ ____ ____ ____
Data ____/ X____X____X____X____X____X____X____X____X____X________
Start 0 1 2 3 4 5 6 7 P Stop
Start bit: can be long as 300-350us.
Inhibit: Pull Data line down to inhibit keyboard to send.
Timing: Host reads bit while Clock is hi.
Stop bit: Keyboard pulls down Data line to lo after 9th clock.
*/
uint8_t ibm4704_recv(void)
{
uint8_t data = 0;
bool parity = true; // odd parity
ibm4704_error = IBM4704_ERR_NONE;
idle();
_delay_us(5); // wait for line settles
/* start bit */
WAIT(clock_lo, 100, 0x11); // wait for keyboard to send
WAIT(data_hi, 100, 0x12); // can be delayed that long
WAIT(clock_hi, 100, 0x13); // first rising edge which can take longer
/* data */
for (uint8_t i = 0; i < 8; i++) {
WAIT(clock_hi, 100, 0x20+i);
//_delay_us(5);
if (data_in()) {
parity = !parity;
data |= (1<<i);
}
WAIT(clock_lo, 150, 0x28+i);
}
/* parity */
WAIT(clock_hi, 100, 0x17);
if (data_in() != parity) {
ibm4704_error = IBM4704_ERR_PARITY;
goto ERROR;
}
WAIT(clock_lo, 150, 0x18);
/* stop bit */
WAIT(clock_hi, 100, 0x19);
WAIT(data_lo, 1, 0x19);
inhibit();
_delay_us(200); // wait to recover clock to hi
return data;
ERROR:
if (ibm4704_error > 0x12) {
xprintf("x%02X ", ibm4704_error);
}
inhibit();
_delay_us(200); // wait to recover clock to hi
return -1;
}

110
protocol/ibm4704.h Normal file
View file

@ -0,0 +1,110 @@
/*
Copyright 2014 Jun WAKO <wakojun@gmail.com>
*/
#ifndef IBM4704_H
#define IBM4704_H
#define IBM4704_ERR_NONE 0
#define IBM4704_ERR_PARITY 0x70
void ibm4704_init(void);
uint8_t ibm4704_send(uint8_t data);
uint8_t ibm4704_recv_response(void);
uint8_t ibm4704_recv(void);
/* Check pin configuration */
#if !(defined(IBM4704_CLOCK_PORT) && \
defined(IBM4704_CLOCK_PIN) && \
defined(IBM4704_CLOCK_DDR) && \
defined(IBM4704_CLOCK_BIT))
# error "ibm4704 clock pin configuration is required in config.h"
#endif
#if !(defined(IBM4704_DATA_PORT) && \
defined(IBM4704_DATA_PIN) && \
defined(IBM4704_DATA_DDR) && \
defined(IBM4704_DATA_BIT))
# error "ibm4704 data pin configuration is required in config.h"
#endif
/*--------------------------------------------------------------------
* static functions
*------------------------------------------------------------------*/
static inline void clock_lo(void)
{
IBM4704_CLOCK_PORT &= ~(1<<IBM4704_CLOCK_BIT);
IBM4704_CLOCK_DDR |= (1<<IBM4704_CLOCK_BIT);
}
static inline void clock_hi(void)
{
/* input with pull up */
IBM4704_CLOCK_DDR &= ~(1<<IBM4704_CLOCK_BIT);
IBM4704_CLOCK_PORT |= (1<<IBM4704_CLOCK_BIT);
}
static inline bool clock_in(void)
{
IBM4704_CLOCK_DDR &= ~(1<<IBM4704_CLOCK_BIT);
IBM4704_CLOCK_PORT |= (1<<IBM4704_CLOCK_BIT);
_delay_us(1);
return IBM4704_CLOCK_PIN&(1<<IBM4704_CLOCK_BIT);
}
static inline void data_lo(void)
{
IBM4704_DATA_PORT &= ~(1<<IBM4704_DATA_BIT);
IBM4704_DATA_DDR |= (1<<IBM4704_DATA_BIT);
}
static inline void data_hi(void)
{
/* input with pull up */
IBM4704_DATA_DDR &= ~(1<<IBM4704_DATA_BIT);
IBM4704_DATA_PORT |= (1<<IBM4704_DATA_BIT);
}
static inline bool data_in(void)
{
IBM4704_DATA_DDR &= ~(1<<IBM4704_DATA_BIT);
IBM4704_DATA_PORT |= (1<<IBM4704_DATA_BIT);
_delay_us(1);
return IBM4704_DATA_PIN&(1<<IBM4704_DATA_BIT);
}
static inline uint16_t wait_clock_lo(uint16_t us)
{
while (clock_in() && us) { asm(""); _delay_us(1); us--; }
return us;
}
static inline uint16_t wait_clock_hi(uint16_t us)
{
while (!clock_in() && us) { asm(""); _delay_us(1); us--; }
return us;
}
static inline uint16_t wait_data_lo(uint16_t us)
{
while (data_in() && us) { asm(""); _delay_us(1); us--; }
return us;
}
static inline uint16_t wait_data_hi(uint16_t us)
{
while (!data_in() && us) { asm(""); _delay_us(1); us--; }
return us;
}
/* idle state that device can send */
static inline void idle(void)
{
clock_hi();
data_hi();
}
/* inhibit device to send
* keyboard checks Data line on start bit(Data:hi) and it stops sending if Data line is low.
*/
static inline void inhibit(void)
{
clock_hi();
data_lo();
}
#endif

26
protocol/iwrap.mk Normal file
View file

@ -0,0 +1,26 @@
IWRAP_DIR = protocol/iwrap
OPT_DEFS += -DPROTOCOL_IWRAP
SRC += $(IWRAP_DIR)/main.c \
$(IWRAP_DIR)/iwrap.c \
$(IWRAP_DIR)/suart.S \
$(COMMON_DIR)/sendchar_uart.c \
$(COMMON_DIR)/uart.c
# Search Path
VPATH += $(TMK_DIR)/protocol/iwrap
# TODO: compatible with LUFA and PJRC
# V-USB
#
VUSB_DIR = protocol/vusb
OPT_DEFS += -DPROTOCOL_VUSB
SRC += $(VUSB_DIR)/vusb.c \
$(VUSB_DIR)/usbdrv/usbdrv.c \
$(VUSB_DIR)/usbdrv/usbdrvasm.S \
$(VUSB_DIR)/usbdrv/oddebug.c
VPATH += $(TMK_DIR)/protocol/vusb:$(TMK_DIR)/protocol/vusb/usbdrv

376
protocol/iwrap/iWRAP4.txt Normal file
View file

@ -0,0 +1,376 @@
Bulegiga WT12
=============
WT12 is a bluetooth module from Bluegiga. http://www.bluegiga.com/
iWRAP
higher layer interface for bluetooth firmware
communicate with UART
iWRAP HID
default setting
115200 8bit/n/1/n
TODO
----
KiCAD circuit/PCB design
power saving
AVR sleep(15ms by watch dog timer)
WT12 sleep
measuring current consumption
measuring battery life of normal usage/idle/intensive usage
software reset/bootloarder
LED indicator(chaging/paring/connecting)
license confirmation of suart.c
consumer page is not working
authenticate method/SSP
SPP keyboard support
SPP debug console support
mouse wheel feature request to Bluegiga
Problems
--------
power consumption
no consumer page support(bug?)
no mouse wheel support
no paring management
no interactive auth method
UART hardware flow control
--------------------------
(iWRAP4 User Guide 9.5)
Hardware flow control is enabled by default and it should not be disabled unless mandatory, because without the hardware flow control the data transmission may not be reliable.
If the hardware flow control is enabled from PS-keys, but no flow control is used, the following steps should be implemented in the hardware design:
- CTS pin must be grounded
- RTS pin must be left floating
Power Saving
------------
power consume
without opimization: 4hr to shutdown(310mAh)
2011/08/25: 9hr(310mAh) SNIFF MASTER sleep/WDTO_120MS
measure current consumption
HHKB keyswitch matrix board
idle
scanning
Bluegiga WT12 module
SLEEP command
deep sleep on/off in config bits
HHKB keyswich
how to power off
I/O pin configuration when sleeping
FET switch for 5V regulator
Bluetooth module
power off when in USB mode
power off by FET switch
AVR configuration
unused pins
ADC
SET CONTROL CONFIG
------------------
SET CONTROL CONFIG 4810
SET CONTROL CONFIG LIST
SET CONTROL CONFIG 0000 0000 4910 DEEP_SLEEP KLUDGE INTERACTIVE_PIN UART_LATENCY
Bit14 UART low latency
Bit11 Interactive pairing mode
Bit04 Deep sleep
Reconnection
------------
SET CONTROL AUTOCALL 1124 5000 HID
1124 HID service class
5000 interval ms
HID profile
-----------
This is needed to configure only once.
SET PROFILE HID ON
RESET
HID class
---------
SET BT CLASS 005C0 // keyboard/mouse combined devie
Pairing Security
----------------
Secure Simple Pairing(SSP)
SET BT SSP 2 0 // Enables SSP for keyboard and Man-in-the-middle protection
SET BT SSP 3 0 // Enables SSP just works mode
for keyboard with SSP
SET BT AUTH * 0000
SET BT SSP 2 0
SET CONTROL CONFIG 800
RESET
for keyboard without SSP
SET BT AUTH * 0000
SET CONTROL CONFIG 800
RESET
AUTH
AUTH xx:xx:xx:xx:xx:xx? // Pairing request event
AUTH xx:xx:xx:xx:xx:xx 0000
SSP PASSKEY 78:dd:08:b7:e4:a2 ?
SSP PASSKEY 78:dd:08:b7:e4:a2 xxxxx
(SSP COMPLETE 78:dd:08:b7:e4:a2 HCI_ERROR_AUTH_FAIL // failed)
RING 0 78:dd:08:b7:e4:a2 11 HID
Connecton
RING xx:xx:xx:xx:xx:xx xx HID // connection event
KILL xx:xx:xx:xx:xx:xx
Mode
----
Command mode
Data mode
Raw mode
(Simple mode not for a real keyboard)
Raw mode
Keyboard:
0x9f, length(10), 0xa1, 0x01, mods, 0x00, key1, key2, key3, key4, key5, key6
Mouse:
0x9f, length(5), 0xa1, 0x02, buttons, X, Y
Consumer page:
0x9f, length(5), 0xa1, 0x03, bitfield1, bitfield2, bitfield3
consumer page suage
Bitfield 1:
0x01 Volume Increment
0x02 Volume Decrement
0x04 Mute
0x08 Play/Pause
0x10 Scan Next Track
0x20 Scan Previous Track
0x40 Stop
0x80 Eject
Bitfield 2:
0x01 Email Reader
0x02 Application Control Search
0x04 AC Bookmarks
0x08 AC Home
0x10 AC Back
0x20 AC Forward
0x40 AC Stop
0x80 AC Refresh
Bitfield 3:
0x01 Application Launch Generic Consumer Control
0x02 AL Internet Browser
0x04 AL Calculator
0x08 AL Terminal Lock / Screensaver
0x10 AL Local Machine Browser
0x20 AC Minimize
0x40 Record
0x80 Rewind
2011/07/13
set
SET BT BDADDR 00:07:80:47:22:14
SET BT NAME HHKB pro BT
SET BT CLASS 0005c0
SET BT AUTH * 0000
SET BT IDENT BT:47 f000 4.1.0 Bluegiga iWRAP
SET BT LAP 9e8b33
SET BT PAGEMODE 4 2000 1
SET BT PAIR 78:dd:08:b7:e4:a2 a191189cd7e51030ad6a07848ce879bb
SET BT POWER 3 3 3
SET BT ROLE 0 f 7d00
SET BT SNIFF 0 20 1 8
SET BT SSP 2 1
SET BT MTU 667
SET CONTROL AUTOCALL 1124 3000 HID
SET CONTROL BAUD 38400,8n1
SET CONTROL CD 00 0
SET CONTROL ECHO 7
SET CONTROL ESCAPE 43 00 1
SET CONTROL GAIN 0 5
SET CONTROL INIT SET CONTROL MUX 0
SET CONTROL MSC DTE 00 00 00 00 00 00
SET CONTROL MUX 1
SET CONTROL PIO 00 00
SET CONTROL READY 00
SET PROFILE HID f HID
SET
info config
!!! THIS IS BETA RELEASE AND MAY BE USED FOR EVALUATION PURPOSES ONLY !!!
WRAP THOR AI (4.1.0 build 435)
Copyright (c) 2003-2011 Bluegiga Technologies Inc.
Compiled on Jun 28 2011 17:19:51, running on WT12-A module, psr v31
AVRCP BGIO FTP HFP HFP_AG HID HID_CONSUMER_PAGE HSP LEDS MAP OTA PBAP PIO=0x00fc SSP SUBRATE TEST VOLUME
- BOCK3 version 435 (Jun 28 2011 17:19:37) (max acl/sco 7/1)
- Bluetooth version 2.1, Power class 2
- Loader 4279, firmware 6297 (56-bit encryption), native execution mode
- up 0 days, 06:23, 2 connections (pool 2)
- User configuration:
&028a = 0001 0000 0000 0011 0024 0000 0000 0010 0000 0080 0000 0000 0080 005f 009b 0034 00fb 0006
&028b = 0000 0bb8
&028d = 0001
&0295 = 0000 0005 000b 0000 0003 0000 0000 0000 0000 0000 0000
&0298 = a006
&0299 = 0000 0000
&02a3 = 0030 0030 0030 0030
&02a4 = 009d 0000
&02a5 = 0053 0045 0054 0020 0043 004f 004e 0054 0052 004f 004c 0020 004d 0055 0058 0020 0030
&02a7 = 0000 05c0
&02a8 = 4910 0000 0000
&02aa = 0004 2000 0001 0033 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
&02ac = 0000 0000 002b 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
&02ad = 4848 424b 7020 6f72 4220 0054
&02b3 = 0005 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003
&02b7 = 000f 4948 0044
&02bb = 8000
READY.
2011/07/07 settings:
set
SET BT BDADDR 00:07:80:47:22:14
SET BT NAME HHKB Pro BT
SET BT CLASS 0005c0
SET BT AUTH * 000
SET BT IDENT BT:47 f000 4.0.0 Bluegiga iWRAP
SET BT LAP 9e8b33
SET BT PAGEMODE 4 2000 1
SET BT PAIR 78:dd:08:b7:e4:a2 9e54d0aabb1b4d73cfccddb1ea4ef2d6
SET BT POWER 3 3 3
SET BT ROLE 0 f 7d00
SET BT SNIFF 0 20 1 8
SET BT SSP 3 0
SET BT MTU 667
SET CONTROL BAUD 38400,8n1
SET CONTROL CD 00 0
SET CONTROL ECHO 7
SET CONTROL ESCAPE 255 00 1
SET CONTROL GAIN 0 5
SET CONTROL INIT set control mux 0
SET CONTROL MSC DTE 00 00 00 00 00 00
SET CONTROL PREAMP 1 1
SET CONTROL READY 00
SET PROFILE HID HID
SET PROFILE SPP Bluetooth Serial Port
SET
info config
WRAP THOR AI (4.0.0 build 317)
Copyright (c) 2003-2010 Bluegiga Technologies Inc.
Compiled on Apr 20 2010 16:44:28, running on WT12-A module, psr v31
AVRCP FTP PBAP PIO=0x00fc SSP SUBRATE VOLUME
- BOCK3 version 317 (Apr 20 2010 16:44:21) (max acl/sco 7/1)
- Bluetooth version 2.1, Power class 2
- Loader 4279, firmware 6297 (56-bit encryption), native execution mode
- up 0 days, 00:00, 0 connections (pool 1)
- User configuration:
&028c = 0001 0020 0000 0001 0008 0000
&028d = 0000
&0296 = 0047 0001 f000 0400 6c42 6575 6967 6167 6920 5257 5041
&0298 = c006
&02a3 = 0030 0030 0030
&02a4 = 009d 0000
&02a5 = 0073 0065 0074 0020 0063 006f 006e 0074 0072 006f 006c 0020 006d 0075 0078 0020 0030
&02a7 = 0000 05c0
&02a8 = 0800 0000 0000
&02ac = 0000 0000 00ff 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
&02ad = 4848 424b 5020 6f72 4220 0054
&02b3 = 0004 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003
&02b7 = 0000
&02bb = 6c42 6575 6f74 746f 2068 6553 6972 6c61 5020 726f 0074
READY.
2011/08/23:
SET BT BDADDR 00:07:80:47:22:14
SET BT NAME HHKB pro BT
SET BT CLASS 0005c0
SET BT AUTH * 0000
SET BT IDENT BT:47 f000 4.1.0 Bluegiga iWRAP
SET BT LAP 9e8b33
SET BT PAGEMODE 4 2000 1
SET BT PAIRCOUNT 4
SET BT POWER 3 3 3
SET BT ROLE 1 f 12c0
SET BT SNIFF 10 2 1 8
SET BT SSP 3 0
SET BT MTU 667
SET CONTROL BAUD 38400,8n1
SET CONTROL CD 00 0
SET CONTROL ECHO 7
SET CONTROL ESCAPE 43 00 1
SET CONTROL GAIN 0 5
SET CONTROL INIT SET CONTROL MUX 0
SET CONTROL MSC DTE 00 00 00 00 00 00
SET CONTROL MUX 1
SET CONTROL PIO 00 00
SET CONTROL READY 00
SET PROFILE HID 7 HIDKeyboardMouse
SET
SET CONTROL CONFIG 0000 0004 481e CLOCK_CACHE INTERLACED_INQ INTERLACED_PAGE DEEP_SLEEP INTERACTIVE_PIN UART_LATENCY 23D_NOKLUDGE
2011/08/25:
SET BT BDADDR 00:07:80:47:22:14
SET BT NAME HHKB pro BT
SET BT CLASS 0005c0
SET BT IDENT BT:47 f000 4.1.0 Bluegiga iWRAP
SET BT LAP 9e8b33
SET BT PAGEMODE 4 2000 1
SET BT PAIRCOUNT 4
SET BT PAIR 78:dd:08:b7:e4:a2 0be83335a03fed8ededae42e99554e28
SET BT POWER 3 3 3
SET BT ROLE 1 f 12c0
SET BT SNIFF 100 20 1 8
SET BT SSP 3 0
SET BT MTU 667
SET CONTROL BAUD 38400,8n1
SET CONTROL CD 00 0
SET CONTROL ECHO 7
SET CONTROL ESCAPE - 20 1
SET CONTROL GAIN 0 5
SET CONTROL INIT SET CONTROL MUX 0
SET CONTROL MSC DTE 00 00 00 00 00 00
SET CONTROL MUX 1
SET CONTROL PIO 00 00
SET CONTROL READY 00
SET PROFILE HID f HIDKeyboardMouse
SET
SET CONTROL CONFIG 0000 0000 490e CLOCK_CACHE INTERLACED_INQ INTERLACED_PAGE KLUDGE INTERACTIVE_PIN UART_LATENCY
2011/09/08:
SET CONTROL CONFIG 0000 0000 410e CLOCK_CACHE INTERLACED_INQ INTERLACED_PAGE KLUDGE UART_LATENCY
Removed INTERACTIVE_PIN to avoid interactive auth and use SET BT AUTH pin(0000).
EOF

356
protocol/iwrap/iWRAP5.txt Normal file
View file

@ -0,0 +1,356 @@
Terminology
===========
PSM
HIDP HID Protocol
L2CAP Logical Link Control Adaptation Protocol
MTU Maximum Transmission Unit
HID Protocol
============
3 of HID_SPEC_V11.pdf
Channel
-------
Control channel PSM=0x0011
Interrupt channel PSM=0x0013
Message
-------
HANDSHAKE(0)
HID_CONTROL(1)
GET_REPORT(4)
Host requests report(DATA payload on Control channel) from Device
Size Desc
------------------------------------------------------------------------------
HIDP-Hdr 1 7..4: HIDP Message TYpe(4: GET_REPORT)
3: Size(1:2-octed buffer size, 0:size of the report)
2: 0
1..0: Report Type(1:input, 2:output, 3: feature)
ReportID 1 Optional
BufferSize 2 Optional(specified when Size=1)
SET_REPORT(5)
GET_PROTOCOL(6)
SET_PROTOCOL(7)
DATA(A)
Input/Output Report: All DATA payloads flow on Interrupt channel.
Other: flows on Control channel.
Size Desc
------------------------------------------------------------------------------
HIDP-Hdr 1 7..4 0xA
3..2 Reserved(0)
1..0 Report Type(0:Other, 1:Input, 2:Output, 3:Feature)
Payload N Data
Boot Protocol
=============
3.3.2
No report descriptor, fixed report descriptors defined.
Device ReportID Size
---------------------------------
Reserved 0
Keyboard 1 9octets
Mouse 2 4octets
Reserved 3-255
Report descriptor
-----------------
Report ID is added to USB HID boot protocol descriptor.
Boot Protocol device doesn't need to supply descriptors. and can send extra data on end of boot report this data will be ignored unless host supports report descriptor.
Report Protocol devices can have specific descriptors. Using Boot protocol descriptor followed by extra data may be useful for compatibility to Boot protocol only supported host.
NOTE:
Bluegiga HID sample say report ID of mouse is 1 but 2?
Bluegiga HID sample say report ID of consumer page is 2 but 3?
** mouse.desc and consumer.desc were fixed.
size
keyboard.desc 67 0x43
mouse.desc 60 0x3c
consumer.desc 82 0x52
combo.desc 209 0xd1
SDP
===
attributes(3.3.2)
----------
HIDDeviceSubclass
which type is supported in Boot Protocol Mode
7 6
---
0 1 Keyboard
1 0 Pointing device
1 1 Combo keyboard/pointing device
HIDBootDevice
TRUE
HIDReconnectInitiate
TRUE
Class of Device/Service
=======================
http://phys.sci.hokudai.ac.jp/LABS/yts/pic/GB002/Bluetooth_assigned_numbers_baseband.pdf
0x0005C0 Keyboard and Pointing deivce(combo)
23 16 15 8 7 0
---------------------------------
Service |Major |Minor |Format
Format type
1 0
---
0 0
Minor Device Class of Peripheral Major
7 6
---
0 1 Keyboard
1 0 Pointing device
1 1 Combo keyboard/pointing device
Major device classes
12 11 10 9 8
--------------
0 0 0 0 0 Miscellaneous
0 0 0 0 1 Computer
0 0 0 1 0 Phone
0 0 0 1 1 LAN /Network Access point
0 0 1 0 0 Audio/Video (headset,speaker,stereo, video display, vcr.....
0 0 1 0 1 *Peripheral (mouse, joystick, keyboards, ..... )
0 0 1 1 0 Imaging (printing, scanner, camera, display, ...)
1 1 1 1 1 Uncategorized, specific device code not specified
X X X X X All other values reserved
Major service classes
bit
--------------------------------------
13 Limited Discoverable Mode [Ref #1]
14 (reserved)
15 (reserved)
16 Positioning (Location identification)
17 Networking (LAN, Ad hoc, ...)
18 Rendering (Printing, Speaker, ...)
19 Capturing (Scanner, Microphone, ...)
20 Object Transfer (v-Inbox, v-Folder, ...)
21 Audio (Speaker, Microphone, Headset service, ...)
22 Telephony (Cordless telephony, Modem, Headset service, ...)
23 Information (WEB-server, WAP-server, ...)
Authentication SSP
-------------------
SET BT SSP 2 0 PASS KEY entering
SET BT SSP 3 0 NO PASS KEY entering
SET BT SSP <capabilities> <mitm>
<capabilities>: 0:display only 1:display+yes/no button 2:keyboard only 3:none
SET BT SSP 2 1 # 2:keyboard only 1:Man-in-the-middle protection is needed
SET BT SSP 2 0 # 2:keyboard only 0:Man-in-the-middle protection is not needed
SET BT SSP 2 1
bond only if MITM protection is supported by host
SET BT SSP 2 0
bond even if MITM protection is not supported by host
On Windows 'Add device' causes SSP PASSKEY event on iWRAP
SSP PASSKEY 78:dd:08:b7:e4:a2 ?
If device has display(0 or 1) this event occurs. User should be shown this code on the device.
SSP CONFIRM 78:dd:08:b7:e4:a2 517572
SET BT SSP 3 0
No input/output, No MITM protection.
Without procedure of authentication the divice is bond to host.
Connect
=======
CALL 78:dd:08:b7:e4:a2 11 HID
Setting
========
Following settings need to be done before wiring into keyboard.
- UART speed: 38400bps(115200bps didn't work with software serial)
- No SSP procedure(without MITM protection)
- No Power Saving
# clear pairing record and set default
SET BT PAIR *
SET RESET
SET CONTROL INIT SET CONTROL MUX 0
SET CONTROL BAUD 38400,8n1
SET BT NAME TMK Blootooth WT12
SET BT CLASS 0005c0
SET BT AUTH * 0000
SET BT SSP 3 0
SET CONTROL CONFIG 4800
SET PROFILE HID 0f c0 0100 00 en 0409 TMK Bluetooth keyboard(WT12)
SET PROFILE SPP
# power saving?
SET BT SNIFF 100 20 1 8
# Report Descriptor
# combo keyboard + mouse + consumer
HID SET d2 05010906a1010507850119e029e715002501750195088102950175088101950575010508850119012905910295017503910395067508150025650507190029658100c005010902a1010901a1008502050919012908150025017501950881020501093009311581257f750895028106093895018106050c0a380295018106c0c0050c0901a1018503050c1500250109e909ea09e209cd19b529b87501950881020a8a010a21020a2a021a23022a27027501950881020a83010a96010a92010a9e010a94010a060209b209b4750195088102c0
SET PROFILE HID
---------------
SET PROFILE HID 0d c0 100 0 en 0409 HHKB pro Bluetooth keyboard
{function bit} uint8
{subclass} uint8
{version} uint16
{country} uint8
{BTlang} char[2]
{USBlang} uint16
{name} string
SET BT CLASS
------------
See Class of Device
composite device: keyboard and mouse
SET BT CLASS 005c0
----------
after setting
----------
set
SET BT BDADDR 00:07:80:47:22:14
SET BT NAME TMK Blootooth WT12
SET BT CLASS 0005c0
SET BT AUTH * 0000
SET BT IDENT BT:47 f000 5.0.1 Bluegiga iWRAP
SET BT LAP 9e8b33
SET BT PAGEMODE 4 2000 1
SET BT PAIR 78:dd:08:b7:e4:a2 9e3d85c91bcae73fef8cc10bec18b42f
SET BT POWER 3 3 3
SET BT ROLE 0 f 7d00
SET BT SNIFF 0 20 1 8
SET BT SSP 3 0
SET BT MTU 667
SET CONTROL BAUD 38400,8n1
SET CONTROL CD 00 0
SET CONTROL ECHO 7
SET CONTROL ESCAPE 43 00 1
SET CONTROL GAIN 0 5
SET CONTROL INIT SET CONTROL MUX 0
SET CONTROL MSC DTE 00 00 00 00 00 00
SET CONTROL MUX 1
SET CONTROL PIO 00 00
SET CONTROL READY 00
SET PROFILE HID 0f c0 0100 00 en 0409 TMK Bluetooth keyboard(WT12)
SET
set control config list
SET CONTROL CONFIG 0000 0000 0000 4900 KLUDGE INTERACTIVE_PIN UART_LATENCY
info config
WRAP THOR AI (5.0.1 build 620)
Copyright (c) 2003-2012 Bluegiga Technologies Inc.
Compiled on Oct 1 2012 10:56:21, running on WT12-A module, psr v31
BGIO FTP HFP HFP_AG HID HID_CONSUMER_PAGE HSP MAP MDP OTA PBAP PIO=0x00fc SSP SUBRATE TEST VOLUME
- BOCK4 version 620 (Oct 1 2012 10:56:03) (max acl/sco 7/1)
- Bluetooth version 3.0, Power class 2
- Loader 8615, firmware 8825 (56-bit encryption), native execution mode
- up 0 days, 01:50, 2 connections (pool 2)
- User configuration:
&028d = 0001
&0295 = 0000 0005 000b 0000 0003 0000 0000 0000 0000 0000 0000
&0298 = c053
&0299 = 0000 0000
&02a3 = 0030 0030 0030 0030
&02a4 = 009d 0000
&02a5 = 0053 0045 0054 0020 0043 004f 004e 0054 0052 004f 004c 0020 004d 0055 0058 0020 0030
&02a7 = 0000 05c0
&02a8 = 0800 0000 0000 0000
&02aa = 0004 2000 0001 0033 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
&02ac = 0000 0000 002b 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
&02ad = 4d54 204b 6c42 6f6f 6f74 746f 2068 5457 3231
&02b0 = fa65 b0aa 934a 077b a600 d1cc fe58 8dd5
&02b3 = 0004 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0005 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0005
&02b7 = 000f 00c0 0100 0000 0065 006e 0409 4d54 204b 6c42 6575 6f74 746f &02bb = 8000
READY.
----------
-----
After 5.0.1 Firmware update
Firmware: ai-5.0.1-620-25b.bc4.dfu
PSR: wt12-a.ai-5.0.1-620-25b.psrf
-----
info config
WRAP THOR AI (5.0.1 build 620)
Copyright (c) 2003-2012 Bluegiga Technologies Inc.
Compiled on Oct 1 2012 10:56:21, running on WT12-A module, psr v31
BGIO FTP HFP HFP_AG HID HID_CONSUMER_PAGE HSP MAP MDP OTA PBAP PIO=0x00fc SSP SUBRATE TEST VOLUME
- BOCK4 version 620 (Oct 1 2012 10:56:03) (max acl/sco 7/1)
- Bluetooth version 3.0, Power class 2
- Loader 8615, firmware 8825 (56-bit encryption), native execution mode
- up 0 days, 00:03, 0 connections (pool 1)
- User configuration:
&0295 = 0000 0005 000b 0000 0003 0000 0000 0000 0000 0000 0000
&0299 = 0000 0000
&02aa = 0004 2000 0001 0033 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
&02ac = 0000 0000 002b 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
&02ad = 5457 3231 412d
&02b0 = fa65 b0aa 934a 077b a600 d1cc fe58 8dd5
READY.
set
SET BT BDADDR 00:07:80:47:22:14
SET BT NAME WT12-A
SET BT CLASS 001f00
SET BT IDENT BT:47 f000 5.0.1 Bluegiga iWRAP
SET BT LAP 9e8b33
SET BT PAGEMODE 4 2000 1
SET BT PAIR 78:dd:08:b7:e4:a2 af18f81faa107e6dd068762ef921f48b
SET BT POWER 3 3 3
SET BT ROLE 0 f 7d00
SET BT SNIFF 0 20 1 8
SET BT SSP 3 0
SET BT MTU 667
SET CONTROL BAUD 115200,8n1
SET CONTROL CD 00 0
SET CONTROL ECHO 7
SET CONTROL ESCAPE 43 00 1
SET CONTROL GAIN 0 5
SET CONTROL MSC DTE 00 00 00 00 00 00
SET CONTROL PIO 00 00
SET CONTROL READY 00
SET PROFILE SPP Bluetooth Serial Port
SET
set control config list
SET CONTROL CONFIG 0000 0000 0000 0100 KLUDGE
---------

469
protocol/iwrap/iwrap.c Normal file
View file

@ -0,0 +1,469 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
/* host driver for Bulegiga iWRAP */
/* Bluegiga BT12
* Connections
* Hardware UART Software UART BlueTooth
* PC=====UART=======AVR=====SUART====iWRAP(BT12)-----------PC
*
* - Hardware UART for Debug Console to communicate iWRAP
* - Software UART for iWRAP control to send keyboard/mouse data
*/
#include <stdint.h>
#include <string.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "keycode.h"
#include "suart.h"
#include "uart.h"
#include "report.h"
#include "host_driver.h"
#include "iwrap.h"
#include "print.h"
/* iWRAP MUX mode utils. 3.10 HID raw mode(iWRAP_HID_Application_Note.pdf) */
#define MUX_HEADER(LINK, LENGTH) do { \
xmit(0xbf); /* SOF */ \
xmit(LINK); /* Link */ \
xmit(0x00); /* Flags */ \
xmit(LENGTH); /* Length */ \
} while (0)
#define MUX_FOOTER(LINK) xmit(LINK^0xff)
static uint8_t connected = 0;
//static uint8_t channel = 1;
/* iWRAP buffer */
#define MUX_BUF_SIZE 64
static char buf[MUX_BUF_SIZE];
static uint8_t snd_pos = 0;
#define MUX_RCV_BUF_SIZE 256
static char rcv_buf[MUX_RCV_BUF_SIZE];
static uint8_t rcv_head = 0;
static uint8_t rcv_tail = 0;
/* receive buffer */
static void rcv_enq(char c)
{
uint8_t next = (rcv_head + 1) % MUX_RCV_BUF_SIZE;
if (next != rcv_tail) {
rcv_buf[rcv_head] = c;
rcv_head = next;
}
}
static char rcv_deq(void)
{
char c = 0;
if (rcv_head != rcv_tail) {
c = rcv_buf[rcv_tail++];
rcv_tail %= MUX_RCV_BUF_SIZE;
}
return c;
}
/*
static char rcv_peek(void)
{
if (rcv_head == rcv_tail)
return 0;
return rcv_buf[rcv_tail];
}
*/
static void rcv_clear(void)
{
rcv_tail = rcv_head = 0;
}
/* iWRAP response */
ISR(PCINT1_vect, ISR_BLOCK) // recv() runs away in case of ISR_NOBLOCK
{
if ((SUART_IN_PIN & (1<<SUART_IN_BIT)))
return;
static volatile uint8_t mux_state = 0xff;
static volatile uint8_t mux_link = 0xff;
uint8_t c = recv();
switch (mux_state) {
case 0xff: // SOF
if (c == 0xbf)
mux_state--;
break;
case 0xfe: // Link
mux_state--;
mux_link = c;
break;
case 0xfd: // Flags
mux_state--;
break;
case 0xfc: // Length
mux_state = c;
break;
case 0x00:
mux_state = 0xff;
mux_link = 0xff;
break;
default:
if (mux_state--) {
uart_putchar(c);
rcv_enq(c);
}
}
}
/*------------------------------------------------------------------*
* iWRAP communication
*------------------------------------------------------------------*/
void iwrap_init(void)
{
// reset iWRAP if in already MUX mode after AVR software-reset
iwrap_send("RESET");
iwrap_mux_send("RESET");
_delay_ms(3000);
iwrap_send("\r\nSET CONTROL MUX 1\r\n");
_delay_ms(500);
iwrap_check_connection();
}
void iwrap_mux_send(const char *s)
{
rcv_clear();
MUX_HEADER(0xff, strlen((char *)s));
iwrap_send(s);
MUX_FOOTER(0xff);
}
void iwrap_send(const char *s)
{
while (*s)
xmit(*s++);
}
/* send buffer */
void iwrap_buf_add(uint8_t c)
{
// need space for '\0'
if (snd_pos < MUX_BUF_SIZE-1)
buf[snd_pos++] = c;
}
void iwrap_buf_del(void)
{
if (snd_pos)
snd_pos--;
}
void iwrap_buf_send(void)
{
buf[snd_pos] = '\0';
snd_pos = 0;
iwrap_mux_send(buf);
}
void iwrap_call(void)
{
char *p;
iwrap_mux_send("SET BT PAIR");
_delay_ms(500);
p = rcv_buf + rcv_tail;
while (!strncmp(p, "SET BT PAIR", 11)) {
p += 7;
strncpy(p, "CALL", 4);
strncpy(p+22, " 11 HID\n\0", 9);
print_S(p);
iwrap_mux_send(p);
// TODO: skip to next line
p += 57;
DEBUG_LED_CONFIG;
DEBUG_LED_ON;
_delay_ms(500);
DEBUG_LED_OFF;
_delay_ms(500);
DEBUG_LED_ON;
_delay_ms(500);
DEBUG_LED_OFF;
_delay_ms(500);
DEBUG_LED_ON;
_delay_ms(500);
DEBUG_LED_OFF;
_delay_ms(500);
DEBUG_LED_ON;
_delay_ms(500);
DEBUG_LED_OFF;
_delay_ms(500);
DEBUG_LED_ON;
_delay_ms(500);
DEBUG_LED_OFF;
_delay_ms(500);
}
iwrap_check_connection();
}
void iwrap_kill(void)
{
char c;
iwrap_mux_send("LIST");
_delay_ms(500);
while ((c = rcv_deq()) && c != '\n') ;
if (strncmp(rcv_buf + rcv_tail, "LIST ", 5)) {
print("no connection to kill.\n");
return;
}
// skip 10 'space' chars
for (uint8_t i = 10; i; i--)
while ((c = rcv_deq()) && c != ' ') ;
char *p = rcv_buf + rcv_tail - 5;
strncpy(p, "KILL ", 5);
strncpy(p + 22, "\n\0", 2);
print_S(p);
iwrap_mux_send(p);
_delay_ms(500);
iwrap_check_connection();
}
void iwrap_unpair(void)
{
iwrap_mux_send("SET BT PAIR");
_delay_ms(500);
char *p = rcv_buf + rcv_tail;
if (!strncmp(p, "SET BT PAIR", 11)) {
strncpy(p+29, "\n\0", 2);
print_S(p);
iwrap_mux_send(p);
}
}
void iwrap_sleep(void)
{
iwrap_mux_send("SLEEP");
}
void iwrap_sniff(void)
{
}
void iwrap_subrate(void)
{
}
bool iwrap_failed(void)
{
if (strncmp(rcv_buf, "SYNTAX ERROR", 12))
return true;
else
return false;
}
uint8_t iwrap_connected(void)
{
return connected;
}
uint8_t iwrap_check_connection(void)
{
iwrap_mux_send("LIST");
_delay_ms(100);
if (strncmp(rcv_buf, "LIST ", 5) || !strncmp(rcv_buf, "LIST 0", 6))
connected = 0;
else
connected = 1;
return connected;
}
/*------------------------------------------------------------------*
* Host driver
*------------------------------------------------------------------*/
static uint8_t keyboard_leds(void);
static void send_keyboard(report_keyboard_t *report);
static void send_mouse(report_mouse_t *report);
static void send_system(uint16_t data);
static void send_consumer(uint16_t data);
static host_driver_t driver = {
keyboard_leds,
send_keyboard,
send_mouse,
send_system,
send_consumer
};
host_driver_t *iwrap_driver(void)
{
return &driver;
}
static uint8_t keyboard_leds(void) {
return 0;
}
static void send_keyboard(report_keyboard_t *report)
{
if (!iwrap_connected() && !iwrap_check_connection()) return;
MUX_HEADER(0x01, 0x0c);
// HID raw mode header
xmit(0x9f);
xmit(0x0a); // Length
xmit(0xa1); // DATA(Input)
xmit(0x01); // Report ID
xmit(report->mods);
xmit(0x00); // reserved byte(always 0)
xmit(report->keys[0]);
xmit(report->keys[1]);
xmit(report->keys[2]);
xmit(report->keys[3]);
xmit(report->keys[4]);
xmit(report->keys[5]);
MUX_FOOTER(0x01);
}
static void send_mouse(report_mouse_t *report)
{
#if defined(MOUSEKEY_ENABLE) || defined(PS2_MOUSE_ENABLE)
if (!iwrap_connected() && !iwrap_check_connection()) return;
MUX_HEADER(0x01, 0x09);
// HID raw mode header
xmit(0x9f);
xmit(0x07); // Length
xmit(0xa1); // DATA(Input)
xmit(0x02); // Report ID
xmit(report->buttons);
xmit(report->x);
xmit(report->y);
xmit(report->v);
xmit(report->h);
MUX_FOOTER(0x01);
#endif
}
static void send_system(uint16_t data)
{
/* not supported */
}
static void send_consumer(uint16_t data)
{
#ifdef EXTRAKEY_ENABLE
static uint16_t last_data = 0;
uint8_t bits1 = 0;
uint8_t bits2 = 0;
uint8_t bits3 = 0;
if (!iwrap_connected() && !iwrap_check_connection()) return;
if (data == last_data) return;
last_data = data;
// 3.10 HID raw mode(iWRAP_HID_Application_Note.pdf)
switch (data) {
case AUDIO_VOL_UP:
bits1 = 0x01;
break;
case AUDIO_VOL_DOWN:
bits1 = 0x02;
break;
case AUDIO_MUTE:
bits1 = 0x04;
break;
case TRANSPORT_PLAY_PAUSE:
bits1 = 0x08;
break;
case TRANSPORT_NEXT_TRACK:
bits1 = 0x10;
break;
case TRANSPORT_PREV_TRACK:
bits1 = 0x20;
break;
case TRANSPORT_STOP:
bits1 = 0x40;
break;
case TRANSPORT_EJECT:
bits1 = 0x80;
break;
case AL_EMAIL:
bits2 = 0x01;
break;
case AC_SEARCH:
bits2 = 0x02;
break;
case AC_BOOKMARKS:
bits2 = 0x04;
break;
case AC_HOME:
bits2 = 0x08;
break;
case AC_BACK:
bits2 = 0x10;
break;
case AC_FORWARD:
bits2 = 0x20;
break;
case AC_STOP:
bits2 = 0x40;
break;
case AC_REFRESH:
bits2 = 0x80;
break;
case AL_CC_CONFIG:
bits3 = 0x01;
break;
case AL_CALCULATOR:
bits3 = 0x04;
break;
case AL_LOCK:
bits3 = 0x08;
break;
case AL_LOCAL_BROWSER:
bits3 = 0x10;
break;
case AC_MINIMIZE:
bits3 = 0x20;
break;
case TRANSPORT_RECORD:
bits3 = 0x40;
break;
case TRANSPORT_REWIND:
bits3 = 0x80;
break;
}
MUX_HEADER(0x01, 0x07);
xmit(0x9f);
xmit(0x05); // Length
xmit(0xa1); // DATA(Input)
xmit(0x03); // Report ID
xmit(bits1);
xmit(bits2);
xmit(bits3);
MUX_FOOTER(0x01);
#endif
}

49
protocol/iwrap/iwrap.h Normal file
View file

@ -0,0 +1,49 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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/>.
*/
#ifndef IWRAP_H
#define IWRAP_H
#include <stdint.h>
#include <stdbool.h>
#include "host_driver.h"
/* enable iWRAP MUX mode */
#define MUX_MODE
host_driver_t *iwrap_driver(void);
void iwrap_init(void);
void iwrap_send(const char *s);
void iwrap_mux_send(const char *s);
void iwrap_buf_send(void);
void iwrap_buf_add(uint8_t c);
void iwrap_buf_del(void);
void iwrap_call(void);
void iwrap_kill(void);
void iwrap_unpair(void);
void iwrap_sleep(void);
void iwrap_sniff(void);
void iwrap_subrate(void);
bool iwrap_failed(void);
uint8_t iwrap_connected(void);
uint8_t iwrap_check_connection(void);
#endif

376
protocol/iwrap/main.c Normal file
View file

@ -0,0 +1,376 @@
/*
Copyright 2011 Jun Wako <wakojun@gmail.com>
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, either version 2 of the License, or
(at your option) any later version.
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 <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
//#include <avr/wdt.h>
#include "wd.h" // in order to use watchdog in interrupt mode
#include <avr/sleep.h>
#include <util/delay.h>
#include <avr/power.h>
#include "keyboard.h"
#include "matrix.h"
#include "host.h"
#include "action.h"
#include "iwrap.h"
#ifdef PROTOCOL_VUSB
# include "vusb.h"
# include "usbdrv.h"
#endif
#include "uart.h"
#include "suart.h"
#include "timer.h"
#include "debug.h"
#include "keycode.h"
#include "command.h"
static void sleep(uint8_t term);
static bool console(void);
static bool console_command(uint8_t c);
static uint8_t key2asc(uint8_t key);
/*
static void set_prr(void)
{
power_adc_disable();
power_spi_disable();
power_twi_disable();
#ifndef TIMER_H
//power_timer0_disable(); // used in timer.c
#endif
power_timer1_disable();
power_timer2_disable();
}
*/
/*
static void pullup_pins(void)
{
// DDRs are set to 0(input) by default.
#ifdef PORTA
PORTA = 0xFF;
#endif
PORTB = 0xFF;
PORTC = 0xFF;
PORTD = 0xFF;
#ifdef PORTE
PORTE = 0xFF;
#endif
#ifdef PORTE
PORTF = 0xFF;
#endif
}
*/
#ifdef PROTOCOL_VUSB
static void disable_vusb(void)
{
// disable interrupt & disconnect to prevent host from enumerating
USB_INTR_ENABLE &= ~(1 << USB_INTR_ENABLE_BIT);
usbDeviceDisconnect();
}
static void enable_vusb(void)
{
USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT);
usbDeviceConnect();
}
static void init_vusb(void)
{
uint8_t i = 0;
usbInit();
disable_vusb();
/* fake USB disconnect for > 250 ms */
while(--i){
_delay_ms(1);
}
enable_vusb();
}
#endif
void change_driver(host_driver_t *driver)
{
/*
host_clear_keyboard_report();
host_swap_keyboard_report();
host_clear_keyboard_report();
host_send_keyboard_report();
*/
clear_keyboard();
_delay_ms(1000);
host_set_driver(driver);
}
static bool sleeping = false;
static bool insomniac = false; // TODO: should be false for power saving
static uint16_t last_timer = 0;
int main(void)
{
MCUSR = 0;
clock_prescale_set(clock_div_1);
WD_SET(WD_OFF);
// power saving: the result is worse than nothing... why?
//pullup_pins();
//set_prr();
#ifdef PROTOCOL_VUSB
disable_vusb();
#endif
uart_init(115200);
keyboard_init();
print("\nSend BREAK for UART Console Commands.\n");
// TODO: move to iWRAP/suart file
print("suart init\n");
// suart init
// PC4: Tx Output IDLE(Hi)
PORTC |= (1<<4);
DDRC |= (1<<4);
// PC5: Rx Input(pull-up)
PORTC |= (1<<5);
DDRC &= ~(1<<5);
// suart receive interrut(PC5/PCINT13)
PCMSK1 = 0b00100000;
PCICR = 0b00000010;
host_set_driver(iwrap_driver());
print("iwrap_init()\n");
iwrap_init();
iwrap_call();
last_timer = timer_read();
while (true) {
#ifdef PROTOCOL_VUSB
if (host_get_driver() == vusb_driver())
usbPoll();
#endif
keyboard_task();
#ifdef PROTOCOL_VUSB
if (host_get_driver() == vusb_driver())
vusb_transfer_keyboard();
#endif
// TODO: depricated
if (matrix_is_modified() || console()) {
last_timer = timer_read();
sleeping = false;
} else if (!sleeping && timer_elapsed(last_timer) > 4000) {
sleeping = true;
iwrap_check_connection();
}
// TODO: suspend.h
if (host_get_driver() == iwrap_driver()) {
if (sleeping && !insomniac) {
_delay_ms(1); // wait for UART to send
iwrap_sleep();
sleep(WDTO_60MS);
}
}
}
}
static void sleep(uint8_t term)
{
WD_SET(WD_IRQ, term);
cli();
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();
sleep_disable();
WD_SET(WD_OFF);
}
static bool console(void)
{
// Send to Bluetoot module WT12
static bool breaked = false;
if (!uart_available())
return false;
else {
uint8_t c;
c = uart_getchar();
uart_putchar(c);
switch (c) {
case 0x00: // BREAK signal
if (!breaked) {
print("break(? for help): ");
breaked = true;
}
break;
case '\r':
uart_putchar('\n');
iwrap_buf_send();
break;
case '\b':
iwrap_buf_del();
break;
default:
if (breaked) {
print("\n");
console_command(c);
breaked = false;
} else {
iwrap_buf_add(c);
}
break;
}
return true;
}
}
bool command_extra(uint8_t code)
{
return console_command(key2asc(code));
}
static bool console_command(uint8_t c)
{
switch (c) {
case 'h':
case '?':
print("\nCommands for Bluetooth(WT12/iWRAP):\n");
print("r: reset. software reset by watchdog\n");
print("i: insomniac. prevent KB from sleeping\n");
print("c: iwrap_call. CALL for BT connection.\n");
#ifdef PROTOCOL_VUSB
print("u: USB mode. switch to USB.\n");
print("w: BT mode. switch to Bluetooth.\n");
#endif
print("k: kill first connection.\n");
print("Del: unpair first pairing.\n");
print("\n");
return 0;
case 'r':
print("reset\n");
WD_AVR_RESET();
return 1;
case 'i':
insomniac = !insomniac;
if (insomniac)
print("insomniac\n");
else
print("not insomniac\n");
return 1;
case 'c':
print("iwrap_call()\n");
iwrap_call();
return 1;
#ifdef PROTOCOL_VUSB
case 'u':
print("USB mode\n");
init_vusb();
change_driver(vusb_driver());
//iwrap_kill();
//iwrap_sleep();
// disable suart receive interrut(PC5/PCINT13)
PCMSK1 &= ~(0b00100000);
PCICR &= ~(0b00000010);
return 1;
case 'w':
print("iWRAP mode\n");
change_driver(iwrap_driver());
disable_vusb();
// enable suart receive interrut(PC5/PCINT13)
PCMSK1 |= 0b00100000;
PCICR |= 0b00000010;
return 1;
#endif
case 'k':
print("kill\n");
iwrap_kill();
return 1;
case 0x7F: // DELETE
print("unpair\n");
iwrap_unpair();
return 1;
}
return 0;
}
// convert keycode into ascii charactor
static uint8_t key2asc(uint8_t key)
{
switch (key) {
case KC_A: return 'a';
case KC_B: return 'b';
case KC_C: return 'c';
case KC_D: return 'd';
case KC_E: return 'e';
case KC_F: return 'f';
case KC_G: return 'g';
case KC_H: return 'h';
case KC_I: return 'i';
case KC_J: return 'j';
case KC_K: return 'k';
case KC_L: return 'l';
case KC_M: return 'm';
case KC_N: return 'n';
case KC_O: return 'o';
case KC_P: return 'p';
case KC_Q: return 'q';
case KC_R: return 'r';
case KC_S: return 's';
case KC_T: return 't';
case KC_U: return 'u';
case KC_V: return 'v';
case KC_W: return 'w';
case KC_X: return 'x';
case KC_Y: return 'y';
case KC_Z: return 'z';
case KC_1: return '1';
case KC_2: return '2';
case KC_3: return '3';
case KC_4: return '4';
case KC_5: return '5';
case KC_6: return '6';
case KC_7: return '7';
case KC_8: return '8';
case KC_9: return '9';
case KC_0: return '0';
case KC_ENTER: return '\n';
case KC_ESCAPE: return 0x1B;
case KC_BSPACE: return '\b';
case KC_TAB: return '\t';
case KC_SPACE: return ' ';
case KC_MINUS: return '-';
case KC_EQUAL: return '=';
case KC_LBRACKET: return '[';
case KC_RBRACKET: return ']';
case KC_BSLASH: return '\\';
case KC_NONUS_HASH: return '\\';
case KC_SCOLON: return ';';
case KC_QUOTE: return '\'';
case KC_GRAVE: return '`';
case KC_COMMA: return ',';
case KC_DOT: return '.';
case KC_SLASH: return '/';
default: return 0x00;
}
}

View file

@ -0,0 +1,7 @@
#
# Rescue from Bluegiga iWRAP MUX mode
# 6.75 of iWRAP5_User_Guid.pdf
#
[0xBF, 0xFF, 0x00, 0x11, 0x53, 0x45, 0x54, 0x20, 0x43, 0x4f, 0x4e, 0x54, 0x52, 0x4f, 0x4c, 0x20, 0x4d, 0x55, 0x58, 0x20, 0x30, 0x00].each do |x|
print x.chr
end

156
protocol/iwrap/suart.S Normal file
View file

@ -0,0 +1,156 @@
;---------------------------------------------------------------------------;
; Software implemented UART module ;
; (C)ChaN, 2005 (http://elm-chan.org/) ;
;---------------------------------------------------------------------------;
; Bit rate settings:
;
; 1MHz 2MHz 4MHz 6MHz 8MHz 10MHz 12MHz 16MHz 20MHz
; 2.4kbps 138 - - - - - - - -
; 4.8kbps 68 138 - - - - - - -
; 9.6kbps 33 68 138 208 - - - - -
; 19.2kbps - 33 68 102 138 173 208 - -
; 38.4kbps - - 33 50 68 85 102 138 172
; 57.6kbps - - 21 33 44 56 68 91 114
; 115.2kbps - - - - 21 27 33 44 56
.nolist
#include <avr/io.h>
.list
#define BPS 102 /* Bit delay. (see above table) */
#define BIDIR 0 /* 0:Separated Tx/Rx, 1:Shared Tx/Rx */
#define OUT_1 sbi _SFR_IO_ADDR(SUART_OUT_PORT), SUART_OUT_BIT /* Output 1 */
#define OUT_0 cbi _SFR_IO_ADDR(SUART_OUT_PORT), SUART_OUT_BIT /* Output 0 */
#define SKIP_IN_1 sbis _SFR_IO_ADDR(SUART_IN_PIN), SUART_IN_BIT /* Skip if 1 */
#define SKIP_IN_0 sbic _SFR_IO_ADDR(SUART_IN_PIN), SUART_IN_BIT /* Skip if 0 */
#ifdef SPM_PAGESIZE
.macro _LPMI reg
lpm \reg, Z+
.endm
.macro _MOVW dh,dl, sh,sl
movw \dl, \sl
.endm
#else
.macro _LPMI reg
lpm
mov \reg, r0
adiw ZL, 1
.endm
.macro _MOVW dh,dl, sh,sl
mov \dl, \sl
mov \dh, \sh
.endm
#endif
;---------------------------------------------------------------------------;
; Transmit a byte in serial format of N81
;
;Prototype: void xmit (uint8_t data);
;Size: 16 words
.global xmit
.func xmit
xmit:
#if BIDIR
ldi r23, BPS-1 ;Pre-idle time for bidirectional data line
5: dec r23 ;
brne 5b ;/
#endif
in r0, _SFR_IO_ADDR(SREG) ;Save flags
com r24 ;C = start bit
ldi r25, 10 ;Bit counter
cli ;Start critical section
1: ldi r23, BPS-1 ;----- Bit transferring loop
2: dec r23 ;Wait for a bit time
brne 2b ;/
brcs 3f ;MISO = bit to be sent
OUT_1 ;
3: brcc 4f ;
OUT_0 ;/
4: lsr r24 ;Get next bit into C
dec r25 ;All bits sent?
brne 1b ; no, coutinue
out _SFR_IO_ADDR(SREG), r0 ;End of critical section
ret
.endfunc
;---------------------------------------------------------------------------;
; Receive a byte
;
;Prototype: uint8_t rcvr (void);
;Size: 19 words
.global rcvr
.func rcvr
rcvr:
in r0, _SFR_IO_ADDR(SREG) ;Save flags
ldi r24, 0x80 ;Receiving shift reg
cli ;Start critical section
1: SKIP_IN_1 ;Wait for idle
rjmp 1b
2: SKIP_IN_0 ;Wait for start bit
rjmp 2b
ldi r25, BPS/2 ;Wait for half bit time
3: dec r25
brne 3b
4: ldi r25, BPS ;----- Bit receiving loop
5: dec r25 ;Wait for a bit time
brne 5b ;/
lsr r24 ;Next bit
SKIP_IN_0 ;Get a data bit into r24.7
ori r24, 0x80
brcc 4b ;All bits received? no, continue
out _SFR_IO_ADDR(SREG), r0 ;End of critical section
ret
.endfunc
; Not wait for start bit. This should be called after detecting start bit.
.global recv
.func recv
recv:
in r0, _SFR_IO_ADDR(SREG) ;Save flags
ldi r24, 0x80 ;Receiving shift reg
cli ;Start critical section
;1: SKIP_IN_1 ;Wait for idle
; rjmp 1b
;2: SKIP_IN_0 ;Wait for start bit
; rjmp 2b
ldi r25, BPS/2 ;Wait for half bit time
3: dec r25
brne 3b
4: ldi r25, BPS ;----- Bit receiving loop
5: dec r25 ;Wait for a bit time
brne 5b ;/
lsr r24 ;Next bit
SKIP_IN_0 ;Get a data bit into r24.7
ori r24, 0x80
brcc 4b ;All bits received? no, continue
ldi r25, BPS/2 ;Wait for half bit time
6: dec r25
brne 6b
7: SKIP_IN_1 ;Wait for stop bit
rjmp 7b
out _SFR_IO_ADDR(SREG), r0 ;End of critical section
ret
.endfunc

8
protocol/iwrap/suart.h Normal file
View file

@ -0,0 +1,8 @@
#ifndef SUART
#define SUART
void xmit(uint8_t);
uint8_t rcvr(void);
uint8_t recv(void);
#endif /* SUART */

159
protocol/iwrap/wd.h Normal file
View file

@ -0,0 +1,159 @@
/* This is from http://www.mtcnet.net/~henryvm/wdt/ */
#ifndef _AVR_WD_H_
#define _AVR_WD_H_
#include <avr/io.h>
/*
Copyright (c) 2009, Curt Van Maanen
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
include usage-
#include "wd.h" //if in same directory as project
#include <avr/wd.h> //if wd.h is in avr directory
set watchdog modes and prescale
usage-
WD_SET(mode,[timeout]); //prescale always set
modes-
WD_OFF disabled
WD_RST normal reset mode
WD_IRQ interrupt only mode (if supported)
WD_RST_IRQ interrupt+reset mode (if supported)
timeout-
WDTO_15MS default if no timeout provided
WDTO_30MS
WDTO_60MS
WDTO_120MS
WDTO_250MS
WDTO_500MS
WDTO_1S
WDTO_2S
WDTO_4S (if supported)
WDTO_8S (if supported)
examples-
WD_SET(WD_RST,WDTO_1S); //reset mode, 1s timeout
WD_SET(WD_OFF); //watchdog disabled (if not fused on)
WD_SET(WD_RST); //reset mode, 15ms (default timeout)
WD_SET(WD_IRQ,WDTO_120MS); //interrupt only mode, 120ms timeout
WD_SET(WD_RST_IRQ,WDTO_2S); //interrupt+reset mode, 2S timeout
for enhanced watchdogs, if the watchdog is not being used WDRF should be
cleared on every power up or reset, along with disabling the watchdog-
WD_DISABLE(); //clear WDRF, then turn off watchdog
*/
//reset registers to the same name (MCUCSR)
#if !defined(MCUCSR)
#define MCUCSR MCUSR
#endif
//watchdog registers to the same name (WDTCSR)
#if !defined(WDTCSR)
#define WDTCSR WDTCR
#endif
//if enhanced watchdog, define irq values, create disable macro
#if defined(WDIF)
#define WD_IRQ 0xC0
#define WD_RST_IRQ 0xC8
#define WD_DISABLE() do{ \
MCUCSR &= ~(1<<WDRF); \
WD_SET(WD_OFF); \
}while(0)
#endif
//all watchdogs
#define WD_RST 8
#define WD_OFF 0
//prescale values
#define WDTO_15MS 0
#define WDTO_30MS 1
#define WDTO_60MS 2
#define WDTO_120MS 3
#define WDTO_250MS 4
#define WDTO_500MS 5
#define WDTO_1S 6
#define WDTO_2S 7
//prescale values for avrs with WDP3
#if defined(WDP3)
#define WDTO_4S 0x20
#define WDTO_8S 0x21
#endif
//watchdog reset
#define WDR() __asm__ __volatile__("wdr")
//avr reset using watchdog
#define WD_AVR_RESET() do{ \
__asm__ __volatile__("cli"); \
WD_SET_UNSAFE(WD_RST); \
while(1); \
}while(0)
/*set the watchdog-
1. save SREG
2. turn off irq's
3. reset watchdog timer
4. enable watchdog change
5. write watchdog value
6. restore SREG (restoring irq status)
*/
#define WD_SET(val,...) \
__asm__ __volatile__( \
"in __tmp_reg__,__SREG__" "\n\t" \
"cli" "\n\t" \
"wdr" "\n\t" \
"sts %[wdreg],%[wden]" "\n\t" \
"sts %[wdreg],%[wdval]" "\n\t" \
"out __SREG__,__tmp_reg__" "\n\t" \
: \
: [wdreg] "M" (&WDTCSR), \
[wden] "r" ((uint8_t)(0x18)), \
[wdval] "r" ((uint8_t)(val|(__VA_ARGS__+0))) \
: "r0" \
)
/*set the watchdog when I bit in SREG known to be clear-
1. reset watchdog timer
2. enable watchdog change
5. write watchdog value
*/
#define WD_SET_UNSAFE(val,...) \
__asm__ __volatile__( \
"wdr" "\n\t" \
"sts %[wdreg],%[wden]" "\n\t" \
"sts %[wdreg],%[wdval]" "\n\t" \
: \
: [wdreg] "M" (&WDTCSR), \
[wden] "r" ((uint8_t)(0x18)), \
[wdval] "r" ((uint8_t)(val|(__VA_ARGS__+0))) \
)
//for compatibility with avr/wdt.h
#define wdt_enable(val) WD_SET(WD_RST,val)
#define wdt_disable() WD_SET(WD_OFF)
#endif /* _AVR_WD_H_ */

50
protocol/lufa.mk Normal file
View file

@ -0,0 +1,50 @@
LUFA_DIR = protocol/lufa
# Path to the LUFA library
ifeq (, $(wildcard $(TMK_DIR)/$(LUFA_DIR)/LUFA-git/LUFA/Version.h))
LUFA_PATH ?= $(LUFA_DIR)/LUFA-120730
else
LUFA_PATH ?= $(LUFA_DIR)/LUFA-git
endif
# Create the LUFA source path variables by including the LUFA makefile
ifneq (, $(wildcard $(TMK_DIR)/$(LUFA_PATH)/LUFA/Build/lufa_sources.mk))
# New build system from 20120730
LUFA_ROOT_PATH = $(LUFA_PATH)/LUFA
include $(TMK_DIR)/$(LUFA_PATH)/LUFA/Build/lufa_sources.mk
else
include $(TMK_DIR)/$(LUFA_PATH)/LUFA/makefile
endif
LUFA_SRC = $(LUFA_DIR)/lufa.c \
$(LUFA_DIR)/descriptor.c \
$(LUFA_SRC_USB)
SRC += $(LUFA_SRC)
# Search Path
VPATH += $(TMK_DIR)/$(LUFA_DIR)
VPATH += $(TMK_DIR)/$(LUFA_PATH)
# Option modules
#ifdef $(or MOUSEKEY_ENABLE, PS2_MOUSE_ENABLE)
#endif
#ifdef EXTRAKEY_ENABLE
#endif
# LUFA library compile-time options and predefined tokens
LUFA_OPTS = -DUSB_DEVICE_ONLY
LUFA_OPTS += -DUSE_FLASH_DESCRIPTORS
LUFA_OPTS += -DUSE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
#LUFA_OPTS += -DINTERRUPT_CONTROL_ENDPOINT
LUFA_OPTS += -DFIXED_CONTROL_ENDPOINT_SIZE=8
LUFA_OPTS += -DFIXED_NUM_CONFIGURATIONS=1
OPT_DEFS += -DF_USB=$(F_USB)UL
OPT_DEFS += -DARCH=ARCH_$(ARCH)
OPT_DEFS += $(LUFA_OPTS)
# This indicates using LUFA stack
OPT_DEFS += -DPROTOCOL_LUFA

View file

@ -0,0 +1,61 @@
/*
LUFA Library
Copyright (C) Dean Camera, 2012.
dean [at] fourwalledcubicle [dot] com
www.lufa-lib.org
*/
/*
Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaim all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
/** \file
*
* Special application to extract an EEPROM image stored in FLASH memory, and
* copy it to the device EEPROM. This application is designed to be used with
* the HID build system module of LUFA to program the EEPROM of a target device
* that uses the HID bootloader protocol, which does not have native EEPROM
* programming support.
*/
#include <avr/io.h>
#include <avr/eeprom.h>
#include <avr/pgmspace.h>
/* References to the binary EEPROM data linked in the AVR's FLASH memory space */
extern const char _binary_InputEEData_bin_start[];
extern const char _binary_InputEEData_bin_end[];
extern const char _binary_InputEEData_bin_size[];
/* Friendly names for the embedded binary data stored in FLASH memory space */
#define InputEEData _binary_InputEEData_bin_start
#define InputEEData_size ((int)_binary_InputEEData_bin_size)
int main(void)
{
/* Copy out the embedded EEPROM data from FLASH to EEPROM memory space */
for (uint16_t i = 0; i < InputEEData_size; i++)
eeprom_update_byte((uint8_t*)i, pgm_read_byte(&InputEEData[i]));
/* Infinite loop once complete */
for (;;);
}

View file

@ -0,0 +1,40 @@
#
# LUFA Library
# Copyright (C) Dean Camera, 2012.
#
# dean [at] fourwalledcubicle [dot] com
# www.lufa-lib.org
#
# --------------------------------------
# LUFA Project Makefile.
# --------------------------------------
MCU = at90usb1287
ARCH = AVR8
F_CPU = 1000000
F_USB = $(F_CPU)
OPTIMIZATION = s
TARGET = HID_EEPROM_Loader
SRC = $(TARGET).c
LUFA_PATH = ../../../LUFA
CC_FLAGS =
LD_FLAGS =
OBJECT_FILES = InputEEData.o
# Default target
all:
# Determine the AVR sub-architecture of the build main application object file
FIND_AVR_SUBARCH = avr$(shell avr-objdump -f $(TARGET).o | grep architecture | cut -d':' -f3 | cut -d',' -f1)
# Create a linkable object file with the input binary EEPROM data stored in the FLASH section
InputEEData.o: InputEEData.bin $(TARGET).o $(MAKEFILE_LIST)
@echo $(MSG_OBJCPY_CMD) Converting \"$<\" to a object file \"$@\"
avr-objcopy -I binary -O elf32-avr -B $(call FIND_AVR_SUBARCH) --rename-section .data=.progmem.data,contents,alloc,readonly,data $< $@
# Include LUFA build script makefiles
include $(LUFA_PATH)/Build/lufa_core.mk
include $(LUFA_PATH)/Build/lufa_build.mk
include $(LUFA_PATH)/Build/lufa_cppcheck.mk
include $(LUFA_PATH)/Build/lufa_doxygen.mk
include $(LUFA_PATH)/Build/lufa_hid.mk

View file

@ -0,0 +1,101 @@
#
# LUFA Library
# Copyright (C) Dean Camera, 2012.
#
# dean [at] fourwalledcubicle [dot] com
# www.lufa-lib.org
#
LUFA_BUILD_MODULES += ATPROGRAM
LUFA_BUILD_TARGETS += atprogram atprogram-ee
LUFA_BUILD_MANDATORY_VARS += MCU TARGET
LUFA_BUILD_OPTIONAL_VARS += ATPROGRAM_PROGRAMMER ATPROGRAM_INTERFACE ATPROGRAM_PORT
LUFA_BUILD_PROVIDED_VARS +=
LUFA_BUILD_PROVIDED_MACROS +=
# -----------------------------------------------------------------------------
# LUFA ATPROGRAM Programmer Buildsystem Makefile Module.
# -----------------------------------------------------------------------------
# DESCRIPTION:
# Provides a set of targets to re-program a device using the Atmel atprogram
# utility in AVR Studio 5.x and Atmel Studio 6.0 onwards.
# -----------------------------------------------------------------------------
# TARGETS:
#
# atprogram - Program target FLASH with application using
# atprogram
# atprogram-ee - Program target EEPROM with application data
# using atprogram
#
# MANDATORY PARAMETERS:
#
# MCU - Microcontroller device model name
# TARGET - Application name
#
# OPTIONAL PARAMETERS:
#
# ATPROGRAM_PROGRAMMER - Name of programming hardware to use
# ATPROGRAM_INTERFACE - Name of programming interface to use
# ATPROGRAM_PORT - Name of communication port to use
#
# PROVIDED VARIABLES:
#
# (None)
#
# PROVIDED MACROS:
#
# (None)
#
# -----------------------------------------------------------------------------
SHELL = /bin/sh
ERROR_IF_UNSET ?= $(if $(filter undefined, $(origin $(strip $(1)))), $(error Makefile $(strip $(1)) value not set))
ERROR_IF_EMPTY ?= $(if $(strip $($(strip $(1)))), , $(error Makefile $(strip $(1)) option cannot be blank))
ERROR_IF_NONBOOL ?= $(if $(filter Y N, $($(strip $(1)))), , $(error Makefile $(strip $(1)) option must be Y or N))
# Default values of optionally user-supplied variables
ATPROGRAM_PROGRAMMER ?= jtagice3
ATPROGRAM_INTERFACE ?= jtag
ATPROGRAM_PORT ?=
# Sanity check user supplied values
$(foreach MANDATORY_VAR, $(LUFA_BUILD_MANDATORY_VARS), $(call ERROR_IF_UNSET, $(MANDATORY_VAR)))
$(call ERROR_IF_EMPTY, MCU)
$(call ERROR_IF_EMPTY, TARGET)
$(call ERROR_IF_EMPTY, ATPROGRAM_PROGRAMMER)
$(call ERROR_IF_EMPTY, ATPROGRAM_INTERFACE)
# Output Messages
MSG_ATPROGRAM_CMD := ' [ATPRGRM] :'
# Construct base atprogram command flags
BASE_ATPROGRAM_FLAGS := --tool $(ATPROGRAM_PROGRAMMER) --interface $(ATPROGRAM_INTERFACE) --device $(MCU)
ifneq ($(ATPROGRAM_PORT),)
BASE_ATPROGRAM_FLAGS += --port $(ATPROGRAM_PORT)
endif
# Construct the flags to use for the various memory spaces
ifeq ($(ARCH), AVR8)
ATPROGRAM_FLASH_FLAGS := --chiperase --flash
ATPROGRAM_EEPROM_FLAGS := --eeprom
else ifeq ($(ARCH), XMEGA)
ATPROGRAM_FLASH_FLAGS := --erase --flash
ATPROGRAM_EEPROM_FLAGS := --eeprom
else ifeq ($(ARCH), UC3)
ATPROGRAM_FLASH_FLAGS := --erase
ATPROGRAM_EEPROM_FLAGS := --eeprom
else
$(error Unsupported architecture "$(ARCH)")
endif
atprogram: $(TARGET).elf $(MAKEFILE_LIST)
@echo $(MSG_ATPROGRAM_CMD) Programming device \"$(MCU)\" FLASH using \"$(ATPROGRAM_PROGRAMMER)\"
atprogram $(BASE_ATPROGRAM_FLAGS) program $(ATPROGRAM_FLASH_FLAGS) --file $<
atprogram-ee: $(TARGET).elf $(MAKEFILE_LIST)
@echo $(MSG_ATPROGRAM_CMD) Programming device \"$(MCU)\" EEPROM using \"$(ATPROGRAM_PROGRAMMER)\"
atprogram $(BASE_ATPROGRAM_FLAGS) program $(ATPROGRAM_EEPROM_FLAGS) --file $<
# Phony build targets for this module
.PHONY: atprogram atprogram-ee

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