aboutsummaryrefslogtreecommitdiff
path: root/tmk_core
diff options
context:
space:
mode:
authorZay950 <Zay950@users.noreply.github.com>2017-03-29 12:00:38 -0700
committerGitHub <noreply@github.com>2017-03-29 12:00:38 -0700
commit2366ebfbbdeb6ec29cc9a0facda44d666305dd6e (patch)
tree883efed0b7260f3143f5a2a879bc3844a8255e0b /tmk_core
parent80c5ada3394c5ad8087df00ef878eb2cbcd87d70 (diff)
parent942f2ccee44bdb2e251553e9730cd8d59307d8b2 (diff)
downloadqmk_firmware-2366ebfbbdeb6ec29cc9a0facda44d666305dd6e.tar.gz
qmk_firmware-2366ebfbbdeb6ec29cc9a0facda44d666305dd6e.zip
Merge branch 'master' into to_push
Diffstat (limited to 'tmk_core')
-rw-r--r--tmk_core/avr.mk2
-rw-r--r--tmk_core/common.mk24
-rw-r--r--tmk_core/common/action.c29
-rw-r--r--tmk_core/common/action_code.h10
-rw-r--r--tmk_core/common/action_layer.c12
-rw-r--r--tmk_core/common/action_layer.h5
-rw-r--r--tmk_core/common/action_macro.h26
-rw-r--r--tmk_core/common/action_tapping.c11
-rw-r--r--tmk_core/common/avr/bootloader.c12
-rw-r--r--tmk_core/common/avr/suspend.c11
-rw-r--r--tmk_core/common/avr/timer.c69
-rw-r--r--tmk_core/common/backlight.c4
-rw-r--r--tmk_core/common/command.c9
-rw-r--r--tmk_core/common/host_driver.h9
-rw-r--r--tmk_core/common/keyboard.c9
-rw-r--r--tmk_core/common/keycode.h2
-rw-r--r--tmk_core/common/matrix.h2
-rw-r--r--tmk_core/common/raw_hid.h8
-rw-r--r--tmk_core/common/report.h7
-rw-r--r--tmk_core/protocol/lufa.mk13
-rw-r--r--tmk_core/protocol/lufa/adafruit_ble.cpp805
-rw-r--r--tmk_core/protocol/lufa/adafruit_ble.h60
-rw-r--r--tmk_core/protocol/lufa/descriptor.c98
-rw-r--r--tmk_core/protocol/lufa/descriptor.h35
-rw-r--r--tmk_core/protocol/lufa/lufa.c305
-rw-r--r--tmk_core/protocol/lufa/lufa.h17
-rw-r--r--tmk_core/protocol/lufa/outputselect.c56
-rw-r--r--tmk_core/protocol/lufa/outputselect.h40
-rw-r--r--tmk_core/protocol/lufa/ringbuffer.hpp66
-rw-r--r--tmk_core/protocol/midi.mk1
-rw-r--r--tmk_core/protocol/ps2_mouse.c330
-rw-r--r--tmk_core/protocol/ps2_mouse.h132
-rw-r--r--tmk_core/protocol/vusb.mk3
-rw-r--r--tmk_core/protocol/vusb/main.c6
-rw-r--r--tmk_core/protocol/vusb/vusb.c22
-rw-r--r--tmk_core/ring_buffer.h26
36 files changed, 1948 insertions, 328 deletions
diff --git a/tmk_core/avr.mk b/tmk_core/avr.mk
index b48173341..5df539def 100644
--- a/tmk_core/avr.mk
+++ b/tmk_core/avr.mk
@@ -26,7 +26,7 @@ CFLAGS += -fno-inline-small-functions
26CFLAGS += -fno-strict-aliasing 26CFLAGS += -fno-strict-aliasing
27 27
28CPPFLAGS += $(COMPILEFLAGS) 28CPPFLAGS += $(COMPILEFLAGS)
29CPPFLAGS += -fno-exceptions 29CPPFLAGS += -fno-exceptions -std=c++11
30 30
31LDFLAGS +=-Wl,--gc-sections 31LDFLAGS +=-Wl,--gc-sections
32 32
diff --git a/tmk_core/common.mk b/tmk_core/common.mk
index f826a7b54..47f6fc571 100644
--- a/tmk_core/common.mk
+++ b/tmk_core/common.mk
@@ -50,6 +50,10 @@ ifeq ($(strip $(EXTRAKEY_ENABLE)), yes)
50 TMK_COMMON_DEFS += -DEXTRAKEY_ENABLE 50 TMK_COMMON_DEFS += -DEXTRAKEY_ENABLE
51endif 51endif
52 52
53ifeq ($(strip $(RAW_ENABLE)), yes)
54 TMK_COMMON_DEFS += -DRAW_ENABLE
55endif
56
53ifeq ($(strip $(CONSOLE_ENABLE)), yes) 57ifeq ($(strip $(CONSOLE_ENABLE)), yes)
54 TMK_COMMON_DEFS += -DCONSOLE_ENABLE 58 TMK_COMMON_DEFS += -DCONSOLE_ENABLE
55else 59else
@@ -76,6 +80,14 @@ ifeq ($(strip $(SLEEP_LED_ENABLE)), yes)
76 TMK_COMMON_DEFS += -DNO_SUSPEND_POWER_DOWN 80 TMK_COMMON_DEFS += -DNO_SUSPEND_POWER_DOWN
77endif 81endif
78 82
83ifeq ($(strip $(NO_UART)), yes)
84 TMK_COMMON_DEFS += -DNO_UART
85endif
86
87ifeq ($(strip $(NO_SUSPEND_POWER_DOWN)), yes)
88 TMK_COMMON_DEFS += -DNO_SUSPEND_POWER_DOWN
89endif
90
79ifeq ($(strip $(BACKLIGHT_ENABLE)), yes) 91ifeq ($(strip $(BACKLIGHT_ENABLE)), yes)
80 TMK_COMMON_SRC += $(COMMON_DIR)/backlight.c 92 TMK_COMMON_SRC += $(COMMON_DIR)/backlight.c
81 TMK_COMMON_DEFS += -DBACKLIGHT_ENABLE 93 TMK_COMMON_DEFS += -DBACKLIGHT_ENABLE
@@ -85,6 +97,16 @@ ifeq ($(strip $(BLUETOOTH_ENABLE)), yes)
85 TMK_COMMON_DEFS += -DBLUETOOTH_ENABLE 97 TMK_COMMON_DEFS += -DBLUETOOTH_ENABLE
86endif 98endif
87 99
100ifeq ($(strip $(BLUETOOTH)), AdafruitBLE)
101 TMK_COMMON_DEFS += -DBLUETOOTH_ENABLE
102 TMK_COMMON_DEFS += -DMODULE_ADAFRUIT_BLE
103endif
104
105ifeq ($(strip $(BLUETOOTH)), AdafruitEZKey)
106 TMK_COMMON_DEFS += -DBLUETOOTH_ENABLE
107 TMK_COMMON_DEFS += -DMODULE_ADAFRUIT_EZKEY
108endif
109
88ifeq ($(strip $(ONEHAND_ENABLE)), yes) 110ifeq ($(strip $(ONEHAND_ENABLE)), yes)
89 TMK_COMMON_DEFS += -DONEHAND_ENABLE 111 TMK_COMMON_DEFS += -DONEHAND_ENABLE
90endif 112endif
@@ -110,4 +132,4 @@ endif
110VPATH += $(TMK_PATH)/$(COMMON_DIR) 132VPATH += $(TMK_PATH)/$(COMMON_DIR)
111ifeq ($(PLATFORM),CHIBIOS) 133ifeq ($(PLATFORM),CHIBIOS)
112VPATH += $(TMK_PATH)/$(COMMON_DIR)/chibios 134VPATH += $(TMK_PATH)/$(COMMON_DIR)/chibios
113endif \ No newline at end of file 135endif
diff --git a/tmk_core/common/action.c b/tmk_core/common/action.c
index d485b46c7..94de36918 100644
--- a/tmk_core/common/action.c
+++ b/tmk_core/common/action.c
@@ -33,6 +33,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
33#include "nodebug.h" 33#include "nodebug.h"
34#endif 34#endif
35 35
36#ifdef FAUXCLICKY_ENABLE
37#include <fauxclicky.h>
38#endif
36 39
37void action_exec(keyevent_t event) 40void action_exec(keyevent_t event)
38{ 41{
@@ -41,6 +44,16 @@ void action_exec(keyevent_t event)
41 dprint("EVENT: "); debug_event(event); dprintln(); 44 dprint("EVENT: "); debug_event(event); dprintln();
42 } 45 }
43 46
47#ifdef FAUXCLICKY_ENABLE
48 if (IS_PRESSED(event)) {
49 FAUXCLICKY_ACTION_PRESS;
50 }
51 if (IS_RELEASED(event)) {
52 FAUXCLICKY_ACTION_RELEASE;
53 }
54 fauxclicky_check();
55#endif
56
44#ifdef ONEHAND_ENABLE 57#ifdef ONEHAND_ENABLE
45 if (!IS_NOEVENT(event)) { 58 if (!IS_NOEVENT(event)) {
46 process_hand_swap(&event); 59 process_hand_swap(&event);
@@ -49,6 +62,13 @@ void action_exec(keyevent_t event)
49 62
50 keyrecord_t record = { .event = event }; 63 keyrecord_t record = { .event = event };
51 64
65#if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0))
66 if (has_oneshot_layer_timed_out()) {
67 dprintf("Oneshot layer: timeout\n");
68 clear_oneshot_layer_state(ONESHOT_OTHER_KEY_PRESSED);
69 }
70#endif
71
52#ifndef NO_ACTION_TAPPING 72#ifndef NO_ACTION_TAPPING
53 action_tapping_process(record); 73 action_tapping_process(record);
54#else 74#else
@@ -100,7 +120,7 @@ bool process_record_quantum(keyrecord_t *record) {
100 return true; 120 return true;
101} 121}
102 122
103void process_record(keyrecord_t *record) 123void process_record(keyrecord_t *record)
104{ 124{
105 if (IS_NOEVENT(record->event)) { return; } 125 if (IS_NOEVENT(record->event)) { return; }
106 126
@@ -126,13 +146,6 @@ void process_action(keyrecord_t *record, action_t action)
126 uint8_t tap_count = record->tap.count; 146 uint8_t tap_count = record->tap.count;
127#endif 147#endif
128 148
129#if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0))
130 if (has_oneshot_layer_timed_out()) {
131 dprintf("Oneshot layer: timeout\n");
132 clear_oneshot_layer_state(ONESHOT_OTHER_KEY_PRESSED);
133 }
134#endif
135
136 if (event.pressed) { 149 if (event.pressed) {
137 // clear the potential weak mods left by previously pressed keys 150 // clear the potential weak mods left by previously pressed keys
138 clear_weak_mods(); 151 clear_weak_mods();
diff --git a/tmk_core/common/action_code.h b/tmk_core/common/action_code.h
index 33da35f35..b15aaa0eb 100644
--- a/tmk_core/common/action_code.h
+++ b/tmk_core/common/action_code.h
@@ -47,10 +47,15 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
47 * 0100|10| usage(10) (reserved) 47 * 0100|10| usage(10) (reserved)
48 * 0100|11| usage(10) (reserved) 48 * 0100|11| usage(10) (reserved)
49 * 49 *
50 * ACT_MOUSEKEY(0110): TODO: Not needed? 50 *
51 * ACT_MOUSEKEY(0101): TODO: Merge these two actions to conserve space?
51 * 0101|xxxx| keycode Mouse key 52 * 0101|xxxx| keycode Mouse key
52 * 53 *
53 * 011x|xxxx xxxx xxxx (reseved) 54 * ACT_SWAP_HANDS(0110):
55 * 0110|xxxx| keycode Swap hands (keycode on tap, or options)
56 *
57 *
58 * 0111|xxxx xxxx xxxx (reserved)
54 * 59 *
55 * 60 *
56 * Layer Actions(10xx) 61 * Layer Actions(10xx)
@@ -67,7 +72,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
67 * ee: on event(01:press, 10:release, 11:both) 72 * ee: on event(01:press, 10:release, 11:both)
68 * 73 *
69 * 1001|xxxx|xxxx xxxx (reserved) 74 * 1001|xxxx|xxxx xxxx (reserved)
70 * 1001|oopp|BBBB BBBB 8-bit Bitwise Operation???
71 * 75 *
72 * ACT_LAYER_TAP(101x): 76 * ACT_LAYER_TAP(101x):
73 * 101E|LLLL| keycode On/Off with tap key (0x00-DF)[TAP] 77 * 101E|LLLL| keycode On/Off with tap key (0x00-DF)[TAP]
diff --git a/tmk_core/common/action_layer.c b/tmk_core/common/action_layer.c
index a3c757964..58d919a04 100644
--- a/tmk_core/common/action_layer.c
+++ b/tmk_core/common/action_layer.c
@@ -16,8 +16,14 @@
16 */ 16 */
17uint32_t default_layer_state = 0; 17uint32_t default_layer_state = 0;
18 18
19__attribute__((weak))
20uint32_t default_layer_state_set_kb(uint32_t state) {
21 return state;
22}
23
19static void default_layer_state_set(uint32_t state) 24static void default_layer_state_set(uint32_t state)
20{ 25{
26 state = default_layer_state_set_kb(state);
21 debug("default_layer_state: "); 27 debug("default_layer_state: ");
22 default_layer_debug(); debug(" to "); 28 default_layer_debug(); debug(" to ");
23 default_layer_state = state; 29 default_layer_state = state;
@@ -57,8 +63,14 @@ void default_layer_xor(uint32_t state)
57 */ 63 */
58uint32_t layer_state = 0; 64uint32_t layer_state = 0;
59 65
66__attribute__((weak))
67uint32_t layer_state_set_kb(uint32_t state) {
68 return state;
69}
70
60static void layer_state_set(uint32_t state) 71static void layer_state_set(uint32_t state)
61{ 72{
73 state = layer_state_set_kb(state);
62 dprint("layer_state: "); 74 dprint("layer_state: ");
63 layer_debug(); dprint(" to "); 75 layer_debug(); dprint(" to ");
64 layer_state = state; 76 layer_state = state;
diff --git a/tmk_core/common/action_layer.h b/tmk_core/common/action_layer.h
index 025cf5420..d89ed6e5c 100644
--- a/tmk_core/common/action_layer.h
+++ b/tmk_core/common/action_layer.h
@@ -29,6 +29,9 @@ extern uint32_t default_layer_state;
29void default_layer_debug(void); 29void default_layer_debug(void);
30void default_layer_set(uint32_t state); 30void default_layer_set(uint32_t state);
31 31
32__attribute__((weak))
33uint32_t default_layer_state_set_kb(uint32_t state);
34
32#ifndef NO_ACTION_LAYER 35#ifndef NO_ACTION_LAYER
33/* bitwise operation */ 36/* bitwise operation */
34void default_layer_or(uint32_t state); 37void default_layer_or(uint32_t state);
@@ -69,6 +72,8 @@ void layer_xor(uint32_t state);
69#define layer_xor(state) 72#define layer_xor(state)
70#define layer_debug() 73#define layer_debug()
71 74
75__attribute__((weak))
76uint32_t layer_state_set_kb(uint32_t state);
72#endif 77#endif
73 78
74/* pressed actions cache */ 79/* pressed actions cache */
diff --git a/tmk_core/common/action_macro.h b/tmk_core/common/action_macro.h
index aedc32ec6..f373f5068 100644
--- a/tmk_core/common/action_macro.h
+++ b/tmk_core/common/action_macro.h
@@ -20,11 +20,33 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
20#include "progmem.h" 20#include "progmem.h"
21 21
22 22
23#define MACRO_NONE 0 23
24typedef uint8_t macro_t;
25
26#define MACRO_NONE (macro_t*)0
24#define MACRO(...) ({ static const macro_t __m[] PROGMEM = { __VA_ARGS__ }; &__m[0]; }) 27#define MACRO(...) ({ static const macro_t __m[] PROGMEM = { __VA_ARGS__ }; &__m[0]; })
25#define MACRO_GET(p) pgm_read_byte(p) 28#define MACRO_GET(p) pgm_read_byte(p)
26 29
27typedef uint8_t macro_t; 30// Sends press when the macro key is pressed, release when release, or tap_macro when the key has been tapped
31#define MACRO_TAP_HOLD(record, press, release, tap_macro) ( ((record)->event.pressed) ? \
32 ( ((record)->tap.count <= 0 || (record)->tap.interrupted) ? (press) : MACRO_NONE ) : \
33 ( ((record)->tap.count > 0 && !((record)->tap.interrupted)) ? (tap_macro) : (release) ) )
34
35// Holds down the modifier mod when the macro key is held, or sends macro instead when tapped
36#define MACRO_TAP_HOLD_MOD(record, macro, mod) MACRO_TAP_HOLD(record, (MACRO(D(mod), END)), MACRO(U(mod), END), macro)
37
38// Holds down the modifier mod when the macro key is held, or pressed a shifted key when tapped (eg: shift+3 for #)
39#define MACRO_TAP_SHFT_KEY_HOLD_MOD(record, key, mod) MACRO_TAP_HOLD_MOD(record, (MACRO(I(10), D(LSFT), T(key), U(LSFT), END)), mod)
40
41
42// Momentary switch layer when held, sends macro if tapped
43#define MACRO_TAP_HOLD_LAYER(record, macro, layer) ( ((record)->event.pressed) ? \
44 ( ((record)->tap.count <= 0 || (record)->tap.interrupted) ? ({layer_on((layer)); MACRO_NONE; }) : MACRO_NONE ) : \
45 ( ((record)->tap.count > 0 && !((record)->tap.interrupted)) ? (macro) : ({layer_off((layer)); MACRO_NONE; }) ) )
46
47// Momentary switch layer when held, presses a shifted key when tapped (eg: shift+3 for #)
48#define MACRO_TAP_SHFT_KEY_HOLD_LAYER(record, key, layer) MACRO_TAP_HOLD_LAYER(record, MACRO(I(10), D(LSFT), T(key), U(LSFT), END), layer)
49
28 50
29 51
30#ifndef NO_ACTION_MACRO 52#ifndef NO_ACTION_MACRO
diff --git a/tmk_core/common/action_tapping.c b/tmk_core/common/action_tapping.c
index e16e11be7..bd9a69ae0 100644
--- a/tmk_core/common/action_tapping.c
+++ b/tmk_core/common/action_tapping.c
@@ -228,6 +228,7 @@ bool process_tapping(keyrecord_t *keyp)
228 if (WITHIN_TAPPING_TERM(event)) { 228 if (WITHIN_TAPPING_TERM(event)) {
229 if (event.pressed) { 229 if (event.pressed) {
230 if (IS_TAPPING_KEY(event.key)) { 230 if (IS_TAPPING_KEY(event.key)) {
231#ifndef TAPPING_FORCE_HOLD
231 if (!tapping_key.tap.interrupted && tapping_key.tap.count > 0) { 232 if (!tapping_key.tap.interrupted && tapping_key.tap.count > 0) {
232 // sequential tap. 233 // sequential tap.
233 keyp->tap = tapping_key.tap; 234 keyp->tap = tapping_key.tap;
@@ -237,11 +238,11 @@ bool process_tapping(keyrecord_t *keyp)
237 tapping_key = *keyp; 238 tapping_key = *keyp;
238 debug_tapping_key(); 239 debug_tapping_key();
239 return true; 240 return true;
240 } else {
241 // FIX: start new tap again
242 tapping_key = *keyp;
243 return true;
244 } 241 }
242#endif
243 // FIX: start new tap again
244 tapping_key = *keyp;
245 return true;
245 } else if (is_tap_key(event.key)) { 246 } else if (is_tap_key(event.key)) {
246 // Sequential tap can be interfered with other tap key. 247 // Sequential tap can be interfered with other tap key.
247 debug("Tapping: Start with interfering other tap.\n"); 248 debug("Tapping: Start with interfering other tap.\n");
@@ -257,7 +258,7 @@ bool process_tapping(keyrecord_t *keyp)
257 return true; 258 return true;
258 } 259 }
259 } else { 260 } else {
260 if (!IS_NOEVENT(event)) debug("Tapping: other key just after tap.\n") {}; 261 if (!IS_NOEVENT(event)) debug("Tapping: other key just after tap.\n");
261 process_record(keyp); 262 process_record(keyp);
262 return true; 263 return true;
263 } 264 }
diff --git a/tmk_core/common/avr/bootloader.c b/tmk_core/common/avr/bootloader.c
index ad547b985..34db8d0b0 100644
--- a/tmk_core/common/avr/bootloader.c
+++ b/tmk_core/common/avr/bootloader.c
@@ -1,6 +1,7 @@
1#include <stdint.h> 1#include <stdint.h>
2#include <stdbool.h> 2#include <stdbool.h>
3#include <avr/io.h> 3#include <avr/io.h>
4#include <avr/eeprom.h>
4#include <avr/interrupt.h> 5#include <avr/interrupt.h>
5#include <avr/wdt.h> 6#include <avr/wdt.h>
6#include <util/delay.h> 7#include <util/delay.h>
@@ -89,6 +90,12 @@ void bootloader_jump(void) {
89 _delay_ms(5); 90 _delay_ms(5);
90 #endif 91 #endif
91 92
93 #ifdef BOOTLOADHID_BOOTLOADER
94 // force bootloadHID to stay in bootloader mode, so that it waits
95 // for a new firmware to be flashed
96 eeprom_write_byte((uint8_t *)1, 0x00);
97 #endif
98
92 // watchdog reset 99 // watchdog reset
93 reset_key = BOOTLOADER_RESET_KEY; 100 reset_key = BOOTLOADER_RESET_KEY;
94 wdt_enable(WDTO_250MS); 101 wdt_enable(WDTO_250MS);
@@ -114,6 +121,11 @@ void bootloader_jump(void) {
114 #endif 121 #endif
115} 122}
116 123
124#ifdef __AVR_ATmega32A__
125// MCUSR is actually called MCUCSR in ATmega32A
126#define MCUSR MCUCSR
127#endif
128
117/* this runs before main() */ 129/* this runs before main() */
118void bootloader_jump_after_watchdog_reset(void) __attribute__ ((used, naked, section (".init3"))); 130void bootloader_jump_after_watchdog_reset(void) __attribute__ ((used, naked, section (".init3")));
119void bootloader_jump_after_watchdog_reset(void) 131void bootloader_jump_after_watchdog_reset(void)
diff --git a/tmk_core/common/avr/suspend.c b/tmk_core/common/avr/suspend.c
index 8a7272bbc..0c81e8361 100644
--- a/tmk_core/common/avr/suspend.c
+++ b/tmk_core/common/avr/suspend.c
@@ -47,6 +47,7 @@ void suspend_idle(uint8_t time)
47 sleep_disable(); 47 sleep_disable();
48} 48}
49 49
50#ifndef NO_SUSPEND_POWER_DOWN
50/* Power down MCU with watchdog timer 51/* Power down MCU with watchdog timer
51 * wdto: watchdog timer timeout defined in <avr/wdt.h> 52 * wdto: watchdog timer timeout defined in <avr/wdt.h>
52 * WDTO_15MS 53 * WDTO_15MS
@@ -61,6 +62,7 @@ void suspend_idle(uint8_t time)
61 * WDTO_8S 62 * WDTO_8S
62 */ 63 */
63static uint8_t wdt_timeout = 0; 64static uint8_t wdt_timeout = 0;
65
64static void power_down(uint8_t wdto) 66static void power_down(uint8_t wdto)
65{ 67{
66#ifdef PROTOCOL_LUFA 68#ifdef PROTOCOL_LUFA
@@ -98,19 +100,19 @@ static void power_down(uint8_t wdto)
98 // Disable watchdog after sleep 100 // Disable watchdog after sleep
99 wdt_disable(); 101 wdt_disable();
100} 102}
103#endif
101 104
102void suspend_power_down(void) 105void suspend_power_down(void)
103{ 106{
107#ifndef NO_SUSPEND_POWER_DOWN
104 power_down(WDTO_15MS); 108 power_down(WDTO_15MS);
109#endif
105} 110}
106 111
107__attribute__ ((weak)) void matrix_power_up(void) {} 112__attribute__ ((weak)) void matrix_power_up(void) {}
108__attribute__ ((weak)) void matrix_power_down(void) {} 113__attribute__ ((weak)) void matrix_power_down(void) {}
109bool suspend_wakeup_condition(void) 114bool suspend_wakeup_condition(void)
110{ 115{
111#ifdef BACKLIGHT_ENABLE
112 backlight_set(0);
113#endif
114 matrix_power_up(); 116 matrix_power_up();
115 matrix_scan(); 117 matrix_scan();
116 matrix_power_down(); 118 matrix_power_down();
@@ -126,10 +128,9 @@ void suspend_wakeup_init(void)
126 // clear keyboard state 128 // clear keyboard state
127 clear_keyboard(); 129 clear_keyboard();
128#ifdef BACKLIGHT_ENABLE 130#ifdef BACKLIGHT_ENABLE
129 backlight_set(0);
130 backlight_init(); 131 backlight_init();
131#endif 132#endif
132led_set(host_keyboard_leds()); 133 led_set(host_keyboard_leds());
133} 134}
134 135
135#ifndef NO_SUSPEND_POWER_DOWN 136#ifndef NO_SUSPEND_POWER_DOWN
diff --git a/tmk_core/common/avr/timer.c b/tmk_core/common/avr/timer.c
index 292b41c3a..369015200 100644
--- a/tmk_core/common/avr/timer.c
+++ b/tmk_core/common/avr/timer.c
@@ -17,6 +17,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18#include <avr/io.h> 18#include <avr/io.h>
19#include <avr/interrupt.h> 19#include <avr/interrupt.h>
20#include <util/atomic.h>
20#include <stdint.h> 21#include <stdint.h>
21#include "timer_avr.h" 22#include "timer_avr.h"
22#include "timer.h" 23#include "timer.h"
@@ -24,38 +25,47 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
24 25
25// counter resolution 1ms 26// counter resolution 1ms
26// NOTE: union { uint32_t timer32; struct { uint16_t dummy; uint16_t timer16; }} 27// NOTE: union { uint32_t timer32; struct { uint16_t dummy; uint16_t timer16; }}
27volatile uint32_t timer_count = 0; 28volatile uint32_t timer_count;
28 29
29void timer_init(void) 30void timer_init(void)
30{ 31{
31 // Timer0 CTC mode
32 TCCR0A = 0x02;
33
34#if TIMER_PRESCALER == 1 32#if TIMER_PRESCALER == 1
35 TCCR0B = 0x01; 33 uint8_t prescaler = 0x01;
36#elif TIMER_PRESCALER == 8 34#elif TIMER_PRESCALER == 8
37 TCCR0B = 0x02; 35 uint8_t prescaler = 0x02;
38#elif TIMER_PRESCALER == 64 36#elif TIMER_PRESCALER == 64
39 TCCR0B = 0x03; 37 uint8_t prescaler = 0x03;
40#elif TIMER_PRESCALER == 256 38#elif TIMER_PRESCALER == 256
41 TCCR0B = 0x04; 39 uint8_t prescaler = 0x04;
42#elif TIMER_PRESCALER == 1024 40#elif TIMER_PRESCALER == 1024
43 TCCR0B = 0x05; 41 uint8_t prescaler = 0x05;
44#else 42#else
45# error "Timer prescaler value is NOT vaild." 43# error "Timer prescaler value is NOT vaild."
46#endif 44#endif
47 45
46#ifndef __AVR_ATmega32A__
47 // Timer0 CTC mode
48 TCCR0A = 0x02;
49
50 TCCR0B = prescaler;
51
48 OCR0A = TIMER_RAW_TOP; 52 OCR0A = TIMER_RAW_TOP;
49 TIMSK0 = (1<<OCIE0A); 53 TIMSK0 = (1<<OCIE0A);
54#else
55 // Timer0 CTC mode
56 TCCR0 = (1 << WGM01) | prescaler;
57
58 OCR0 = TIMER_RAW_TOP;
59 TIMSK = (1 << OCIE0);
60#endif
50} 61}
51 62
52inline 63inline
53void timer_clear(void) 64void timer_clear(void)
54{ 65{
55 uint8_t sreg = SREG; 66 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
56 cli();
57 timer_count = 0; 67 timer_count = 0;
58 SREG = sreg; 68 }
59} 69}
60 70
61inline 71inline
@@ -63,10 +73,9 @@ uint16_t timer_read(void)
63{ 73{
64 uint32_t t; 74 uint32_t t;
65 75
66 uint8_t sreg = SREG; 76 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
67 cli(); 77 t = timer_count;
68 t = timer_count; 78 }
69 SREG = sreg;
70 79
71 return (t & 0xFFFF); 80 return (t & 0xFFFF);
72} 81}
@@ -76,10 +85,9 @@ uint32_t timer_read32(void)
76{ 85{
77 uint32_t t; 86 uint32_t t;
78 87
79 uint8_t sreg = SREG; 88 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
80 cli(); 89 t = timer_count;
81 t = timer_count; 90 }
82 SREG = sreg;
83 91
84 return t; 92 return t;
85} 93}
@@ -89,10 +97,9 @@ uint16_t timer_elapsed(uint16_t last)
89{ 97{
90 uint32_t t; 98 uint32_t t;
91 99
92 uint8_t sreg = SREG; 100 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
93 cli(); 101 t = timer_count;
94 t = timer_count; 102 }
95 SREG = sreg;
96 103
97 return TIMER_DIFF_16((t & 0xFFFF), last); 104 return TIMER_DIFF_16((t & 0xFFFF), last);
98} 105}
@@ -102,16 +109,20 @@ uint32_t timer_elapsed32(uint32_t last)
102{ 109{
103 uint32_t t; 110 uint32_t t;
104 111
105 uint8_t sreg = SREG; 112 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
106 cli(); 113 t = timer_count;
107 t = timer_count; 114 }
108 SREG = sreg;
109 115
110 return TIMER_DIFF_32(t, last); 116 return TIMER_DIFF_32(t, last);
111} 117}
112 118
113// excecuted once per 1ms.(excess for just timer count?) 119// excecuted once per 1ms.(excess for just timer count?)
114ISR(TIMER0_COMPA_vect) 120#ifndef __AVR_ATmega32A__
121#define TIMER_INTERRUPT_VECTOR TIMER0_COMPA_vect
122#else
123#define TIMER_INTERRUPT_VECTOR TIMER0_COMP_vect
124#endif
125ISR(TIMER_INTERRUPT_VECTOR, ISR_NOBLOCK)
115{ 126{
116 timer_count++; 127 timer_count++;
117} 128}
diff --git a/tmk_core/common/backlight.c b/tmk_core/common/backlight.c
index c9e8fd3fd..0e0ad2d15 100644
--- a/tmk_core/common/backlight.c
+++ b/tmk_core/common/backlight.c
@@ -36,9 +36,9 @@ void backlight_increase(void)
36 if(backlight_config.level < BACKLIGHT_LEVELS) 36 if(backlight_config.level < BACKLIGHT_LEVELS)
37 { 37 {
38 backlight_config.level++; 38 backlight_config.level++;
39 backlight_config.enable = 1;
40 eeconfig_update_backlight(backlight_config.raw);
41 } 39 }
40 backlight_config.enable = 1;
41 eeconfig_update_backlight(backlight_config.raw);
42 dprintf("backlight increase: %u\n", backlight_config.level); 42 dprintf("backlight increase: %u\n", backlight_config.level);
43 backlight_set(backlight_config.level); 43 backlight_set(backlight_config.level);
44} 44}
diff --git a/tmk_core/common/command.c b/tmk_core/common/command.c
index f3e1bf623..f79d5a257 100644
--- a/tmk_core/common/command.c
+++ b/tmk_core/common/command.c
@@ -235,8 +235,11 @@ static void print_status(void)
235 print("\n\t- Status -\n"); 235 print("\n\t- Status -\n");
236 236
237 print_val_hex8(host_keyboard_leds()); 237 print_val_hex8(host_keyboard_leds());
238#ifndef PROTOCOL_VUSB
239 // these aren't set on the V-USB protocol, so we just ignore them for now
238 print_val_hex8(keyboard_protocol); 240 print_val_hex8(keyboard_protocol);
239 print_val_hex8(keyboard_idle); 241 print_val_hex8(keyboard_idle);
242#endif
240#ifdef NKRO_ENABLE 243#ifdef NKRO_ENABLE
241 print_val_hex8(keymap_config.nkro); 244 print_val_hex8(keymap_config.nkro);
242#endif 245#endif
@@ -379,11 +382,11 @@ static bool command_common(uint8_t code)
379 debug_enable = !debug_enable; 382 debug_enable = !debug_enable;
380 if (debug_enable) { 383 if (debug_enable) {
381 print("\ndebug: on\n"); 384 print("\ndebug: on\n");
382 debug_matrix = true;
383 debug_keyboard = true;
384 debug_mouse = true;
385 } else { 385 } else {
386 print("\ndebug: off\n"); 386 print("\ndebug: off\n");
387 debug_matrix = false;
388 debug_keyboard = false;
389 debug_mouse = false;
387 } 390 }
388 break; 391 break;
389 392
diff --git a/tmk_core/common/host_driver.h b/tmk_core/common/host_driver.h
index edb9e5dd9..588d1c0be 100644
--- a/tmk_core/common/host_driver.h
+++ b/tmk_core/common/host_driver.h
@@ -20,7 +20,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
20 20
21#include <stdint.h> 21#include <stdint.h>
22#include "report.h" 22#include "report.h"
23 23#ifdef MIDI_ENABLE
24 #include "midi.h"
25#endif
24 26
25typedef struct { 27typedef struct {
26 uint8_t (*keyboard_leds)(void); 28 uint8_t (*keyboard_leds)(void);
@@ -28,6 +30,11 @@ typedef struct {
28 void (*send_mouse)(report_mouse_t *); 30 void (*send_mouse)(report_mouse_t *);
29 void (*send_system)(uint16_t); 31 void (*send_system)(uint16_t);
30 void (*send_consumer)(uint16_t); 32 void (*send_consumer)(uint16_t);
33#ifdef MIDI_ENABLE
34 void (*usb_send_func)(MidiDevice *, uint16_t, uint8_t, uint8_t, uint8_t);
35 void (*usb_get_midi)(MidiDevice *);
36 void (*midi_usb_init)(MidiDevice *);
37#endif
31} host_driver_t; 38} host_driver_t;
32 39
33#endif 40#endif
diff --git a/tmk_core/common/keyboard.c b/tmk_core/common/keyboard.c
index 371d93f3e..eac1f1dd8 100644
--- a/tmk_core/common/keyboard.c
+++ b/tmk_core/common/keyboard.c
@@ -14,6 +14,7 @@ GNU General Public License for more details.
14You should have received a copy of the GNU General Public License 14You should have received a copy of the GNU General Public License
15along with this program. If not, see <http://www.gnu.org/licenses/>. 15along with this program. If not, see <http://www.gnu.org/licenses/>.
16*/ 16*/
17
17#include <stdint.h> 18#include <stdint.h>
18#include "keyboard.h" 19#include "keyboard.h"
19#include "matrix.h" 20#include "matrix.h"
@@ -50,6 +51,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
50#ifdef RGBLIGHT_ENABLE 51#ifdef RGBLIGHT_ENABLE
51# include "rgblight.h" 52# include "rgblight.h"
52#endif 53#endif
54#ifdef FAUXCLICKY_ENABLE
55# include "fauxclicky.h"
56#endif
53#ifdef SERIAL_LINK_ENABLE 57#ifdef SERIAL_LINK_ENABLE
54# include "serial_link/system/serial_link.h" 58# include "serial_link/system/serial_link.h"
55#endif 59#endif
@@ -107,6 +111,9 @@ void keyboard_init(void) {
107#ifdef RGBLIGHT_ENABLE 111#ifdef RGBLIGHT_ENABLE
108 rgblight_init(); 112 rgblight_init();
109#endif 113#endif
114#ifdef FAUXCLICKY_ENABLE
115 fauxclicky_init();
116#endif
110#if defined(NKRO_ENABLE) && defined(FORCE_NKRO) 117#if defined(NKRO_ENABLE) && defined(FORCE_NKRO)
111 keymap_config.nkro = 1; 118 keymap_config.nkro = 1;
112#endif 119#endif
@@ -188,7 +195,7 @@ MATRIX_LOOP_END:
188#endif 195#endif
189 196
190#ifdef VISUALIZER_ENABLE 197#ifdef VISUALIZER_ENABLE
191 visualizer_update(default_layer_state, layer_state, host_keyboard_leds()); 198 visualizer_update(default_layer_state, layer_state, visualizer_get_mods(), host_keyboard_leds());
192#endif 199#endif
193 200
194 // update LED 201 // update LED
diff --git a/tmk_core/common/keycode.h b/tmk_core/common/keycode.h
index 2f208c54e..54e9c322c 100644
--- a/tmk_core/common/keycode.h
+++ b/tmk_core/common/keycode.h
@@ -85,7 +85,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
85#define KC_LCAP KC_LOCKING_CAPS 85#define KC_LCAP KC_LOCKING_CAPS
86#define KC_LNUM KC_LOCKING_NUM 86#define KC_LNUM KC_LOCKING_NUM
87#define KC_LSCR KC_LOCKING_SCROLL 87#define KC_LSCR KC_LOCKING_SCROLL
88#define KC_ERAS KC_ALT_ERASE, 88#define KC_ERAS KC_ALT_ERASE
89#define KC_CLR KC_CLEAR 89#define KC_CLR KC_CLEAR
90/* Japanese specific */ 90/* Japanese specific */
91#define KC_ZKHK KC_GRAVE 91#define KC_ZKHK KC_GRAVE
diff --git a/tmk_core/common/matrix.h b/tmk_core/common/matrix.h
index cee3593ee..2543f5abc 100644
--- a/tmk_core/common/matrix.h
+++ b/tmk_core/common/matrix.h
@@ -50,7 +50,7 @@ void matrix_init(void);
50uint8_t matrix_scan(void); 50uint8_t matrix_scan(void);
51/* whether modified from previous scan. used after matrix_scan. */ 51/* whether modified from previous scan. used after matrix_scan. */
52bool matrix_is_modified(void) __attribute__ ((deprecated)); 52bool matrix_is_modified(void) __attribute__ ((deprecated));
53/* whether a swtich is on */ 53/* whether a switch is on */
54bool matrix_is_on(uint8_t row, uint8_t col); 54bool matrix_is_on(uint8_t row, uint8_t col);
55/* matrix state on row */ 55/* matrix state on row */
56matrix_row_t matrix_get_row(uint8_t row); 56matrix_row_t matrix_get_row(uint8_t row);
diff --git a/tmk_core/common/raw_hid.h b/tmk_core/common/raw_hid.h
new file mode 100644
index 000000000..86da02fd1
--- /dev/null
+++ b/tmk_core/common/raw_hid.h
@@ -0,0 +1,8 @@
1#ifndef _RAW_HID_H_
2#define _RAW_HID_H_
3
4void raw_hid_receive( uint8_t *data, uint8_t length );
5
6void raw_hid_send( uint8_t *data, uint8_t length );
7
8#endif
diff --git a/tmk_core/common/report.h b/tmk_core/common/report.h
index 0c799eca3..8fb28b6ce 100644
--- a/tmk_core/common/report.h
+++ b/tmk_core/common/report.h
@@ -134,13 +134,6 @@ typedef union {
134 } nkro; 134 } nkro;
135#endif 135#endif
136} __attribute__ ((packed)) report_keyboard_t; 136} __attribute__ ((packed)) report_keyboard_t;
137/*
138typedef struct {
139 uint8_t mods;
140 uint8_t reserved;
141 uint8_t keys[REPORT_KEYS];
142} __attribute__ ((packed)) report_keyboard_t;
143*/
144 137
145typedef struct { 138typedef struct {
146 uint8_t buttons; 139 uint8_t buttons;
diff --git a/tmk_core/protocol/lufa.mk b/tmk_core/protocol/lufa.mk
index 5b1e3d19d..5b1577972 100644
--- a/tmk_core/protocol/lufa.mk
+++ b/tmk_core/protocol/lufa.mk
@@ -8,13 +8,14 @@ LUFA_PATH ?= $(LUFA_DIR)/LUFA-git
8ifneq (, $(wildcard $(TMK_PATH)/$(LUFA_PATH)/LUFA/Build/lufa_sources.mk)) 8ifneq (, $(wildcard $(TMK_PATH)/$(LUFA_PATH)/LUFA/Build/lufa_sources.mk))
9 # New build system from 20120730 9 # New build system from 20120730
10 LUFA_ROOT_PATH = $(LUFA_PATH)/LUFA 10 LUFA_ROOT_PATH = $(LUFA_PATH)/LUFA
11 include $(TMK_PATH)/$(LUFA_PATH)/LUFA/Build/lufa_sources.mk 11 include $(TMK_PATH)/$(LUFA_PATH)/LUFA/Build/lufa_sources.mk
12else 12else
13 include $(TMK_PATH)/$(LUFA_PATH)/LUFA/makefile 13 include $(TMK_PATH)/$(LUFA_PATH)/LUFA/makefile
14endif 14endif
15 15
16LUFA_SRC = lufa.c \ 16LUFA_SRC = lufa.c \
17 descriptor.c \ 17 descriptor.c \
18 outputselect.c \
18 $(LUFA_SRC_USB) 19 $(LUFA_SRC_USB)
19 20
20ifeq ($(strip $(MIDI_ENABLE)), yes) 21ifeq ($(strip $(MIDI_ENABLE)), yes)
@@ -26,6 +27,15 @@ ifeq ($(strip $(BLUETOOTH_ENABLE)), yes)
26 $(TMK_DIR)/protocol/serial_uart.c 27 $(TMK_DIR)/protocol/serial_uart.c
27endif 28endif
28 29
30ifeq ($(strip $(BLUETOOTH)), AdafruitBLE)
31 LUFA_SRC += $(LUFA_DIR)/adafruit_ble.cpp
32endif
33
34ifeq ($(strip $(BLUETOOTH)), AdafruitEZKey)
35 LUFA_SRC += $(LUFA_DIR)/bluetooth.c \
36 $(TMK_DIR)/protocol/serial_uart.c
37endif
38
29ifeq ($(strip $(VIRTSER_ENABLE)), yes) 39ifeq ($(strip $(VIRTSER_ENABLE)), yes)
30 LUFA_SRC += $(LUFA_ROOT_PATH)/Drivers/USB/Class/Device/CDCClassDevice.c 40 LUFA_SRC += $(LUFA_ROOT_PATH)/Drivers/USB/Class/Device/CDCClassDevice.c
31endif 41endif
@@ -49,6 +59,7 @@ LUFA_OPTS += -DUSE_FLASH_DESCRIPTORS
49LUFA_OPTS += -DUSE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)" 59LUFA_OPTS += -DUSE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
50#LUFA_OPTS += -DINTERRUPT_CONTROL_ENDPOINT 60#LUFA_OPTS += -DINTERRUPT_CONTROL_ENDPOINT
51LUFA_OPTS += -DFIXED_CONTROL_ENDPOINT_SIZE=8 61LUFA_OPTS += -DFIXED_CONTROL_ENDPOINT_SIZE=8
62LUFA_OPTS += -DFIXED_CONTROL_ENDPOINT_SIZE=8
52LUFA_OPTS += -DFIXED_NUM_CONFIGURATIONS=1 63LUFA_OPTS += -DFIXED_NUM_CONFIGURATIONS=1
53 64
54# Remote wakeup fix for ATmega32U2 https://github.com/tmk/tmk_keyboard/issues/361 65# Remote wakeup fix for ATmega32U2 https://github.com/tmk/tmk_keyboard/issues/361
diff --git a/tmk_core/protocol/lufa/adafruit_ble.cpp b/tmk_core/protocol/lufa/adafruit_ble.cpp
new file mode 100644
index 000000000..fd6edd42c
--- /dev/null
+++ b/tmk_core/protocol/lufa/adafruit_ble.cpp
@@ -0,0 +1,805 @@
1#include "adafruit_ble.h"
2#include <stdio.h>
3#include <stdlib.h>
4#include <alloca.h>
5#include <util/delay.h>
6#include <util/atomic.h>
7#include "debug.h"
8#include "pincontrol.h"
9#include "timer.h"
10#include "action_util.h"
11#include "ringbuffer.hpp"
12#include <string.h>
13
14// These are the pin assignments for the 32u4 boards.
15// You may define them to something else in your config.h
16// if yours is wired up differently.
17#ifndef AdafruitBleResetPin
18#define AdafruitBleResetPin D4
19#endif
20
21#ifndef AdafruitBleCSPin
22#define AdafruitBleCSPin B4
23#endif
24
25#ifndef AdafruitBleIRQPin
26#define AdafruitBleIRQPin E6
27#endif
28
29
30#define SAMPLE_BATTERY
31#define ConnectionUpdateInterval 1000 /* milliseconds */
32
33static struct {
34 bool is_connected;
35 bool initialized;
36 bool configured;
37
38#define ProbedEvents 1
39#define UsingEvents 2
40 bool event_flags;
41
42#ifdef SAMPLE_BATTERY
43 uint16_t last_battery_update;
44 uint32_t vbat;
45#endif
46 uint16_t last_connection_update;
47} state;
48
49// Commands are encoded using SDEP and sent via SPI
50// https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
51
52#define SdepMaxPayload 16
53struct sdep_msg {
54 uint8_t type;
55 uint8_t cmd_low;
56 uint8_t cmd_high;
57 struct __attribute__((packed)) {
58 uint8_t len:7;
59 uint8_t more:1;
60 };
61 uint8_t payload[SdepMaxPayload];
62} __attribute__((packed));
63
64// The recv latency is relatively high, so when we're hammering keys quickly,
65// we want to avoid waiting for the responses in the matrix loop. We maintain
66// a short queue for that. Since there is quite a lot of space overhead for
67// the AT command representation wrapped up in SDEP, we queue the minimal
68// information here.
69
70enum queue_type {
71 QTKeyReport, // 1-byte modifier + 6-byte key report
72 QTConsumer, // 16-bit key code
73#ifdef MOUSE_ENABLE
74 QTMouseMove, // 4-byte mouse report
75#endif
76};
77
78struct queue_item {
79 enum queue_type queue_type;
80 uint16_t added;
81 union __attribute__((packed)) {
82 struct __attribute__((packed)) {
83 uint8_t modifier;
84 uint8_t keys[6];
85 } key;
86
87 uint16_t consumer;
88 struct __attribute__((packed)) {
89 int8_t x, y, scroll, pan;
90 } mousemove;
91 };
92};
93
94// Items that we wish to send
95static RingBuffer<queue_item, 40> send_buf;
96// Pending response; while pending, we can't send any more requests.
97// This records the time at which we sent the command for which we
98// are expecting a response.
99static RingBuffer<uint16_t, 2> resp_buf;
100
101static bool process_queue_item(struct queue_item *item, uint16_t timeout);
102
103enum sdep_type {
104 SdepCommand = 0x10,
105 SdepResponse = 0x20,
106 SdepAlert = 0x40,
107 SdepError = 0x80,
108 SdepSlaveNotReady = 0xfe, // Try again later
109 SdepSlaveOverflow = 0xff, // You read more data than is available
110};
111
112enum ble_cmd {
113 BleInitialize = 0xbeef,
114 BleAtWrapper = 0x0a00,
115 BleUartTx = 0x0a01,
116 BleUartRx = 0x0a02,
117};
118
119enum ble_system_event_bits {
120 BleSystemConnected = 0,
121 BleSystemDisconnected = 1,
122 BleSystemUartRx = 8,
123 BleSystemMidiRx = 10,
124};
125
126// The SDEP.md file says 2MHz but the web page and the sample driver
127// both use 4MHz
128#define SpiBusSpeed 4000000
129
130#define SdepTimeout 150 /* milliseconds */
131#define SdepShortTimeout 10 /* milliseconds */
132#define SdepBackOff 25 /* microseconds */
133#define BatteryUpdateInterval 10000 /* milliseconds */
134
135static bool at_command(const char *cmd, char *resp, uint16_t resplen,
136 bool verbose, uint16_t timeout = SdepTimeout);
137static bool at_command_P(const char *cmd, char *resp, uint16_t resplen,
138 bool verbose = false);
139
140struct SPI_Settings {
141 uint8_t spcr, spsr;
142};
143
144static struct SPI_Settings spi;
145
146// Initialize 4Mhz MSBFIRST MODE0
147void SPI_init(struct SPI_Settings *spi) {
148 spi->spcr = _BV(SPE) | _BV(MSTR);
149 spi->spsr = _BV(SPI2X);
150
151 static_assert(SpiBusSpeed == F_CPU / 2, "hard coded at 4Mhz");
152
153 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
154 // Ensure that SS is OUTPUT High
155 digitalWrite(B0, PinLevelHigh);
156 pinMode(B0, PinDirectionOutput);
157
158 SPCR |= _BV(MSTR);
159 SPCR |= _BV(SPE);
160 pinMode(B1 /* SCK */, PinDirectionOutput);
161 pinMode(B2 /* MOSI */, PinDirectionOutput);
162 }
163}
164
165static inline void SPI_begin(struct SPI_Settings*spi) {
166 SPCR = spi->spcr;
167 SPSR = spi->spsr;
168}
169
170static inline uint8_t SPI_TransferByte(uint8_t data) {
171 SPDR = data;
172 asm volatile("nop");
173 while (!(SPSR & _BV(SPIF))) {
174 ; // wait
175 }
176 return SPDR;
177}
178
179static inline void spi_send_bytes(const uint8_t *buf, uint8_t len) {
180 if (len == 0) return;
181 const uint8_t *end = buf + len;
182 while (buf < end) {
183 SPDR = *buf;
184 while (!(SPSR & _BV(SPIF))) {
185 ; // wait
186 }
187 ++buf;
188 }
189}
190
191static inline uint16_t spi_read_byte(void) {
192 return SPI_TransferByte(0x00 /* dummy */);
193}
194
195static inline void spi_recv_bytes(uint8_t *buf, uint8_t len) {
196 const uint8_t *end = buf + len;
197 if (len == 0) return;
198 while (buf < end) {
199 SPDR = 0; // write a dummy to initiate read
200 while (!(SPSR & _BV(SPIF))) {
201 ; // wait
202 }
203 *buf = SPDR;
204 ++buf;
205 }
206}
207
208#if 0
209static void dump_pkt(const struct sdep_msg *msg) {
210 print("pkt: type=");
211 print_hex8(msg->type);
212 print(" cmd=");
213 print_hex8(msg->cmd_high);
214 print_hex8(msg->cmd_low);
215 print(" len=");
216 print_hex8(msg->len);
217 print(" more=");
218 print_hex8(msg->more);
219 print("\n");
220}
221#endif
222
223// Send a single SDEP packet
224static bool sdep_send_pkt(const struct sdep_msg *msg, uint16_t timeout) {
225 SPI_begin(&spi);
226
227 digitalWrite(AdafruitBleCSPin, PinLevelLow);
228 uint16_t timerStart = timer_read();
229 bool success = false;
230 bool ready = false;
231
232 do {
233 ready = SPI_TransferByte(msg->type) != SdepSlaveNotReady;
234 if (ready) {
235 break;
236 }
237
238 // Release it and let it initialize
239 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
240 _delay_us(SdepBackOff);
241 digitalWrite(AdafruitBleCSPin, PinLevelLow);
242 } while (timer_elapsed(timerStart) < timeout);
243
244 if (ready) {
245 // Slave is ready; send the rest of the packet
246 spi_send_bytes(&msg->cmd_low,
247 sizeof(*msg) - (1 + sizeof(msg->payload)) + msg->len);
248 success = true;
249 }
250
251 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
252
253 return success;
254}
255
256static inline void sdep_build_pkt(struct sdep_msg *msg, uint16_t command,
257 const uint8_t *payload, uint8_t len,
258 bool moredata) {
259 msg->type = SdepCommand;
260 msg->cmd_low = command & 0xff;
261 msg->cmd_high = command >> 8;
262 msg->len = len;
263 msg->more = (moredata && len == SdepMaxPayload) ? 1 : 0;
264
265 static_assert(sizeof(*msg) == 20, "msg is correctly packed");
266
267 memcpy(msg->payload, payload, len);
268}
269
270// Read a single SDEP packet
271static bool sdep_recv_pkt(struct sdep_msg *msg, uint16_t timeout) {
272 bool success = false;
273 uint16_t timerStart = timer_read();
274 bool ready = false;
275
276 do {
277 ready = digitalRead(AdafruitBleIRQPin);
278 if (ready) {
279 break;
280 }
281 _delay_us(1);
282 } while (timer_elapsed(timerStart) < timeout);
283
284 if (ready) {
285 SPI_begin(&spi);
286
287 digitalWrite(AdafruitBleCSPin, PinLevelLow);
288
289 do {
290 // Read the command type, waiting for the data to be ready
291 msg->type = spi_read_byte();
292 if (msg->type == SdepSlaveNotReady || msg->type == SdepSlaveOverflow) {
293 // Release it and let it initialize
294 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
295 _delay_us(SdepBackOff);
296 digitalWrite(AdafruitBleCSPin, PinLevelLow);
297 continue;
298 }
299
300 // Read the rest of the header
301 spi_recv_bytes(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)));
302
303 // and get the payload if there is any
304 if (msg->len <= SdepMaxPayload) {
305 spi_recv_bytes(msg->payload, msg->len);
306 }
307 success = true;
308 break;
309 } while (timer_elapsed(timerStart) < timeout);
310
311 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
312 }
313 return success;
314}
315
316static void resp_buf_read_one(bool greedy) {
317 uint16_t last_send;
318 if (!resp_buf.peek(last_send)) {
319 return;
320 }
321
322 if (digitalRead(AdafruitBleIRQPin)) {
323 struct sdep_msg msg;
324
325again:
326 if (sdep_recv_pkt(&msg, SdepTimeout)) {
327 if (!msg.more) {
328 // We got it; consume this entry
329 resp_buf.get(last_send);
330 dprintf("recv latency %dms\n", TIMER_DIFF_16(timer_read(), last_send));
331 }
332
333 if (greedy && resp_buf.peek(last_send) && digitalRead(AdafruitBleIRQPin)) {
334 goto again;
335 }
336 }
337
338 } else if (timer_elapsed(last_send) > SdepTimeout * 2) {
339 dprintf("waiting_for_result: timeout, resp_buf size %d\n",
340 (int)resp_buf.size());
341
342 // Timed out: consume this entry
343 resp_buf.get(last_send);
344 }
345}
346
347static void send_buf_send_one(uint16_t timeout = SdepTimeout) {
348 struct queue_item item;
349
350 // Don't send anything more until we get an ACK
351 if (!resp_buf.empty()) {
352 return;
353 }
354
355 if (!send_buf.peek(item)) {
356 return;
357 }
358 if (process_queue_item(&item, timeout)) {
359 // commit that peek
360 send_buf.get(item);
361 dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf.size());
362 } else {
363 dprint("failed to send, will retry\n");
364 _delay_ms(SdepTimeout);
365 resp_buf_read_one(true);
366 }
367}
368
369static void resp_buf_wait(const char *cmd) {
370 bool didPrint = false;
371 while (!resp_buf.empty()) {
372 if (!didPrint) {
373 dprintf("wait on buf for %s\n", cmd);
374 didPrint = true;
375 }
376 resp_buf_read_one(true);
377 }
378}
379
380static bool ble_init(void) {
381 state.initialized = false;
382 state.configured = false;
383 state.is_connected = false;
384
385 pinMode(AdafruitBleIRQPin, PinDirectionInput);
386 pinMode(AdafruitBleCSPin, PinDirectionOutput);
387 digitalWrite(AdafruitBleCSPin, PinLevelHigh);
388
389 SPI_init(&spi);
390
391 // Perform a hardware reset
392 pinMode(AdafruitBleResetPin, PinDirectionOutput);
393 digitalWrite(AdafruitBleResetPin, PinLevelHigh);
394 digitalWrite(AdafruitBleResetPin, PinLevelLow);
395 _delay_ms(10);
396 digitalWrite(AdafruitBleResetPin, PinLevelHigh);
397
398 _delay_ms(1000); // Give it a second to initialize
399
400 state.initialized = true;
401 return state.initialized;
402}
403
404static inline uint8_t min(uint8_t a, uint8_t b) {
405 return a < b ? a : b;
406}
407
408static bool read_response(char *resp, uint16_t resplen, bool verbose) {
409 char *dest = resp;
410 char *end = dest + resplen;
411
412 while (true) {
413 struct sdep_msg msg;
414
415 if (!sdep_recv_pkt(&msg, 2 * SdepTimeout)) {
416 dprint("sdep_recv_pkt failed\n");
417 return false;
418 }
419
420 if (msg.type != SdepResponse) {
421 *resp = 0;
422 return false;
423 }
424
425 uint8_t len = min(msg.len, end - dest);
426 if (len > 0) {
427 memcpy(dest, msg.payload, len);
428 dest += len;
429 }
430
431 if (!msg.more) {
432 // No more data is expected!
433 break;
434 }
435 }
436
437 // Ensure the response is NUL terminated
438 *dest = 0;
439
440 // "Parse" the result text; we want to snip off the trailing OK or ERROR line
441 // Rewind past the possible trailing CRLF so that we can strip it
442 --dest;
443 while (dest > resp && (dest[0] == '\n' || dest[0] == '\r')) {
444 *dest = 0;
445 --dest;
446 }
447
448 // Look back for start of preceeding line
449 char *last_line = strrchr(resp, '\n');
450 if (last_line) {
451 ++last_line;
452 } else {
453 last_line = resp;
454 }
455
456 bool success = false;
457 static const char kOK[] PROGMEM = "OK";
458
459 success = !strcmp_P(last_line, kOK );
460
461 if (verbose || !success) {
462 dprintf("result: %s\n", resp);
463 }
464 return success;
465}
466
467static bool at_command(const char *cmd, char *resp, uint16_t resplen,
468 bool verbose, uint16_t timeout) {
469 const char *end = cmd + strlen(cmd);
470 struct sdep_msg msg;
471
472 if (verbose) {
473 dprintf("ble send: %s\n", cmd);
474 }
475
476 if (resp) {
477 // They want to decode the response, so we need to flush and wait
478 // for all pending I/O to finish before we start this one, so
479 // that we don't confuse the results
480 resp_buf_wait(cmd);
481 *resp = 0;
482 }
483
484 // Fragment the command into a series of SDEP packets
485 while (end - cmd > SdepMaxPayload) {
486 sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, SdepMaxPayload, true);
487 if (!sdep_send_pkt(&msg, timeout)) {
488 return false;
489 }
490 cmd += SdepMaxPayload;
491 }
492
493 sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, end - cmd, false);
494 if (!sdep_send_pkt(&msg, timeout)) {
495 return false;
496 }
497
498 if (resp == NULL) {
499 auto now = timer_read();
500 while (!resp_buf.enqueue(now)) {
501 resp_buf_read_one(false);
502 }
503 auto later = timer_read();
504 if (TIMER_DIFF_16(later, now) > 0) {
505 dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later, now));
506 }
507 return true;
508 }
509
510 return read_response(resp, resplen, verbose);
511}
512
513bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose) {
514 auto cmdbuf = (char *)alloca(strlen_P(cmd) + 1);
515 strcpy_P(cmdbuf, cmd);
516 return at_command(cmdbuf, resp, resplen, verbose);
517}
518
519bool adafruit_ble_is_connected(void) {
520 return state.is_connected;
521}
522
523bool adafruit_ble_enable_keyboard(void) {
524 char resbuf[128];
525
526 if (!state.initialized && !ble_init()) {
527 return false;
528 }
529
530 state.configured = false;
531
532 // Disable command echo
533 static const char kEcho[] PROGMEM = "ATE=0";
534 // Make the advertised name match the keyboard
535 static const char kGapDevName[] PROGMEM =
536 "AT+GAPDEVNAME=" STR(PRODUCT) " " STR(DESCRIPTION);
537 // Turn on keyboard support
538 static const char kHidEnOn[] PROGMEM = "AT+BLEHIDEN=1";
539
540 // Adjust intervals to improve latency. This causes the "central"
541 // system (computer/tablet) to poll us every 10-30 ms. We can't
542 // set a smaller value than 10ms, and 30ms seems to be the natural
543 // processing time on my macbook. Keeping it constrained to that
544 // feels reasonable to type to.
545 static const char kGapIntervals[] PROGMEM = "AT+GAPINTERVALS=10,30,,";
546
547 // Reset the device so that it picks up the above changes
548 static const char kATZ[] PROGMEM = "ATZ";
549
550 // Turn down the power level a bit
551 static const char kPower[] PROGMEM = "AT+BLEPOWERLEVEL=-12";
552 static PGM_P const configure_commands[] PROGMEM = {
553 kEcho,
554 kGapIntervals,
555 kGapDevName,
556 kHidEnOn,
557 kPower,
558 kATZ,
559 };
560
561 uint8_t i;
562 for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]);
563 ++i) {
564 PGM_P cmd;
565 memcpy_P(&cmd, configure_commands + i, sizeof(cmd));
566
567 if (!at_command_P(cmd, resbuf, sizeof(resbuf))) {
568 dprintf("failed BLE command: %S: %s\n", cmd, resbuf);
569 goto fail;
570 }
571 }
572
573 state.configured = true;
574
575 // Check connection status in a little while; allow the ATZ time
576 // to kick in.
577 state.last_connection_update = timer_read();
578fail:
579 return state.configured;
580}
581
582static void set_connected(bool connected) {
583 if (connected != state.is_connected) {
584 if (connected) {
585 print("****** BLE CONNECT!!!!\n");
586 } else {
587 print("****** BLE DISCONNECT!!!!\n");
588 }
589 state.is_connected = connected;
590
591 // TODO: if modifiers are down on the USB interface and
592 // we cut over to BLE or vice versa, they will remain stuck.
593 // This feels like a good point to do something like clearing
594 // the keyboard and/or generating a fake all keys up message.
595 // However, I've noticed that it takes a couple of seconds
596 // for macOS to to start recognizing key presses after BLE
597 // is in the connected state, so I worry that doing that
598 // here may not be good enough.
599 }
600}
601
602void adafruit_ble_task(void) {
603 char resbuf[48];
604
605 if (!state.configured && !adafruit_ble_enable_keyboard()) {
606 return;
607 }
608 resp_buf_read_one(true);
609 send_buf_send_one(SdepShortTimeout);
610
611 if (resp_buf.empty() && (state.event_flags & UsingEvents) &&
612 digitalRead(AdafruitBleIRQPin)) {
613 // Must be an event update
614 if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf, sizeof(resbuf))) {
615 uint32_t mask = strtoul(resbuf, NULL, 16);
616
617 if (mask & BleSystemConnected) {
618 set_connected(true);
619 } else if (mask & BleSystemDisconnected) {
620 set_connected(false);
621 }
622 }
623 }
624
625 if (timer_elapsed(state.last_connection_update) > ConnectionUpdateInterval) {
626 bool shouldPoll = true;
627 if (!(state.event_flags & ProbedEvents)) {
628 // Request notifications about connection status changes.
629 // This only works in SPIFRIEND firmware > 0.6.7, which is why
630 // we check for this conditionally here.
631 // Note that at the time of writing, HID reports only work correctly
632 // with Apple products on firmware version 0.6.7!
633 // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
634 if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf, sizeof(resbuf))) {
635 at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf, sizeof(resbuf));
636 state.event_flags |= UsingEvents;
637 }
638 state.event_flags |= ProbedEvents;
639
640 // leave shouldPoll == true so that we check at least once
641 // before relying solely on events
642 } else {
643 shouldPoll = false;
644 }
645
646 static const char kGetConn[] PROGMEM = "AT+GAPGETCONN";
647 state.last_connection_update = timer_read();
648
649 if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) {
650 set_connected(atoi(resbuf));
651 }
652 }
653
654#ifdef SAMPLE_BATTERY
655 // I don't know if this really does anything useful yet; the reported
656 // voltage level always seems to be around 3200mV. We may want to just rip
657 // this code out.
658 if (timer_elapsed(state.last_battery_update) > BatteryUpdateInterval &&
659 resp_buf.empty()) {
660 state.last_battery_update = timer_read();
661
662 if (at_command_P(PSTR("AT+HWVBAT"), resbuf, sizeof(resbuf))) {
663 state.vbat = atoi(resbuf);
664 }
665 }
666#endif
667}
668
669static bool process_queue_item(struct queue_item *item, uint16_t timeout) {
670 char cmdbuf[48];
671 char fmtbuf[64];
672
673 // Arrange to re-check connection after keys have settled
674 state.last_connection_update = timer_read();
675
676#if 1
677 if (TIMER_DIFF_16(state.last_connection_update, item->added) > 0) {
678 dprintf("send latency %dms\n",
679 TIMER_DIFF_16(state.last_connection_update, item->added));
680 }
681#endif
682
683 switch (item->queue_type) {
684 case QTKeyReport:
685 strcpy_P(fmtbuf,
686 PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
687 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->key.modifier,
688 item->key.keys[0], item->key.keys[1], item->key.keys[2],
689 item->key.keys[3], item->key.keys[4], item->key.keys[5]);
690 return at_command(cmdbuf, NULL, 0, true, timeout);
691
692 case QTConsumer:
693 strcpy_P(fmtbuf, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
694 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->consumer);
695 return at_command(cmdbuf, NULL, 0, true, timeout);
696
697#ifdef MOUSE_ENABLE
698 case QTMouseMove:
699 strcpy_P(fmtbuf, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
700 snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->mousemove.x,
701 item->mousemove.y, item->mousemove.scroll, item->mousemove.pan);
702 return at_command(cmdbuf, NULL, 0, true, timeout);
703#endif
704 default:
705 return true;
706 }
707}
708
709bool adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys,
710 uint8_t nkeys) {
711 struct queue_item item;
712 bool didWait = false;
713
714 item.queue_type = QTKeyReport;
715 item.key.modifier = hid_modifier_mask;
716 item.added = timer_read();
717
718 while (nkeys >= 0) {
719 item.key.keys[0] = keys[0];
720 item.key.keys[1] = nkeys >= 1 ? keys[1] : 0;
721 item.key.keys[2] = nkeys >= 2 ? keys[2] : 0;
722 item.key.keys[3] = nkeys >= 3 ? keys[3] : 0;
723 item.key.keys[4] = nkeys >= 4 ? keys[4] : 0;
724 item.key.keys[5] = nkeys >= 5 ? keys[5] : 0;
725
726 if (!send_buf.enqueue(item)) {
727 if (!didWait) {
728 dprint("wait for buf space\n");
729 didWait = true;
730 }
731 send_buf_send_one();
732 continue;
733 }
734
735 if (nkeys <= 6) {
736 return true;
737 }
738
739 nkeys -= 6;
740 keys += 6;
741 }
742
743 return true;
744}
745
746bool adafruit_ble_send_consumer_key(uint16_t keycode, int hold_duration) {
747 struct queue_item item;
748
749 item.queue_type = QTConsumer;
750 item.consumer = keycode;
751
752 while (!send_buf.enqueue(item)) {
753 send_buf_send_one();
754 }
755 return true;
756}
757
758#ifdef MOUSE_ENABLE
759bool adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll,
760 int8_t pan) {
761 struct queue_item item;
762
763 item.queue_type = QTMouseMove;
764 item.mousemove.x = x;
765 item.mousemove.y = y;
766 item.mousemove.scroll = scroll;
767 item.mousemove.pan = pan;
768
769 while (!send_buf.enqueue(item)) {
770 send_buf_send_one();
771 }
772 return true;
773}
774#endif
775
776uint32_t adafruit_ble_read_battery_voltage(void) {
777 return state.vbat;
778}
779
780bool adafruit_ble_set_mode_leds(bool on) {
781 if (!state.configured) {
782 return false;
783 }
784
785 // The "mode" led is the red blinky one
786 at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0);
787
788 // Pin 19 is the blue "connected" LED; turn that off too.
789 // When turning LEDs back on, don't turn that LED on if we're
790 // not connected, as that would be confusing.
791 at_command_P(on && state.is_connected ? PSTR("AT+HWGPIO=19,1")
792 : PSTR("AT+HWGPIO=19,0"),
793 NULL, 0);
794 return true;
795}
796
797// https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
798bool adafruit_ble_set_power_level(int8_t level) {
799 char cmd[46];
800 if (!state.configured) {
801 return false;
802 }
803 snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level);
804 return at_command(cmd, NULL, 0, false);
805}
diff --git a/tmk_core/protocol/lufa/adafruit_ble.h b/tmk_core/protocol/lufa/adafruit_ble.h
new file mode 100644
index 000000000..b3bab3ca0
--- /dev/null
+++ b/tmk_core/protocol/lufa/adafruit_ble.h
@@ -0,0 +1,60 @@
1/* Bluetooth Low Energy Protocol for QMK.
2 * Author: Wez Furlong, 2016
3 * Supports the Adafruit BLE board built around the nRF51822 chip.
4 */
5#pragma once
6#ifdef MODULE_ADAFRUIT_BLE
7#include <stdbool.h>
8#include <stdint.h>
9#include <string.h>
10
11#ifdef __cplusplus
12extern "C" {
13#endif
14
15/* Instruct the module to enable HID keyboard support and reset */
16extern bool adafruit_ble_enable_keyboard(void);
17
18/* Query to see if the BLE module is connected */
19extern bool adafruit_ble_query_is_connected(void);
20
21/* Returns true if we believe that the BLE module is connected.
22 * This uses our cached understanding that is maintained by
23 * calling ble_task() periodically. */
24extern bool adafruit_ble_is_connected(void);
25
26/* Call this periodically to process BLE-originated things */
27extern void adafruit_ble_task(void);
28
29/* Generates keypress events for a set of keys.
30 * The hid modifier mask specifies the state of the modifier keys for
31 * this set of keys.
32 * Also sends a key release indicator, so that the keys do not remain
33 * held down. */
34extern bool adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys,
35 uint8_t nkeys);
36
37/* Send a consumer keycode, holding it down for the specified duration
38 * (milliseconds) */
39extern bool adafruit_ble_send_consumer_key(uint16_t keycode, int hold_duration);
40
41#ifdef MOUSE_ENABLE
42/* Send a mouse/wheel movement report.
43 * The parameters are signed and indicate positive of negative direction
44 * change. */
45extern bool adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll,
46 int8_t pan);
47#endif
48
49/* Compute battery voltage by reading an analog pin.
50 * Returns the integer number of millivolts */
51extern uint32_t adafruit_ble_read_battery_voltage(void);
52
53extern bool adafruit_ble_set_mode_leds(bool on);
54extern bool adafruit_ble_set_power_level(int8_t level);
55
56#ifdef __cplusplus
57}
58#endif
59
60#endif // MODULE_ADAFRUIT_BLE
diff --git a/tmk_core/protocol/lufa/descriptor.c b/tmk_core/protocol/lufa/descriptor.c
index 6f2407f58..feeea76df 100644
--- a/tmk_core/protocol/lufa/descriptor.c
+++ b/tmk_core/protocol/lufa/descriptor.c
@@ -40,6 +40,9 @@
40#include "report.h" 40#include "report.h"
41#include "descriptor.h" 41#include "descriptor.h"
42 42
43#ifndef USB_MAX_POWER_CONSUMPTION
44#define USB_MAX_POWER_CONSUMPTION 500
45#endif
43 46
44/******************************************************************************* 47/*******************************************************************************
45 * HID Report Descriptors 48 * HID Report Descriptors
@@ -140,10 +143,10 @@ const USB_Descriptor_HIDReport_Datatype_t PROGMEM ExtrakeyReport[] =
140 HID_RI_USAGE(8, 0x80), /* System Control */ 143 HID_RI_USAGE(8, 0x80), /* System Control */
141 HID_RI_COLLECTION(8, 0x01), /* Application */ 144 HID_RI_COLLECTION(8, 0x01), /* Application */
142 HID_RI_REPORT_ID(8, REPORT_ID_SYSTEM), 145 HID_RI_REPORT_ID(8, REPORT_ID_SYSTEM),
143 HID_RI_LOGICAL_MINIMUM(16, 0x0081), 146 HID_RI_LOGICAL_MINIMUM(16, 0x0001),
144 HID_RI_LOGICAL_MAXIMUM(16, 0x00B7), 147 HID_RI_LOGICAL_MAXIMUM(16, 0x0003),
145 HID_RI_USAGE_MINIMUM(16, 0x0081), /* System Power Down */ 148 HID_RI_USAGE_MINIMUM(16, 0x0081), /* System Power Down */
146 HID_RI_USAGE_MAXIMUM(16, 0x00B7), /* System Display LCD Autoscale */ 149 HID_RI_USAGE_MAXIMUM(16, 0x0083), /* System Wake Up */
147 HID_RI_REPORT_SIZE(8, 16), 150 HID_RI_REPORT_SIZE(8, 16),
148 HID_RI_REPORT_COUNT(8, 1), 151 HID_RI_REPORT_COUNT(8, 1),
149 HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_ARRAY | HID_IOF_ABSOLUTE), 152 HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_ARRAY | HID_IOF_ABSOLUTE),
@@ -164,6 +167,28 @@ const USB_Descriptor_HIDReport_Datatype_t PROGMEM ExtrakeyReport[] =
164}; 167};
165#endif 168#endif
166 169
170#ifdef RAW_ENABLE
171const USB_Descriptor_HIDReport_Datatype_t PROGMEM RawReport[] =
172{
173 HID_RI_USAGE_PAGE(16, 0xFF60), /* Vendor Page 0xFF60 */
174 HID_RI_USAGE(8, 0x61), /* Vendor Usage 0x61 */
175 HID_RI_COLLECTION(8, 0x01), /* Application */
176 HID_RI_USAGE(8, 0x62), /* Vendor Usage 0x62 */
177 HID_RI_LOGICAL_MINIMUM(8, 0x00),
178 HID_RI_LOGICAL_MAXIMUM(16, 0x00FF),
179 HID_RI_REPORT_COUNT(8, RAW_EPSIZE),
180 HID_RI_REPORT_SIZE(8, 0x08),
181 HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
182 HID_RI_USAGE(8, 0x63), /* Vendor Usage 0x63 */
183 HID_RI_LOGICAL_MINIMUM(8, 0x00),
184 HID_RI_LOGICAL_MAXIMUM(16, 0x00FF),
185 HID_RI_REPORT_COUNT(8, RAW_EPSIZE),
186 HID_RI_REPORT_SIZE(8, 0x08),
187 HID_RI_OUTPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE | HID_IOF_NON_VOLATILE),
188 HID_RI_END_COLLECTION(0),
189};
190#endif
191
167#ifdef CONSOLE_ENABLE 192#ifdef CONSOLE_ENABLE
168const USB_Descriptor_HIDReport_Datatype_t PROGMEM ConsoleReport[] = 193const USB_Descriptor_HIDReport_Datatype_t PROGMEM ConsoleReport[] =
169{ 194{
@@ -272,7 +297,7 @@ const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
272 297
273 .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_REMOTEWAKEUP), 298 .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_REMOTEWAKEUP),
274 299
275 .MaxPowerConsumption = USB_CONFIG_POWER_MA(500) 300 .MaxPowerConsumption = USB_CONFIG_POWER_MA(USB_MAX_POWER_CONSUMPTION)
276 }, 301 },
277 302
278 /* 303 /*
@@ -399,6 +424,58 @@ const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
399 }, 424 },
400#endif 425#endif
401 426
427 /*
428 * Raw
429 */
430 #ifdef RAW_ENABLE
431 .Raw_Interface =
432 {
433 .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
434
435 .InterfaceNumber = RAW_INTERFACE,
436 .AlternateSetting = 0x00,
437
438 .TotalEndpoints = 2,
439
440 .Class = HID_CSCP_HIDClass,
441 .SubClass = HID_CSCP_NonBootSubclass,
442 .Protocol = HID_CSCP_NonBootProtocol,
443
444 .InterfaceStrIndex = NO_DESCRIPTOR
445 },
446
447 .Raw_HID =
448 {
449 .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
450
451 .HIDSpec = VERSION_BCD(1,1,1),
452 .CountryCode = 0x00,
453 .TotalReportDescriptors = 1,
454 .HIDReportType = HID_DTYPE_Report,
455 .HIDReportLength = sizeof(RawReport)
456 },
457
458 .Raw_INEndpoint =
459 {
460 .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
461
462 .EndpointAddress = (ENDPOINT_DIR_IN | RAW_IN_EPNUM),
463 .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
464 .EndpointSize = RAW_EPSIZE,
465 .PollingIntervalMS = 0x01
466 },
467
468 .Raw_OUTEndpoint =
469 {
470 .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
471
472 .EndpointAddress = (ENDPOINT_DIR_OUT | RAW_OUT_EPNUM),
473 .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
474 .EndpointSize = RAW_EPSIZE,
475 .PollingIntervalMS = 0x01
476 },
477 #endif
478
402 /* 479 /*
403 * Console 480 * Console
404 */ 481 */
@@ -754,7 +831,6 @@ const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
754 .PollingIntervalMS = 0x05 831 .PollingIntervalMS = 0x05
755 }, 832 },
756#endif 833#endif
757
758}; 834};
759 835
760 836
@@ -846,6 +922,12 @@ uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
846 Size = sizeof(USB_HID_Descriptor_HID_t); 922 Size = sizeof(USB_HID_Descriptor_HID_t);
847 break; 923 break;
848#endif 924#endif
925#ifdef RAW_ENABLE
926 case RAW_INTERFACE:
927 Address = &ConfigurationDescriptor.Raw_HID;
928 Size = sizeof(USB_HID_Descriptor_HID_t);
929 break;
930#endif
849#ifdef CONSOLE_ENABLE 931#ifdef CONSOLE_ENABLE
850 case CONSOLE_INTERFACE: 932 case CONSOLE_INTERFACE:
851 Address = &ConfigurationDescriptor.Console_HID; 933 Address = &ConfigurationDescriptor.Console_HID;
@@ -878,6 +960,12 @@ uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
878 Size = sizeof(ExtrakeyReport); 960 Size = sizeof(ExtrakeyReport);
879 break; 961 break;
880#endif 962#endif
963#ifdef RAW_ENABLE
964 case RAW_INTERFACE:
965 Address = &RawReport;
966 Size = sizeof(RawReport);
967 break;
968#endif
881#ifdef CONSOLE_ENABLE 969#ifdef CONSOLE_ENABLE
882 case CONSOLE_INTERFACE: 970 case CONSOLE_INTERFACE:
883 Address = &ConsoleReport; 971 Address = &ConsoleReport;
diff --git a/tmk_core/protocol/lufa/descriptor.h b/tmk_core/protocol/lufa/descriptor.h
index c6c94e361..24ce420e6 100644
--- a/tmk_core/protocol/lufa/descriptor.h
+++ b/tmk_core/protocol/lufa/descriptor.h
@@ -71,6 +71,14 @@ typedef struct
71 USB_Descriptor_Endpoint_t Extrakey_INEndpoint; 71 USB_Descriptor_Endpoint_t Extrakey_INEndpoint;
72#endif 72#endif
73 73
74#ifdef RAW_ENABLE
75 // Raw HID Interface
76 USB_Descriptor_Interface_t Raw_Interface;
77 USB_HID_Descriptor_HID_t Raw_HID;
78 USB_Descriptor_Endpoint_t Raw_INEndpoint;
79 USB_Descriptor_Endpoint_t Raw_OUTEndpoint;
80#endif
81
74#ifdef CONSOLE_ENABLE 82#ifdef CONSOLE_ENABLE
75 // Console HID Interface 83 // Console HID Interface
76 USB_Descriptor_Interface_t Console_Interface; 84 USB_Descriptor_Interface_t Console_Interface;
@@ -137,10 +145,16 @@ typedef struct
137# define EXTRAKEY_INTERFACE MOUSE_INTERFACE 145# define EXTRAKEY_INTERFACE MOUSE_INTERFACE
138#endif 146#endif
139 147
148#ifdef RAW_ENABLE
149# define RAW_INTERFACE (EXTRAKEY_INTERFACE + 1)
150#else
151# define RAW_INTERFACE EXTRAKEY_INTERFACE
152#endif
153
140#ifdef CONSOLE_ENABLE 154#ifdef CONSOLE_ENABLE
141# define CONSOLE_INTERFACE (EXTRAKEY_INTERFACE + 1) 155# define CONSOLE_INTERFACE (RAW_INTERFACE + 1)
142#else 156#else
143# define CONSOLE_INTERFACE EXTRAKEY_INTERFACE 157# define CONSOLE_INTERFACE RAW_INTERFACE
144#endif 158#endif
145 159
146#ifdef NKRO_ENABLE 160#ifdef NKRO_ENABLE
@@ -182,12 +196,19 @@ typedef struct
182# define EXTRAKEY_IN_EPNUM MOUSE_IN_EPNUM 196# define EXTRAKEY_IN_EPNUM MOUSE_IN_EPNUM
183#endif 197#endif
184 198
199#ifdef RAW_ENABLE
200# define RAW_IN_EPNUM (EXTRAKEY_IN_EPNUM + 1)
201# define RAW_OUT_EPNUM (EXTRAKEY_IN_EPNUM + 2)
202#else
203# define RAW_OUT_EPNUM EXTRAKEY_IN_EPNUM
204#endif
205
185#ifdef CONSOLE_ENABLE 206#ifdef CONSOLE_ENABLE
186# define CONSOLE_IN_EPNUM (EXTRAKEY_IN_EPNUM + 1) 207# define CONSOLE_IN_EPNUM (RAW_OUT_EPNUM + 1)
187# define CONSOLE_OUT_EPNUM (EXTRAKEY_IN_EPNUM + 1) 208//# define CONSOLE_OUT_EPNUM (RAW_OUT_EPNUM + 2)
188//# define CONSOLE_OUT_EPNUM (EXTRAKEY_IN_EPNUM + 2) 209# define CONSOLE_OUT_EPNUM (RAW_OUT_EPNUM + 1)
189#else 210#else
190# define CONSOLE_OUT_EPNUM EXTRAKEY_IN_EPNUM 211# define CONSOLE_OUT_EPNUM RAW_OUT_EPNUM
191#endif 212#endif
192 213
193#ifdef NKRO_ENABLE 214#ifdef NKRO_ENABLE
@@ -217,7 +238,6 @@ typedef struct
217# define CDC_OUT_EPNUM MIDI_STREAM_OUT_EPNUM 238# define CDC_OUT_EPNUM MIDI_STREAM_OUT_EPNUM
218#endif 239#endif
219 240
220
221#if defined(__AVR_ATmega32U2__) && CDC_OUT_EPNUM > 4 241#if defined(__AVR_ATmega32U2__) && CDC_OUT_EPNUM > 4
222# error "Endpoints are not available enough to support all functions. Remove some in Makefile.(MOUSEKEY, EXTRAKEY, CONSOLE, NKRO, MIDI, SERIAL)" 242# error "Endpoints are not available enough to support all functions. Remove some in Makefile.(MOUSEKEY, EXTRAKEY, CONSOLE, NKRO, MIDI, SERIAL)"
223#endif 243#endif
@@ -225,6 +245,7 @@ typedef struct
225#define KEYBOARD_EPSIZE 8 245#define KEYBOARD_EPSIZE 8
226#define MOUSE_EPSIZE 8 246#define MOUSE_EPSIZE 8
227#define EXTRAKEY_EPSIZE 8 247#define EXTRAKEY_EPSIZE 8
248#define RAW_EPSIZE 32
228#define CONSOLE_EPSIZE 32 249#define CONSOLE_EPSIZE 32
229#define NKRO_EPSIZE 32 250#define NKRO_EPSIZE 32
230#define MIDI_STREAM_EPSIZE 64 251#define MIDI_STREAM_EPSIZE 64
diff --git a/tmk_core/protocol/lufa/lufa.c b/tmk_core/protocol/lufa/lufa.c
index 01c0e45b0..60cba8d2a 100644
--- a/tmk_core/protocol/lufa/lufa.c
+++ b/tmk_core/protocol/lufa/lufa.c
@@ -51,6 +51,9 @@
51 51
52#include "descriptor.h" 52#include "descriptor.h"
53#include "lufa.h" 53#include "lufa.h"
54#include "quantum.h"
55#include <util/atomic.h>
56#include "outputselect.h"
54 57
55#ifdef NKRO_ENABLE 58#ifdef NKRO_ENABLE
56 #include "keycode_config.h" 59 #include "keycode_config.h"
@@ -64,13 +67,29 @@
64#endif 67#endif
65 68
66#ifdef BLUETOOTH_ENABLE 69#ifdef BLUETOOTH_ENABLE
70 #ifdef MODULE_ADAFRUIT_BLE
71 #include "adafruit_ble.h"
72 #else
67 #include "bluetooth.h" 73 #include "bluetooth.h"
74 #endif
68#endif 75#endif
69 76
70#ifdef VIRTSER_ENABLE 77#ifdef VIRTSER_ENABLE
71 #include "virtser.h" 78 #include "virtser.h"
72#endif 79#endif
73 80
81#if (defined(RGB_MIDI) | defined(RGBLIGHT_ANIMATIONS)) & defined(RGBLIGHT_ENABLE)
82 #include "rgblight.h"
83#endif
84
85#ifdef MIDI_ENABLE
86 #include "sysex_tools.h"
87#endif
88
89#ifdef RAW_ENABLE
90 #include "raw_hid.h"
91#endif
92
74uint8_t keyboard_idle = 0; 93uint8_t keyboard_idle = 0;
75/* 0: Boot Protocol, 1: Report Protocol(default) */ 94/* 0: Boot Protocol, 1: Report Protocol(default) */
76uint8_t keyboard_protocol = 1; 95uint8_t keyboard_protocol = 1;
@@ -79,9 +98,9 @@ static uint8_t keyboard_led_stats = 0;
79static report_keyboard_t keyboard_report_sent; 98static report_keyboard_t keyboard_report_sent;
80 99
81#ifdef MIDI_ENABLE 100#ifdef MIDI_ENABLE
82void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2); 101static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
83void usb_get_midi(MidiDevice * device); 102static void usb_get_midi(MidiDevice * device);
84void midi_usb_init(MidiDevice * device); 103static void midi_usb_init(MidiDevice * device);
85#endif 104#endif
86 105
87/* Host driver */ 106/* Host driver */
@@ -166,6 +185,80 @@ USB_ClassInfo_CDC_Device_t cdc_device =
166}; 185};
167#endif 186#endif
168 187
188#ifdef RAW_ENABLE
189
190void raw_hid_send( uint8_t *data, uint8_t length )
191{
192 // TODO: implement variable size packet
193 if ( length != RAW_EPSIZE )
194 {
195 return;
196 }
197
198 if (USB_DeviceState != DEVICE_STATE_Configured)
199 {
200 return;
201 }
202
203 // TODO: decide if we allow calls to raw_hid_send() in the middle
204 // of other endpoint usage.
205 uint8_t ep = Endpoint_GetCurrentEndpoint();
206
207 Endpoint_SelectEndpoint(RAW_IN_EPNUM);
208
209 // Check to see if the host is ready to accept another packet
210 if (Endpoint_IsINReady())
211 {
212 // Write data
213 Endpoint_Write_Stream_LE(data, RAW_EPSIZE, NULL);
214 // Finalize the stream transfer to send the last packet
215 Endpoint_ClearIN();
216 }
217
218 Endpoint_SelectEndpoint(ep);
219}
220
221__attribute__ ((weak))
222void raw_hid_receive( uint8_t *data, uint8_t length )
223{
224 // Users should #include "raw_hid.h" in their own code
225 // and implement this function there. Leave this as weak linkage
226 // so users can opt to not handle data coming in.
227}
228
229static void raw_hid_task(void)
230{
231 // Create a temporary buffer to hold the read in data from the host
232 uint8_t data[RAW_EPSIZE];
233 bool data_read = false;
234
235 // Device must be connected and configured for the task to run
236 if (USB_DeviceState != DEVICE_STATE_Configured)
237 return;
238
239 Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
240
241 // Check to see if a packet has been sent from the host
242 if (Endpoint_IsOUTReceived())
243 {
244 // Check to see if the packet contains data
245 if (Endpoint_IsReadWriteAllowed())
246 {
247 /* Read data */
248 Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
249 data_read = true;
250 }
251
252 // Finalize the stream transfer to receive the last packet
253 Endpoint_ClearOUT();
254
255 if ( data_read )
256 {
257 raw_hid_receive( data, sizeof(data) );
258 }
259 }
260}
261#endif
169 262
170/******************************************************************************* 263/*******************************************************************************
171 * Console 264 * Console
@@ -285,10 +378,14 @@ void EVENT_USB_Device_WakeUp()
285#endif 378#endif
286} 379}
287 380
381
382
288#ifdef CONSOLE_ENABLE 383#ifdef CONSOLE_ENABLE
289static bool console_flush = false; 384static bool console_flush = false;
290#define CONSOLE_FLUSH_SET(b) do { \ 385#define CONSOLE_FLUSH_SET(b) do { \
291 uint8_t sreg = SREG; cli(); console_flush = b; SREG = sreg; \ 386 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {\
387 console_flush = b; \
388 } \
292} while (0) 389} while (0)
293 390
294// called every 1ms 391// called every 1ms
@@ -302,6 +399,7 @@ void EVENT_USB_Device_StartOfFrame(void)
302 Console_Task(); 399 Console_Task();
303 console_flush = false; 400 console_flush = false;
304} 401}
402
305#endif 403#endif
306 404
307/** Event handler for the USB_ConfigurationChanged event. 405/** Event handler for the USB_ConfigurationChanged event.
@@ -330,6 +428,14 @@ void EVENT_USB_Device_ConfigurationChanged(void)
330 EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE); 428 EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
331#endif 429#endif
332 430
431#ifdef RAW_ENABLE
432 /* Setup Raw HID Report Endpoints */
433 ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
434 RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
435 ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
436 RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
437#endif
438
333#ifdef CONSOLE_ENABLE 439#ifdef CONSOLE_ENABLE
334 /* Setup Console HID Report Endpoints */ 440 /* Setup Console HID Report Endpoints */
335 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN, 441 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
@@ -485,7 +591,6 @@ void EVENT_USB_Device_ControlRequest(void)
485 591
486/******************************************************************************* 592/*******************************************************************************
487 * Host driver 593 * Host driver
488p
489 ******************************************************************************/ 594 ******************************************************************************/
490static uint8_t keyboard_leds(void) 595static uint8_t keyboard_leds(void)
491{ 596{
@@ -494,18 +599,25 @@ static uint8_t keyboard_leds(void)
494 599
495static void send_keyboard(report_keyboard_t *report) 600static void send_keyboard(report_keyboard_t *report)
496{ 601{
602 uint8_t timeout = 255;
603 uint8_t where = where_to_send();
497 604
498#ifdef BLUETOOTH_ENABLE 605#ifdef BLUETOOTH_ENABLE
499 bluefruit_serial_send(0xFD); 606 if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
500 for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) { 607 #ifdef MODULE_ADAFRUIT_BLE
608 adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
609 #else
610 bluefruit_serial_send(0xFD);
611 for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
501 bluefruit_serial_send(report->raw[i]); 612 bluefruit_serial_send(report->raw[i]);
502 } 613 }
614 #endif
615 }
503#endif 616#endif
504 617
505 uint8_t timeout = 255; 618 if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
506 619 return;
507 if (USB_DeviceState != DEVICE_STATE_Configured) 620 }
508 return;
509 621
510 /* Select the Keyboard Report Endpoint */ 622 /* Select the Keyboard Report Endpoint */
511#ifdef NKRO_ENABLE 623#ifdef NKRO_ENABLE
@@ -543,23 +655,31 @@ static void send_keyboard(report_keyboard_t *report)
543static void send_mouse(report_mouse_t *report) 655static void send_mouse(report_mouse_t *report)
544{ 656{
545#ifdef MOUSE_ENABLE 657#ifdef MOUSE_ENABLE
658 uint8_t timeout = 255;
659 uint8_t where = where_to_send();
546 660
547#ifdef BLUETOOTH_ENABLE 661#ifdef BLUETOOTH_ENABLE
548 bluefruit_serial_send(0xFD); 662 if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
549 bluefruit_serial_send(0x00); 663 #ifdef MODULE_ADAFRUIT_BLE
550 bluefruit_serial_send(0x03); 664 // FIXME: mouse buttons
551 bluefruit_serial_send(report->buttons); 665 adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h);
552 bluefruit_serial_send(report->x); 666 #else
553 bluefruit_serial_send(report->y); 667 bluefruit_serial_send(0xFD);
554 bluefruit_serial_send(report->v); // should try sending the wheel v here 668 bluefruit_serial_send(0x00);
555 bluefruit_serial_send(report->h); // should try sending the wheel h here 669 bluefruit_serial_send(0x03);
556 bluefruit_serial_send(0x00); 670 bluefruit_serial_send(report->buttons);
671 bluefruit_serial_send(report->x);
672 bluefruit_serial_send(report->y);
673 bluefruit_serial_send(report->v); // should try sending the wheel v here
674 bluefruit_serial_send(report->h); // should try sending the wheel h here
675 bluefruit_serial_send(0x00);
676 #endif
677 }
557#endif 678#endif
558 679
559 uint8_t timeout = 255; 680 if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
560 681 return;
561 if (USB_DeviceState != DEVICE_STATE_Configured) 682 }
562 return;
563 683
564 /* Select the Mouse Report Endpoint */ 684 /* Select the Mouse Report Endpoint */
565 Endpoint_SelectEndpoint(MOUSE_IN_EPNUM); 685 Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
@@ -585,7 +705,7 @@ static void send_system(uint16_t data)
585 705
586 report_extra_t r = { 706 report_extra_t r = {
587 .report_id = REPORT_ID_SYSTEM, 707 .report_id = REPORT_ID_SYSTEM,
588 .usage = data 708 .usage = data - SYSTEM_POWER_DOWN + 1
589 }; 709 };
590 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM); 710 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
591 711
@@ -599,27 +719,34 @@ static void send_system(uint16_t data)
599 719
600static void send_consumer(uint16_t data) 720static void send_consumer(uint16_t data)
601{ 721{
722 uint8_t timeout = 255;
723 uint8_t where = where_to_send();
602 724
603#ifdef BLUETOOTH_ENABLE 725#ifdef BLUETOOTH_ENABLE
604 static uint16_t last_data = 0; 726 if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
605 if (data == last_data) return; 727 #ifdef MODULE_ADAFRUIT_BLE
606 last_data = data; 728 adafruit_ble_send_consumer_key(data, 0);
607 uint16_t bitmap = CONSUMER2BLUEFRUIT(data); 729 #else
608 bluefruit_serial_send(0xFD); 730 static uint16_t last_data = 0;
609 bluefruit_serial_send(0x00); 731 if (data == last_data) return;
610 bluefruit_serial_send(0x02); 732 last_data = data;
611 bluefruit_serial_send((bitmap>>8)&0xFF); 733 uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
612 bluefruit_serial_send(bitmap&0xFF); 734 bluefruit_serial_send(0xFD);
613 bluefruit_serial_send(0x00); 735 bluefruit_serial_send(0x00);
614 bluefruit_serial_send(0x00); 736 bluefruit_serial_send(0x02);
615 bluefruit_serial_send(0x00); 737 bluefruit_serial_send((bitmap>>8)&0xFF);
616 bluefruit_serial_send(0x00); 738 bluefruit_serial_send(bitmap&0xFF);
739 bluefruit_serial_send(0x00);
740 bluefruit_serial_send(0x00);
741 bluefruit_serial_send(0x00);
742 bluefruit_serial_send(0x00);
743 #endif
744 }
617#endif 745#endif
618 746
619 uint8_t timeout = 255; 747 if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
620 748 return;
621 if (USB_DeviceState != DEVICE_STATE_Configured) 749 }
622 return;
623 750
624 report_extra_t r = { 751 report_extra_t r = {
625 .report_id = REPORT_ID_CONSUMER, 752 .report_id = REPORT_ID_CONSUMER,
@@ -709,7 +836,7 @@ int8_t sendchar(uint8_t c)
709 ******************************************************************************/ 836 ******************************************************************************/
710 837
711#ifdef MIDI_ENABLE 838#ifdef MIDI_ENABLE
712void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) { 839static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) {
713 MIDI_EventPacket_t event; 840 MIDI_EventPacket_t event;
714 event.Data1 = byte0; 841 event.Data1 = byte0;
715 event.Data2 = byte1; 842 event.Data2 = byte1;
@@ -769,7 +896,7 @@ void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byt
769 USB_USBTask(); 896 USB_USBTask();
770} 897}
771 898
772void usb_get_midi(MidiDevice * device) { 899static void usb_get_midi(MidiDevice * device) {
773 MIDI_EventPacket_t event; 900 MIDI_EventPacket_t event;
774 while (MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, &event)) { 901 while (MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, &event)) {
775 902
@@ -799,12 +926,12 @@ void usb_get_midi(MidiDevice * device) {
799 USB_USBTask(); 926 USB_USBTask();
800} 927}
801 928
802void midi_usb_init(MidiDevice * device){ 929static void midi_usb_init(MidiDevice * device){
803 midi_device_init(device); 930 midi_device_init(device);
804 midi_device_set_send_func(device, usb_send_func); 931 midi_device_set_send_func(device, usb_send_func);
805 midi_device_set_pre_input_process_func(device, usb_get_midi); 932 midi_device_set_pre_input_process_func(device, usb_get_midi);
806 933
807 SetupHardware(); 934 // SetupHardware();
808 sei(); 935 sei();
809} 936}
810 937
@@ -969,16 +1096,23 @@ void cc_callback(MidiDevice * device,
969 uint8_t chan, uint8_t num, uint8_t val); 1096 uint8_t chan, uint8_t num, uint8_t val);
970void sysex_callback(MidiDevice * device, 1097void sysex_callback(MidiDevice * device,
971 uint16_t start, uint8_t length, uint8_t * data); 1098 uint16_t start, uint8_t length, uint8_t * data);
1099
1100void setup_midi(void)
1101{
1102#ifdef MIDI_ADVANCED
1103 midi_init();
1104#endif
1105 midi_device_init(&midi_device);
1106 midi_device_set_send_func(&midi_device, usb_send_func);
1107 midi_device_set_pre_input_process_func(&midi_device, usb_get_midi);
1108}
972#endif 1109#endif
973 1110
974int main(void) __attribute__ ((weak)); 1111int main(void) __attribute__ ((weak));
975int main(void) 1112int main(void)
976{ 1113{
977
978#ifdef MIDI_ENABLE 1114#ifdef MIDI_ENABLE
979 midi_device_init(&midi_device); 1115 setup_midi();
980 midi_device_set_send_func(&midi_device, usb_send_func);
981 midi_device_set_pre_input_process_func(&midi_device, usb_get_midi);
982#endif 1116#endif
983 1117
984 setup_mcu(); 1118 setup_mcu();
@@ -998,7 +1132,7 @@ int main(void)
998 // midi_send_noteoff(&midi_device, 0, 64, 127); 1132 // midi_send_noteoff(&midi_device, 0, 64, 127);
999#endif 1133#endif
1000 1134
1001#ifdef BLUETOOTH_ENABLE 1135#ifdef MODULE_ADAFRUIT_EZKEY
1002 serial_init(); 1136 serial_init();
1003#endif 1137#endif
1004 1138
@@ -1029,7 +1163,7 @@ int main(void)
1029 1163
1030 print("Keyboard start.\n"); 1164 print("Keyboard start.\n");
1031 while (1) { 1165 while (1) {
1032 #ifndef BLUETOOTH_ENABLE 1166 #if !defined(BLUETOOTH_ENABLE)
1033 while (USB_DeviceState == DEVICE_STATE_Suspended) { 1167 while (USB_DeviceState == DEVICE_STATE_Suspended) {
1034 print("[s]"); 1168 print("[s]");
1035 suspend_power_down(); 1169 suspend_power_down();
@@ -1039,20 +1173,36 @@ int main(void)
1039 } 1173 }
1040 #endif 1174 #endif
1041 1175
1176 keyboard_task();
1177
1042#ifdef MIDI_ENABLE 1178#ifdef MIDI_ENABLE
1043 midi_device_process(&midi_device); 1179 midi_device_process(&midi_device);
1044 // MIDI_Task(); 1180#ifdef MIDI_ADVANCED
1181 midi_task();
1182#endif
1183#endif
1184
1185#if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
1186 rgblight_task();
1187#endif
1188
1189#ifdef MODULE_ADAFRUIT_BLE
1190 adafruit_ble_task();
1045#endif 1191#endif
1046 keyboard_task();
1047 1192
1048#ifdef VIRTSER_ENABLE 1193#ifdef VIRTSER_ENABLE
1049 virtser_task(); 1194 virtser_task();
1050 CDC_Device_USBTask(&cdc_device); 1195 CDC_Device_USBTask(&cdc_device);
1051#endif 1196#endif
1052 1197
1198#ifdef RAW_ENABLE
1199 raw_hid_task();
1200#endif
1201
1053#if !defined(INTERRUPT_CONTROL_ENDPOINT) 1202#if !defined(INTERRUPT_CONTROL_ENDPOINT)
1054 USB_USBTask(); 1203 USB_USBTask();
1055#endif 1204#endif
1205
1056 } 1206 }
1057} 1207}
1058 1208
@@ -1077,15 +1227,50 @@ void fallthrough_callback(MidiDevice * device,
1077#endif 1227#endif
1078} 1228}
1079 1229
1230
1080void cc_callback(MidiDevice * device, 1231void cc_callback(MidiDevice * device,
1081 uint8_t chan, uint8_t num, uint8_t val) { 1232 uint8_t chan, uint8_t num, uint8_t val) {
1082 //sending it back on the next channel 1233 //sending it back on the next channel
1083 midi_send_cc(device, (chan + 1) % 16, num, val); 1234 // midi_send_cc(device, (chan + 1) % 16, num, val);
1084} 1235}
1085 1236
1086void sysex_callback(MidiDevice * device, 1237#ifdef API_SYSEX_ENABLE
1087 uint16_t start, uint8_t length, uint8_t * data) { 1238uint8_t midi_buffer[MIDI_SYSEX_BUFFER] = {0};
1088 for (int i = 0; i < length; i++) 1239#endif
1089 midi_send_cc(device, 15, 0x7F & data[i], 0x7F & (start + i)); 1240
1241void sysex_callback(MidiDevice * device, uint16_t start, uint8_t length, uint8_t * data) {
1242 #ifdef API_SYSEX_ENABLE
1243 // SEND_STRING("\n");
1244 // send_word(start);
1245 // SEND_STRING(": ");
1246 // Don't store the header
1247 int16_t pos = start - 4;
1248 for (uint8_t place = 0; place < length; place++) {
1249 // send_byte(*data);
1250 if (pos >= 0) {
1251 if (*data == 0xF7) {
1252 // SEND_STRING("\nRD: ");
1253 // for (uint8_t i = 0; i < start + place + 1; i++){
1254 // send_byte(midi_buffer[i]);
1255 // SEND_STRING(" ");
1256 // }
1257 const unsigned decoded_length = sysex_decoded_length(pos);
1258 uint8_t decoded[API_SYSEX_MAX_SIZE];
1259 sysex_decode(decoded, midi_buffer, pos);
1260 process_api(decoded_length, decoded);
1261 return;
1262 }
1263 else if (pos >= MIDI_SYSEX_BUFFER) {
1264 return;
1265 }
1266 midi_buffer[pos] = *data;
1267 }
1268 // SEND_STRING(" ");
1269 data++;
1270 pos++;
1271 }
1272 #endif
1090} 1273}
1274
1275
1091#endif 1276#endif
diff --git a/tmk_core/protocol/lufa/lufa.h b/tmk_core/protocol/lufa/lufa.h
index aad08d640..a51573786 100644
--- a/tmk_core/protocol/lufa/lufa.h
+++ b/tmk_core/protocol/lufa/lufa.h
@@ -49,7 +49,7 @@
49#include <LUFA/Drivers/USB/USB.h> 49#include <LUFA/Drivers/USB/USB.h>
50#include "host.h" 50#include "host.h"
51#ifdef MIDI_ENABLE 51#ifdef MIDI_ENABLE
52 #include "midi.h" 52 #include "process_midi.h"
53#endif 53#endif
54#ifdef __cplusplus 54#ifdef __cplusplus
55extern "C" { 55extern "C" {
@@ -68,8 +68,19 @@ typedef struct {
68} __attribute__ ((packed)) report_extra_t; 68} __attribute__ ((packed)) report_extra_t;
69 69
70#ifdef MIDI_ENABLE 70#ifdef MIDI_ENABLE
71void MIDI_Task(void); 71 void MIDI_Task(void);
72MidiDevice midi_device; 72 MidiDevice midi_device;
73#endif
74
75#ifdef API_ENABLE
76 #include "api.h"
77#endif
78
79#ifdef API_SYSEX_ENABLE
80 #include "api_sysex.h"
81 // Allocate space for encoding overhead.
82 //The header and terminator are not stored to save a few bytes of precious ram
83 #define MIDI_SYSEX_BUFFER (API_SYSEX_MAX_SIZE + API_SYSEX_MAX_SIZE / 7 + (API_SYSEX_MAX_SIZE % 7 ? 1 : 0))
73#endif 84#endif
74 85
75// #if LUFA_VERSION_INTEGER < 0x120730 86// #if LUFA_VERSION_INTEGER < 0x120730
diff --git a/tmk_core/protocol/lufa/outputselect.c b/tmk_core/protocol/lufa/outputselect.c
new file mode 100644
index 000000000..0df5d3b75
--- /dev/null
+++ b/tmk_core/protocol/lufa/outputselect.c
@@ -0,0 +1,56 @@
1/*
2Copyright 2017 Priyadi Iman Nurcahyo
3This program is free software: you can redistribute it and/or modify
4it under the terms of the GNU General Public License as published by
5the Free Software Foundation, either version 2 of the License, or
6(at your option) any later version.
7This program is distributed in the hope that it will be useful,
8but WITHOUT ANY WARRANTY; without even the implied warranty of
9MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10GNU General Public License for more details.
11You should have received a copy of the GNU General Public License
12along with this program. If not, see <http://www.gnu.org/licenses/>.
13*/
14
15#include "lufa.h"
16#include "outputselect.h"
17#ifdef MODULE_ADAFRUIT_BLE
18 #include "adafruit_ble.h"
19#endif
20
21uint8_t desired_output = OUTPUT_DEFAULT;
22
23void set_output(uint8_t output) {
24 set_output_user(output);
25 desired_output = output;
26}
27
28__attribute__((weak))
29void set_output_user(uint8_t output) {
30}
31
32uint8_t auto_detect_output(void) {
33 if (USB_DeviceState == DEVICE_STATE_Configured) {
34 return OUTPUT_USB;
35 }
36
37#ifdef MODULE_ADAFRUIT_BLE
38 if (adafruit_ble_is_connected()) {
39 return OUTPUT_BLUETOOTH;
40 }
41#endif
42
43#ifdef BLUETOOTH_ENABLE
44 return OUTPUT_BLUETOOTH; // should check if BT is connected here
45#endif
46
47 return OUTPUT_NONE;
48}
49
50uint8_t where_to_send(void) {
51 if (desired_output == OUTPUT_AUTO) {
52 return auto_detect_output();
53 }
54 return desired_output;
55}
56
diff --git a/tmk_core/protocol/lufa/outputselect.h b/tmk_core/protocol/lufa/outputselect.h
new file mode 100644
index 000000000..28cc3298e
--- /dev/null
+++ b/tmk_core/protocol/lufa/outputselect.h
@@ -0,0 +1,40 @@
1/*
2Copyright 2017 Priyadi Iman Nurcahyo
3This program is free software: you can redistribute it and/or modify
4it under the terms of the GNU General Public License as published by
5the Free Software Foundation, either version 2 of the License, or
6(at your option) any later version.
7This program is distributed in the hope that it will be useful,
8but WITHOUT ANY WARRANTY; without even the implied warranty of
9MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10GNU General Public License for more details.
11You should have received a copy of the GNU General Public License
12along with this program. If not, see <http://www.gnu.org/licenses/>.
13*/
14
15enum outputs {
16 OUTPUT_AUTO,
17
18 OUTPUT_NONE,
19 OUTPUT_USB,
20 OUTPUT_BLUETOOTH,
21
22 // backward compatibility
23 OUTPUT_USB_AND_BT
24};
25
26/**
27 * backward compatibility for BLUETOOTH_ENABLE, send to BT and USB by default
28 */
29#ifndef OUTPUT_DEFAULT
30 #ifdef BLUETOOTH_ENABLE
31 #define OUTPUT_DEFAULT OUTPUT_USB_AND_BT
32 #else
33 #define OUTPUT_DEFAULT OUTPUT_AUTO
34 #endif
35#endif
36
37void set_output(uint8_t output);
38void set_output_user(uint8_t output);
39uint8_t auto_detect_output(void);
40uint8_t where_to_send(void); \ No newline at end of file
diff --git a/tmk_core/protocol/lufa/ringbuffer.hpp b/tmk_core/protocol/lufa/ringbuffer.hpp
new file mode 100644
index 000000000..70a3c4881
--- /dev/null
+++ b/tmk_core/protocol/lufa/ringbuffer.hpp
@@ -0,0 +1,66 @@
1#pragma once
2// A simple ringbuffer holding Size elements of type T
3template <typename T, uint8_t Size>
4class RingBuffer {
5 protected:
6 T buf_[Size];
7 uint8_t head_{0}, tail_{0};
8 public:
9 inline uint8_t nextPosition(uint8_t position) {
10 return (position + 1) % Size;
11 }
12
13 inline uint8_t prevPosition(uint8_t position) {
14 if (position == 0) {
15 return Size - 1;
16 }
17 return position - 1;
18 }
19
20 inline bool enqueue(const T &item) {
21 static_assert(Size > 1, "RingBuffer size must be > 1");
22 uint8_t next = nextPosition(head_);
23 if (next == tail_) {
24 // Full
25 return false;
26 }
27
28 buf_[head_] = item;
29 head_ = next;
30 return true;
31 }
32
33 inline bool get(T &dest, bool commit = true) {
34 auto tail = tail_;
35 if (tail == head_) {
36 // No more data
37 return false;
38 }
39
40 dest = buf_[tail];
41 tail = nextPosition(tail);
42
43 if (commit) {
44 tail_ = tail;
45 }
46 return true;
47 }
48
49 inline bool empty() const { return head_ == tail_; }
50
51 inline uint8_t size() const {
52 int diff = head_ - tail_;
53 if (diff >= 0) {
54 return diff;
55 }
56 return Size + diff;
57 }
58
59 inline T& front() {
60 return buf_[tail_];
61 }
62
63 inline bool peek(T &item) {
64 return get(item, false);
65 }
66};
diff --git a/tmk_core/protocol/midi.mk b/tmk_core/protocol/midi.mk
index c85ae42ff..4855b23d3 100644
--- a/tmk_core/protocol/midi.mk
+++ b/tmk_core/protocol/midi.mk
@@ -4,6 +4,7 @@ SRC += midi.c \
4 midi_device.c \ 4 midi_device.c \
5 bytequeue/bytequeue.c \ 5 bytequeue/bytequeue.c \
6 bytequeue/interrupt_setting.c \ 6 bytequeue/interrupt_setting.c \
7 sysex_tools.c \
7 $(LUFA_SRC_USBCLASS) 8 $(LUFA_SRC_USBCLASS)
8 9
9VPATH += $(TMK_PATH)/$(MIDI_DIR) \ No newline at end of file 10VPATH += $(TMK_PATH)/$(MIDI_DIR) \ No newline at end of file
diff --git a/tmk_core/protocol/ps2_mouse.c b/tmk_core/protocol/ps2_mouse.c
index c3e8b3c1c..d9ccbecb4 100644
--- a/tmk_core/protocol/ps2_mouse.c
+++ b/tmk_core/protocol/ps2_mouse.c
@@ -18,60 +18,59 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
18#include <stdbool.h> 18#include <stdbool.h>
19#include<avr/io.h> 19#include<avr/io.h>
20#include<util/delay.h> 20#include<util/delay.h>
21#include "ps2.h"
22#include "ps2_mouse.h" 21#include "ps2_mouse.h"
23#include "report.h"
24#include "host.h" 22#include "host.h"
25#include "timer.h" 23#include "timer.h"
26#include "print.h" 24#include "print.h"
25#include "report.h"
27#include "debug.h" 26#include "debug.h"
27#include "ps2.h"
28 28
29/* ============================= MACROS ============================ */
29 30
30static report_mouse_t mouse_report = {}; 31static report_mouse_t mouse_report = {};
31 32
33static inline void ps2_mouse_print_report(report_mouse_t *mouse_report);
34static inline void ps2_mouse_convert_report_to_hid(report_mouse_t *mouse_report);
35static inline void ps2_mouse_clear_report(report_mouse_t *mouse_report);
36static inline void ps2_mouse_enable_scrolling(void);
37static inline void ps2_mouse_scroll_button_task(report_mouse_t *mouse_report);
32 38
33static void print_usb_data(void); 39/* ============================= IMPLEMENTATION ============================ */
34
35 40
36/* supports only 3 button mouse at this time */ 41/* supports only 3 button mouse at this time */
37uint8_t ps2_mouse_init(void) { 42void ps2_mouse_init(void) {
38 uint8_t rcv;
39
40 ps2_host_init(); 43 ps2_host_init();
41 44
42 _delay_ms(1000); // wait for powering up 45 _delay_ms(PS2_MOUSE_INIT_DELAY); // wait for powering up
43 46
44 // send Reset 47 PS2_MOUSE_SEND(PS2_MOUSE_RESET, "ps2_mouse_init: sending reset");
45 rcv = ps2_host_send(0xFF);
46 print("ps2_mouse_init: send Reset: ");
47 phex(rcv); phex(ps2_error); print("\n");
48 48
49 // read completion code of BAT 49 PS2_MOUSE_RECEIVE("ps2_mouse_init: read BAT");
50 rcv = ps2_host_recv_response(); 50 PS2_MOUSE_RECEIVE("ps2_mouse_init: read DevID");
51 print("ps2_mouse_init: read BAT: ");
52 phex(rcv); phex(ps2_error); print("\n");
53 51
54 // read Device ID 52#ifdef PS2_MOUSE_USE_REMOTE_MODE
55 rcv = ps2_host_recv_response(); 53 ps2_mouse_set_remote_mode();
56 print("ps2_mouse_init: read DevID: "); 54#else
57 phex(rcv); phex(ps2_error); print("\n"); 55 ps2_mouse_enable_data_reporting();
56#endif
57
58#ifdef PS2_MOUSE_ENABLE_SCROLLING
59 ps2_mouse_enable_scrolling();
60#endif
58 61
59 // send Set Remote mode 62#ifdef PS2_MOUSE_USE_2_1_SCALING
60 rcv = ps2_host_send(0xF0); 63 ps2_mouse_set_scaling_2_1();
61 print("ps2_mouse_init: send 0xF0: "); 64#endif
62 phex(rcv); phex(ps2_error); print("\n");
63 65
64 return 0; 66 ps2_mouse_init_user();
65} 67}
66 68
67#define X_IS_NEG (mouse_report.buttons & (1<<PS2_MOUSE_X_SIGN)) 69__attribute__((weak))
68#define Y_IS_NEG (mouse_report.buttons & (1<<PS2_MOUSE_Y_SIGN)) 70void ps2_mouse_init_user(void) {
69#define X_IS_OVF (mouse_report.buttons & (1<<PS2_MOUSE_X_OVFLW)) 71}
70#define Y_IS_OVF (mouse_report.buttons & (1<<PS2_MOUSE_Y_OVFLW)) 72
71void ps2_mouse_task(void) 73void ps2_mouse_task(void) {
72{
73 enum { SCROLL_NONE, SCROLL_BTN, SCROLL_SENT };
74 static uint8_t scroll_state = SCROLL_NONE;
75 static uint8_t buttons_prev = 0; 74 static uint8_t buttons_prev = 0;
76 75
77 /* receives packet from mouse */ 76 /* receives packet from mouse */
@@ -79,142 +78,169 @@ void ps2_mouse_task(void)
79 rcv = ps2_host_send(PS2_MOUSE_READ_DATA); 78 rcv = ps2_host_send(PS2_MOUSE_READ_DATA);
80 if (rcv == PS2_ACK) { 79 if (rcv == PS2_ACK) {
81 mouse_report.buttons = ps2_host_recv_response(); 80 mouse_report.buttons = ps2_host_recv_response();
82 mouse_report.x = ps2_host_recv_response(); 81 mouse_report.x = ps2_host_recv_response() * PS2_MOUSE_X_MULTIPLIER;
83 mouse_report.y = ps2_host_recv_response(); 82 mouse_report.y = ps2_host_recv_response() * PS2_MOUSE_Y_MULTIPLIER;
83#ifdef PS2_MOUSE_ENABLE_SCROLLING
84 mouse_report.v = -(ps2_host_recv_response() & PS2_MOUSE_SCROLL_MASK) * PS2_MOUSE_V_MULTIPLIER;
85#endif
84 } else { 86 } else {
85 if (debug_mouse) print("ps2_mouse: fail to get mouse packet\n"); 87 if (debug_mouse) print("ps2_mouse: fail to get mouse packet\n");
86 return; 88 return;
87 } 89 }
88 xprintf("%ud ", timer_read());
89 print("ps2_mouse raw: [");
90 phex(mouse_report.buttons); print("|");
91 print_hex8((uint8_t)mouse_report.x); print(" ");
92 print_hex8((uint8_t)mouse_report.y); print("]\n");
93 90
94 /* if mouse moves or buttons state changes */ 91 /* if mouse moves or buttons state changes */
95 if (mouse_report.x || mouse_report.y || 92 if (mouse_report.x || mouse_report.y || mouse_report.v ||
96 ((mouse_report.buttons ^ buttons_prev) & PS2_MOUSE_BTN_MASK)) { 93 ((mouse_report.buttons ^ buttons_prev) & PS2_MOUSE_BTN_MASK)) {
97 94#ifdef PS2_MOUSE_DEBUG_RAW
98#ifdef PS2_MOUSE_DEBUG 95 // Used to debug raw ps2 bytes from mouse
99 print("ps2_mouse raw: ["); 96 ps2_mouse_print_report(&mouse_report);
100 phex(mouse_report.buttons); print("|");
101 print_hex8((uint8_t)mouse_report.x); print(" ");
102 print_hex8((uint8_t)mouse_report.y); print("]\n");
103#endif 97#endif
104
105 buttons_prev = mouse_report.buttons; 98 buttons_prev = mouse_report.buttons;
99 ps2_mouse_convert_report_to_hid(&mouse_report);
100#if PS2_MOUSE_SCROLL_BTN_MASK
101 ps2_mouse_scroll_button_task(&mouse_report);
102#endif
103#ifdef PS2_MOUSE_DEBUG_HID
104 // Used to debug the bytes sent to the host
105 ps2_mouse_print_report(&mouse_report);
106#endif
107 host_mouse_send(&mouse_report);
108 }
109
110 ps2_mouse_clear_report(&mouse_report);
111}
106 112
107 // PS/2 mouse data is '9-bit integer'(-256 to 255) which is comprised of sign-bit and 8-bit value. 113void ps2_mouse_disable_data_reporting(void) {
108 // bit: 8 7 ... 0 114 PS2_MOUSE_SEND(PS2_MOUSE_DISABLE_DATA_REPORTING, "ps2 mouse disable data reporting");
109 // sign \8-bit/ 115}
110 //
111 // Meanwhile USB HID mouse indicates 8bit data(-127 to 127), note that -128 is not used.
112 //
113 // This converts PS/2 data into HID value. Use only -127-127 out of PS/2 9-bit.
114 mouse_report.x = X_IS_NEG ?
115 ((!X_IS_OVF && -127 <= mouse_report.x && mouse_report.x <= -1) ? mouse_report.x : -127) :
116 ((!X_IS_OVF && 0 <= mouse_report.x && mouse_report.x <= 127) ? mouse_report.x : 127);
117 mouse_report.y = Y_IS_NEG ?
118 ((!Y_IS_OVF && -127 <= mouse_report.y && mouse_report.y <= -1) ? mouse_report.y : -127) :
119 ((!Y_IS_OVF && 0 <= mouse_report.y && mouse_report.y <= 127) ? mouse_report.y : 127);
120 116
121 // remove sign and overflow flags 117void ps2_mouse_enable_data_reporting(void) {
122 mouse_report.buttons &= PS2_MOUSE_BTN_MASK; 118 PS2_MOUSE_SEND(PS2_MOUSE_ENABLE_DATA_REPORTING, "ps2 mouse enable data reporting");
119}
123 120
124 // invert coordinate of y to conform to USB HID mouse 121void ps2_mouse_set_remote_mode(void) {
125 mouse_report.y = -mouse_report.y; 122 PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_REMOTE_MODE, "ps2 mouse set remote mode");
123 ps2_mouse_mode = PS2_MOUSE_REMOTE_MODE;
124}
126 125
126void ps2_mouse_set_stream_mode(void) {
127 PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_STREAM_MODE, "ps2 mouse set stream mode");
128 ps2_mouse_mode = PS2_MOUSE_STREAM_MODE;
129}
127 130
128#if PS2_MOUSE_SCROLL_BTN_MASK 131void ps2_mouse_set_scaling_2_1(void) {
129 static uint16_t scroll_button_time = 0; 132 PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_SCALING_2_1, "ps2 mouse set scaling 2:1");
130 if ((mouse_report.buttons & (PS2_MOUSE_SCROLL_BTN_MASK)) == (PS2_MOUSE_SCROLL_BTN_MASK)) { 133}
131 if (scroll_state == SCROLL_NONE) { 134
132 scroll_button_time = timer_read(); 135void ps2_mouse_set_scaling_1_1(void) {
133 scroll_state = SCROLL_BTN; 136 PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_SCALING_1_1, "ps2 mouse set scaling 1:1");
134 } 137}
135 138
136 // doesn't send Scroll Button 139void ps2_mouse_set_resolution(ps2_mouse_resolution_t resolution) {
137 //mouse_report.buttons &= ~(PS2_MOUSE_SCROLL_BTN_MASK); 140 PS2_MOUSE_SET_SAFE(PS2_MOUSE_SET_RESOLUTION, resolution, "ps2 mouse set resolution");
138 141}
139 if (mouse_report.x || mouse_report.y) { 142
140 scroll_state = SCROLL_SENT; 143void ps2_mouse_set_sample_rate(ps2_mouse_sample_rate_t sample_rate) {
141 144 PS2_MOUSE_SET_SAFE(PS2_MOUSE_SET_SAMPLE_RATE, sample_rate, "ps2 mouse set sample rate");
142 mouse_report.v = -mouse_report.y/(PS2_MOUSE_SCROLL_DIVISOR_V); 145}
143 mouse_report.h = mouse_report.x/(PS2_MOUSE_SCROLL_DIVISOR_H); 146
144 mouse_report.x = 0; 147/* ============================= HELPERS ============================ */
145 mouse_report.y = 0; 148
146 //host_mouse_send(&mouse_report); 149#define X_IS_NEG (mouse_report->buttons & (1<<PS2_MOUSE_X_SIGN))
147 } 150#define Y_IS_NEG (mouse_report->buttons & (1<<PS2_MOUSE_Y_SIGN))
151#define X_IS_OVF (mouse_report->buttons & (1<<PS2_MOUSE_X_OVFLW))
152#define Y_IS_OVF (mouse_report->buttons & (1<<PS2_MOUSE_Y_OVFLW))
153static inline void ps2_mouse_convert_report_to_hid(report_mouse_t *mouse_report) {
154 // PS/2 mouse data is '9-bit integer'(-256 to 255) which is comprised of sign-bit and 8-bit value.
155 // bit: 8 7 ... 0
156 // sign \8-bit/
157 //
158 // Meanwhile USB HID mouse indicates 8bit data(-127 to 127), note that -128 is not used.
159 //
160 // This converts PS/2 data into HID value. Use only -127-127 out of PS/2 9-bit.
161 mouse_report->x = X_IS_NEG ?
162 ((!X_IS_OVF && -127 <= mouse_report->x && mouse_report->x <= -1) ? mouse_report->x : -127) :
163 ((!X_IS_OVF && 0 <= mouse_report->x && mouse_report->x <= 127) ? mouse_report->x : 127);
164 mouse_report->y = Y_IS_NEG ?
165 ((!Y_IS_OVF && -127 <= mouse_report->y && mouse_report->y <= -1) ? mouse_report->y : -127) :
166 ((!Y_IS_OVF && 0 <= mouse_report->y && mouse_report->y <= 127) ? mouse_report->y : 127);
167
168 // remove sign and overflow flags
169 mouse_report->buttons &= PS2_MOUSE_BTN_MASK;
170
171 // invert coordinate of y to conform to USB HID mouse
172 mouse_report->y = -mouse_report->y;
173}
174
175static inline void ps2_mouse_clear_report(report_mouse_t *mouse_report) {
176 mouse_report->x = 0;
177 mouse_report->y = 0;
178 mouse_report->v = 0;
179 mouse_report->h = 0;
180 mouse_report->buttons = 0;
181}
182
183static inline void ps2_mouse_print_report(report_mouse_t *mouse_report) {
184 if (!debug_mouse) return;
185 print("ps2_mouse: [");
186 phex(mouse_report->buttons); print("|");
187 print_hex8((uint8_t)mouse_report->x); print(" ");
188 print_hex8((uint8_t)mouse_report->y); print(" ");
189 print_hex8((uint8_t)mouse_report->v); print(" ");
190 print_hex8((uint8_t)mouse_report->h); print("]\n");
191}
192
193static inline void ps2_mouse_enable_scrolling(void) {
194 PS2_MOUSE_SEND(PS2_MOUSE_SET_SAMPLE_RATE, "Initiaing scroll wheel enable: Set sample rate");
195 PS2_MOUSE_SEND(200, "200");
196 PS2_MOUSE_SEND(PS2_MOUSE_SET_SAMPLE_RATE, "Set sample rate");
197 PS2_MOUSE_SEND(100, "100");
198 PS2_MOUSE_SEND(PS2_MOUSE_SET_SAMPLE_RATE, "Set sample rate");
199 PS2_MOUSE_SEND(80, "80");
200 PS2_MOUSE_SEND(PS2_MOUSE_GET_DEVICE_ID, "Finished enabling scroll wheel");
201 _delay_ms(20);
202}
203
204#define PRESS_SCROLL_BUTTONS mouse_report->buttons |= (PS2_MOUSE_SCROLL_BTN_MASK)
205#define RELEASE_SCROLL_BUTTONS mouse_report->buttons &= ~(PS2_MOUSE_SCROLL_BTN_MASK)
206static inline void ps2_mouse_scroll_button_task(report_mouse_t *mouse_report) {
207 static enum {
208 SCROLL_NONE,
209 SCROLL_BTN,
210 SCROLL_SENT,
211 } scroll_state = SCROLL_NONE;
212 static uint16_t scroll_button_time = 0;
213
214 if (PS2_MOUSE_SCROLL_BTN_MASK == (mouse_report->buttons & (PS2_MOUSE_SCROLL_BTN_MASK))) {
215 // All scroll buttons are pressed
216
217 if (scroll_state == SCROLL_NONE) {
218 scroll_button_time = timer_read();
219 scroll_state = SCROLL_BTN;
148 } 220 }
149 else if ((mouse_report.buttons & (PS2_MOUSE_SCROLL_BTN_MASK)) == 0) { 221
222 // If the mouse has moved, update the report to scroll instead of move the mouse
223 if (mouse_report->x || mouse_report->y) {
224 scroll_state = SCROLL_SENT;
225 mouse_report->v = -mouse_report->y/(PS2_MOUSE_SCROLL_DIVISOR_V);
226 mouse_report->h = mouse_report->x/(PS2_MOUSE_SCROLL_DIVISOR_H);
227 mouse_report->x = 0;
228 mouse_report->y = 0;
229 }
230 } else if (0 == (PS2_MOUSE_SCROLL_BTN_MASK & mouse_report->buttons)) {
231 // None of the scroll buttons are pressed
232
150#if PS2_MOUSE_SCROLL_BTN_SEND 233#if PS2_MOUSE_SCROLL_BTN_SEND
151 if (scroll_state == SCROLL_BTN && 234 if (scroll_state == SCROLL_BTN
152 TIMER_DIFF_16(timer_read(), scroll_button_time) < PS2_MOUSE_SCROLL_BTN_SEND) { 235 && timer_elapsed(scroll_button_time) < PS2_MOUSE_SCROLL_BTN_SEND) {
153 // send Scroll Button(down and up at once) when not scrolled 236 PRESS_SCROLL_BUTTONS;
154 mouse_report.buttons |= (PS2_MOUSE_SCROLL_BTN_MASK); 237 host_mouse_send(mouse_report);
155 host_mouse_send(&mouse_report); 238 _delay_ms(100);
156 _delay_ms(100); 239 RELEASE_SCROLL_BUTTONS;
157 mouse_report.buttons &= ~(PS2_MOUSE_SCROLL_BTN_MASK);
158 }
159#endif
160 scroll_state = SCROLL_NONE;
161 } 240 }
162 // doesn't send Scroll Button
163 mouse_report.buttons &= ~(PS2_MOUSE_SCROLL_BTN_MASK);
164#endif 241#endif
165 242 scroll_state = SCROLL_NONE;
166
167 host_mouse_send(&mouse_report);
168 print_usb_data();
169 } 243 }
170 // clear report
171 mouse_report.x = 0;
172 mouse_report.y = 0;
173 mouse_report.v = 0;
174 mouse_report.h = 0;
175 mouse_report.buttons = 0;
176}
177 244
178static void print_usb_data(void) 245 RELEASE_SCROLL_BUTTONS;
179{ 246}
180 if (!debug_mouse) return;
181 print("ps2_mouse usb: [");
182 phex(mouse_report.buttons); print("|");
183 print_hex8((uint8_t)mouse_report.x); print(" ");
184 print_hex8((uint8_t)mouse_report.y); print(" ");
185 print_hex8((uint8_t)mouse_report.v); print(" ");
186 print_hex8((uint8_t)mouse_report.h); print("]\n");
187}
188
189
190/* PS/2 Mouse Synopsis
191 * http://www.computer-engineering.org/ps2mouse/
192 *
193 * Command:
194 * 0xFF: Reset
195 * 0xF6: Set Defaults Sampling; rate=100, resolution=4cnt/mm, scaling=1:1, reporting=disabled
196 * 0xF5: Disable Data Reporting
197 * 0xF4: Enable Data Reporting
198 * 0xF3: Set Sample Rate
199 * 0xF2: Get Device ID
200 * 0xF0: Set Remote Mode
201 * 0xEB: Read Data
202 * 0xEA: Set Stream Mode
203 * 0xE9: Status Request
204 * 0xE8: Set Resolution
205 * 0xE7: Set Scaling 2:1
206 * 0xE6: Set Scaling 1:1
207 *
208 * Mode:
209 * Stream Mode: devices sends the data when it changs its state
210 * Remote Mode: host polls the data periodically
211 *
212 * This code uses Remote Mode and polls the data with Read Data(0xEB).
213 *
214 * Data format:
215 * byte|7 6 5 4 3 2 1 0
216 * ----+--------------------------------------------------------------
217 * 0|Yovflw Xovflw Ysign Xsign 1 Middle Right Left
218 * 1| X movement
219 * 2| Y movement
220 */
diff --git a/tmk_core/protocol/ps2_mouse.h b/tmk_core/protocol/ps2_mouse.h
index 27d9790d4..eeeffe4d8 100644
--- a/tmk_core/protocol/ps2_mouse.h
+++ b/tmk_core/protocol/ps2_mouse.h
@@ -19,16 +19,62 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
19#define PS2_MOUSE_H 19#define PS2_MOUSE_H
20 20
21#include <stdbool.h> 21#include <stdbool.h>
22#include "debug.h"
22 23
23#define PS2_MOUSE_READ_DATA 0xEB 24#define PS2_MOUSE_SEND(command, message) \
25do { \
26 __attribute__ ((unused)) uint8_t rcv = ps2_host_send(command); \
27 if (debug_mouse) { \
28 print((message)); \
29 xprintf(" command: %X, result: %X, error: %X \n", command, rcv, ps2_error); \
30 } \
31} while(0)
32
33#define PS2_MOUSE_SEND_SAFE(command, message) \
34do { \
35 if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
36 ps2_mouse_disable_data_reporting(); \
37 } \
38 PS2_MOUSE_SEND(command, message); \
39 if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
40 ps2_mouse_enable_data_reporting(); \
41 } \
42} while(0)
43
44#define PS2_MOUSE_SET_SAFE(command, value, message) \
45do { \
46 if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
47 ps2_mouse_disable_data_reporting(); \
48 } \
49 PS2_MOUSE_SEND(command, message); \
50 PS2_MOUSE_SEND(value, "Sending value"); \
51 if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
52 ps2_mouse_enable_data_reporting(); \
53 } \
54} while(0)
55
56#define PS2_MOUSE_RECEIVE(message) \
57do { \
58 __attribute__ ((unused)) uint8_t rcv = ps2_host_recv_response(); \
59 if (debug_mouse) { \
60 print((message)); \
61 xprintf(" result: %X, error: %X \n", rcv, ps2_error); \
62 } \
63} while(0)
64
65__attribute__ ((unused))
66static enum ps2_mouse_mode_e {
67 PS2_MOUSE_STREAM_MODE,
68 PS2_MOUSE_REMOTE_MODE,
69} ps2_mouse_mode = PS2_MOUSE_STREAM_MODE;
24 70
25/* 71/*
26 * Data format: 72 * Data format:
27 * byte|7 6 5 4 3 2 1 0 73 * byte|7 6 5 4 3 2 1 0
28 * ----+-------------------------------------------------------------- 74 * ----+----------------------------------------------------------------
29 * 0|Yovflw Xovflw Ysign Xsign 1 Middle Right Left 75 * 0|[Yovflw][Xovflw][Ysign ][Xsign ][ 1 ][Middle][Right ][Left ]
30 * 1| X movement(0-255) 76 * 1|[ X movement(0-255) ]
31 * 2| Y movement(0-255) 77 * 2|[ Y movement(0-255) ]
32 */ 78 */
33#define PS2_MOUSE_BTN_MASK 0x07 79#define PS2_MOUSE_BTN_MASK 0x07
34#define PS2_MOUSE_BTN_LEFT 0 80#define PS2_MOUSE_BTN_LEFT 0
@@ -39,10 +85,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
39#define PS2_MOUSE_X_OVFLW 6 85#define PS2_MOUSE_X_OVFLW 6
40#define PS2_MOUSE_Y_OVFLW 7 86#define PS2_MOUSE_Y_OVFLW 7
41 87
42
43/*
44 * Scroll by mouse move with pressing button
45 */
46/* mouse button to start scrolling; set 0 to disable scroll */ 88/* mouse button to start scrolling; set 0 to disable scroll */
47#ifndef PS2_MOUSE_SCROLL_BTN_MASK 89#ifndef PS2_MOUSE_SCROLL_BTN_MASK
48#define PS2_MOUSE_SCROLL_BTN_MASK (1<<PS2_MOUSE_BTN_MIDDLE) 90#define PS2_MOUSE_SCROLL_BTN_MASK (1<<PS2_MOUSE_BTN_MIDDLE)
@@ -58,9 +100,79 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
58#ifndef PS2_MOUSE_SCROLL_DIVISOR_H 100#ifndef PS2_MOUSE_SCROLL_DIVISOR_H
59#define PS2_MOUSE_SCROLL_DIVISOR_H 2 101#define PS2_MOUSE_SCROLL_DIVISOR_H 2
60#endif 102#endif
103/* multiply reported mouse values by these */
104#ifndef PS2_MOUSE_X_MULTIPLIER
105#define PS2_MOUSE_X_MULTIPLIER 1
106#endif
107#ifndef PS2_MOUSE_Y_MULTIPLIER
108#define PS2_MOUSE_Y_MULTIPLIER 1
109#endif
110#ifndef PS2_MOUSE_V_MULTIPLIER
111#define PS2_MOUSE_V_MULTIPLIER 1
112#endif
113/* For some mice this will need to be 0x0F */
114#ifndef PS2_MOUSE_SCROLL_MASK
115#define PS2_MOUSE_SCROLL_MASK 0xFF
116#endif
117#ifndef PS2_MOUSE_INIT_DELAY
118#define PS2_MOUSE_INIT_DELAY 1000
119#endif
61 120
121enum ps2_mouse_command_e {
122 PS2_MOUSE_RESET = 0xFF,
123 PS2_MOUSE_RESEND = 0xFE,
124 PS2_MOSUE_SET_DEFAULTS = 0xF6,
125 PS2_MOUSE_DISABLE_DATA_REPORTING = 0xF5,
126 PS2_MOUSE_ENABLE_DATA_REPORTING = 0xF4,
127 PS2_MOUSE_SET_SAMPLE_RATE = 0xF3,
128 PS2_MOUSE_GET_DEVICE_ID = 0xF2,
129 PS2_MOUSE_SET_REMOTE_MODE = 0xF0,
130 PS2_MOUSE_SET_WRAP_MODE = 0xEC,
131 PS2_MOUSE_READ_DATA = 0xEB,
132 PS2_MOUSE_SET_STREAM_MODE = 0xEA,
133 PS2_MOUSE_STATUS_REQUEST = 0xE9,
134 PS2_MOUSE_SET_RESOLUTION = 0xE8,
135 PS2_MOUSE_SET_SCALING_2_1 = 0xE7,
136 PS2_MOUSE_SET_SCALING_1_1 = 0xE6,
137};
138
139typedef enum ps2_mouse_resolution_e {
140 PS2_MOUSE_1_COUNT_MM,
141 PS2_MOUSE_2_COUNT_MM,
142 PS2_MOUSE_4_COUNT_MM,
143 PS2_MOUSE_8_COUNT_MM,
144} ps2_mouse_resolution_t;
145
146typedef enum ps2_mouse_sample_rate_e {
147 PS2_MOUSE_10_SAMPLES_SEC = 10,
148 PS2_MOUSE_20_SAMPLES_SEC = 20,
149 PS2_MOUSE_40_SAMPLES_SEC = 40,
150 PS2_MOUSE_60_SAMPLES_SEC = 60,
151 PS2_MOUSE_80_SAMPLES_SEC = 80,
152 PS2_MOUSE_100_SAMPLES_SEC = 100,
153 PS2_MOUSE_200_SAMPLES_SEC = 200,
154} ps2_mouse_sample_rate_t;
155
156void ps2_mouse_init(void);
157
158void ps2_mouse_init_user(void);
62 159
63uint8_t ps2_mouse_init(void);
64void ps2_mouse_task(void); 160void ps2_mouse_task(void);
65 161
162void ps2_mouse_disable_data_reporting(void);
163
164void ps2_mouse_enable_data_reporting(void);
165
166void ps2_mouse_set_remote_mode(void);
167
168void ps2_mouse_set_stream_mode(void);
169
170void ps2_mouse_set_scaling_2_1(void);
171
172void ps2_mouse_set_scaling_1_1(void);
173
174void ps2_mouse_set_resolution(ps2_mouse_resolution_t resolution);
175
176void ps2_mouse_set_sample_rate(ps2_mouse_sample_rate_t sample_rate);
177
66#endif 178#endif
diff --git a/tmk_core/protocol/vusb.mk b/tmk_core/protocol/vusb.mk
index 3cba3f71a..897b833e1 100644
--- a/tmk_core/protocol/vusb.mk
+++ b/tmk_core/protocol/vusb.mk
@@ -18,4 +18,5 @@ endif
18 18
19 19
20# Search Path 20# Search Path
21VPATH += $(TMK_DIR)/protocol/vusb:$(TMK_DIR)/protocol/vusb/usbdrv 21VPATH += $(TMK_PATH)/$(VUSB_DIR)
22VPATH += $(TMK_PATH)/$(VUSB_DIR)/usbdrv
diff --git a/tmk_core/protocol/vusb/main.c b/tmk_core/protocol/vusb/main.c
index 8e4a266e9..f6a0c7e9a 100644
--- a/tmk_core/protocol/vusb/main.c
+++ b/tmk_core/protocol/vusb/main.c
@@ -48,8 +48,12 @@ int main(void)
48 uint16_t last_timer = timer_read(); 48 uint16_t last_timer = timer_read();
49#endif 49#endif
50 50
51#ifdef CLKPR
52 // avoid unintentional changes of clock frequency in devices that have a
53 // clock prescaler
51 CLKPR = 0x80, CLKPR = 0; 54 CLKPR = 0x80, CLKPR = 0;
52#ifndef PS2_USE_USART 55#endif
56#ifndef NO_UART
53 uart_init(UART_BAUD_RATE); 57 uart_init(UART_BAUD_RATE);
54#endif 58#endif
55 59
diff --git a/tmk_core/protocol/vusb/vusb.c b/tmk_core/protocol/vusb/vusb.c
index eaa1c512d..022ac6f6b 100644
--- a/tmk_core/protocol/vusb/vusb.c
+++ b/tmk_core/protocol/vusb/vusb.c
@@ -15,6 +15,8 @@ You should have received a copy of the GNU General Public License
15along with this program. If not, see <http://www.gnu.org/licenses/>. 15along with this program. If not, see <http://www.gnu.org/licenses/>.
16*/ 16*/
17 17
18#include <avr/eeprom.h>
19#include <avr/wdt.h>
18#include <stdint.h> 20#include <stdint.h>
19#include "usbdrv.h" 21#include "usbdrv.h"
20#include "usbconfig.h" 22#include "usbconfig.h"
@@ -24,6 +26,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
24#include "debug.h" 26#include "debug.h"
25#include "host_driver.h" 27#include "host_driver.h"
26#include "vusb.h" 28#include "vusb.h"
29#include "bootloader.h"
27 30
28 31
29static uint8_t vusb_keyboard_leds = 0; 32static uint8_t vusb_keyboard_leds = 0;
@@ -163,6 +166,7 @@ static struct {
163 uint16_t len; 166 uint16_t len;
164 enum { 167 enum {
165 NONE, 168 NONE,
169 BOOTLOADER,
166 SET_LED 170 SET_LED
167 } kind; 171 } kind;
168} last_req; 172} last_req;
@@ -193,6 +197,11 @@ usbRequest_t *rq = (void *)data;
193 debug("SET_LED: "); 197 debug("SET_LED: ");
194 last_req.kind = SET_LED; 198 last_req.kind = SET_LED;
195 last_req.len = rq->wLength.word; 199 last_req.len = rq->wLength.word;
200#ifdef BOOTLOADER_SIZE
201 } else if(rq->wValue.word == 0x0301) {
202 last_req.kind = BOOTLOADER;
203 last_req.len = rq->wLength.word;
204#endif
196 } 205 }
197 return USB_NO_MSG; // to get data in usbFunctionWrite 206 return USB_NO_MSG; // to get data in usbFunctionWrite
198 } else { 207 } else {
@@ -220,6 +229,11 @@ uchar usbFunctionWrite(uchar *data, uchar len)
220 last_req.len = 0; 229 last_req.len = 0;
221 return 1; 230 return 1;
222 break; 231 break;
232 case BOOTLOADER:
233 usbDeviceDisconnect();
234 bootloader_jump();
235 return 1;
236 break;
223 case NONE: 237 case NONE:
224 default: 238 default:
225 return -1; 239 return -1;
@@ -266,7 +280,7 @@ const PROGMEM uchar keyboard_hid_report[] = {
266 0x95, 0x06, // Report Count (6), 280 0x95, 0x06, // Report Count (6),
267 0x75, 0x08, // Report Size (8), 281 0x75, 0x08, // Report Size (8),
268 0x15, 0x00, // Logical Minimum (0), 282 0x15, 0x00, // Logical Minimum (0),
269 0x25, 0xFF, 0x00 // Logical Maximum(255), 283 0x26, 0xFF, 0x00, // Logical Maximum(255),
270 0x05, 0x07, // Usage Page (Key Codes), 284 0x05, 0x07, // Usage Page (Key Codes),
271 0x19, 0x00, // Usage Minimum (0), 285 0x19, 0x00, // Usage Minimum (0),
272 0x29, 0xFF, // Usage Maximum (255), 286 0x29, 0xFF, // Usage Maximum (255),
@@ -336,7 +350,7 @@ const PROGMEM uchar mouse_hid_report[] = {
336 0xa1, 0x01, // COLLECTION (Application) 350 0xa1, 0x01, // COLLECTION (Application)
337 0x85, REPORT_ID_SYSTEM, // REPORT_ID (2) 351 0x85, REPORT_ID_SYSTEM, // REPORT_ID (2)
338 0x15, 0x01, // LOGICAL_MINIMUM (0x1) 352 0x15, 0x01, // LOGICAL_MINIMUM (0x1)
339 0x25, 0xb7, 0x00 // LOGICAL_MAXIMUM (0xb7) 353 0x26, 0xb7, 0x00, // LOGICAL_MAXIMUM (0xb7)
340 0x19, 0x01, // USAGE_MINIMUM (0x1) 354 0x19, 0x01, // USAGE_MINIMUM (0x1)
341 0x29, 0xb7, // USAGE_MAXIMUM (0xb7) 355 0x29, 0xb7, // USAGE_MAXIMUM (0xb7)
342 0x75, 0x10, // REPORT_SIZE (16) 356 0x75, 0x10, // REPORT_SIZE (16)
@@ -481,11 +495,11 @@ USB_PUBLIC usbMsgLen_t usbFunctionDescriptor(struct usbRequest *rq)
481 /* interface index */ 495 /* interface index */
482 switch (rq->wIndex.word) { 496 switch (rq->wIndex.word) {
483 case 0: 497 case 0:
484 usbMsgPtr = keyboard_hid_report; 498 usbMsgPtr = (unsigned char *)keyboard_hid_report;
485 len = sizeof(keyboard_hid_report); 499 len = sizeof(keyboard_hid_report);
486 break; 500 break;
487 case 1: 501 case 1:
488 usbMsgPtr = mouse_hid_report; 502 usbMsgPtr = (unsigned char *)mouse_hid_report;
489 len = sizeof(mouse_hid_report); 503 len = sizeof(mouse_hid_report);
490 break; 504 break;
491 } 505 }
diff --git a/tmk_core/ring_buffer.h b/tmk_core/ring_buffer.h
index 7bdebbcf3..005d1be61 100644
--- a/tmk_core/ring_buffer.h
+++ b/tmk_core/ring_buffer.h
@@ -4,13 +4,13 @@
4 * Ring buffer to store scan codes from keyboard 4 * Ring buffer to store scan codes from keyboard
5 *------------------------------------------------------------------*/ 5 *------------------------------------------------------------------*/
6#define RBUF_SIZE 32 6#define RBUF_SIZE 32
7#include <util/atomic.h>
7static uint8_t rbuf[RBUF_SIZE]; 8static uint8_t rbuf[RBUF_SIZE];
8static uint8_t rbuf_head = 0; 9static uint8_t rbuf_head = 0;
9static uint8_t rbuf_tail = 0; 10static uint8_t rbuf_tail = 0;
10static inline void rbuf_enqueue(uint8_t data) 11static inline void rbuf_enqueue(uint8_t data)
11{ 12{
12 uint8_t sreg = SREG; 13 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
13 cli();
14 uint8_t next = (rbuf_head + 1) % RBUF_SIZE; 14 uint8_t next = (rbuf_head + 1) % RBUF_SIZE;
15 if (next != rbuf_tail) { 15 if (next != rbuf_tail) {
16 rbuf[rbuf_head] = data; 16 rbuf[rbuf_head] = data;
@@ -18,36 +18,34 @@ static inline void rbuf_enqueue(uint8_t data)
18 } else { 18 } else {
19 print("rbuf: full\n"); 19 print("rbuf: full\n");
20 } 20 }
21 SREG = sreg; 21 }
22} 22}
23static inline uint8_t rbuf_dequeue(void) 23static inline uint8_t rbuf_dequeue(void)
24{ 24{
25 uint8_t val = 0; 25 uint8_t val = 0;
26 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
26 27
27 uint8_t sreg = SREG;
28 cli();
29 if (rbuf_head != rbuf_tail) { 28 if (rbuf_head != rbuf_tail) {
30 val = rbuf[rbuf_tail]; 29 val = rbuf[rbuf_tail];
31 rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE; 30 rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
32 } 31 }
33 SREG = sreg; 32 }
34 33
35 return val; 34 return val;
36} 35}
37static inline bool rbuf_has_data(void) 36static inline bool rbuf_has_data(void)
38{ 37{
39 uint8_t sreg = SREG; 38 bool has_data;
40 cli(); 39 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
41 bool has_data = (rbuf_head != rbuf_tail); 40 has_data = (rbuf_head != rbuf_tail);
42 SREG = sreg; 41 }
43 return has_data; 42 return has_data;
44} 43}
45static inline void rbuf_clear(void) 44static inline void rbuf_clear(void)
46{ 45{
47 uint8_t sreg = SREG; 46 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
48 cli();
49 rbuf_head = rbuf_tail = 0; 47 rbuf_head = rbuf_tail = 0;
50 SREG = sreg; 48 }
51} 49}
52 50
53#endif /* RING_BUFFER_H */ 51#endif /* RING_BUFFER_H */