]> git.friedersdorff.com Git - max/tmk_keyboard.git/blobdiff - tmk_core/protocol/lufa/lufa.c
core: lufa: Add delay for console startup
[max/tmk_keyboard.git] / tmk_core / protocol / lufa / lufa.c
index cdfc7bc6ad990bfd5a0031cb71dec93bbf99067c..60849aea4c935da108839c6e583d596540624719 100644 (file)
@@ -1,4 +1,4 @@
-/* 
+/*
  * Copyright 2012 Jun Wako <wakojun@gmail.com>
  * This file is based on:
  *     LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
 #include "sleep_led.h"
 #endif
 #include "suspend.h"
+#include "hook.h"
+
+#ifdef LUFA_DEBUG_SUART
+#include "avr/suart.h"
+#endif
 
+#include "matrix.h"
 #include "descriptor.h"
 #include "lufa.h"
 
+
+//#define LUFA_DEBUG
+
+
 uint8_t keyboard_idle = 0;
+/* 0: Boot Protocol, 1: Report Protocol(default) */
 uint8_t keyboard_protocol = 1;
 static uint8_t keyboard_led_stats = 0;
 
@@ -98,10 +109,10 @@ static void Console_Task(void)
         {
             /* Create a temporary buffer to hold the read in report from the host */
             uint8_t ConsoleData[CONSOLE_EPSIZE];
+
             /* Read Console Report Data */
             Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
+
             /* Process Console Report Data */
             //ProcessConsoleHIDReport(ConsoleData);
         }
@@ -162,7 +173,7 @@ void EVENT_USB_Device_Disconnect(void)
     print("[D]");
     /* For battery powered device */
     USB_IsInitialized = false;
-/* TODO: This doesn't work. After several plug in/outs can not be enumerated. 
+/* TODO: This doesn't work. After several plug in/outs can not be enumerated.
     if (USB_IsInitialized) {
         USB_Disable();  // Disable all interrupts
        USB_Controller_Enable();
@@ -173,40 +184,57 @@ void EVENT_USB_Device_Disconnect(void)
 
 void EVENT_USB_Device_Reset(void)
 {
+#ifdef LUFA_DEBUG
     print("[R]");
+#endif
 }
 
 void EVENT_USB_Device_Suspend()
 {
+#ifdef LUFA_DEBUG
     print("[S]");
-    matrix_power_down();
-#ifdef SLEEP_LED_ENABLE
-    sleep_led_enable();
 #endif
+    hook_usb_suspend_entry();
 }
 
 void EVENT_USB_Device_WakeUp()
 {
+#ifdef LUFA_DEBUG
     print("[W]");
-    suspend_wakeup_init();
-
-#ifdef SLEEP_LED_ENABLE
-    sleep_led_disable();
-    // NOTE: converters may not accept this
-    led_set(host_keyboard_leds());
 #endif
+    hook_usb_wakeup();
 }
 
+#ifdef CONSOLE_ENABLE
+static bool console_flush = false;
+#define CONSOLE_FLUSH_SET(b)   do { \
+    uint8_t sreg = SREG; cli(); console_flush = b; SREG = sreg; \
+} while (0)
+
+// called every 1ms
 void EVENT_USB_Device_StartOfFrame(void)
 {
+    static uint8_t count;
+    if (++count % 50) return;
+    count = 0;
+
+    if (!console_flush) return;
     Console_Task();
+    console_flush = false;
 }
+#endif
 
 /** Event handler for the USB_ConfigurationChanged event.
  * This is fired when the host sets the current configuration of the USB device after enumeration.
+ *
+ * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
+ * it is safe to use singl bank for all endpoints.
  */
 void EVENT_USB_Device_ConfigurationChanged(void)
 {
+#ifdef LUFA_DEBUG
+    print("[c]");
+#endif
     bool ConfigSuccess = true;
 
     /* Setup Keyboard HID Report Endpoints */
@@ -228,7 +256,7 @@ void EVENT_USB_Device_ConfigurationChanged(void)
 #ifdef CONSOLE_ENABLE
     /* Setup Console HID Report Endpoints */
     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
-                                     CONSOLE_EPSIZE, ENDPOINT_BANK_DOUBLE);
+                                     CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
 #if 0
     ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
                                      CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
@@ -283,6 +311,9 @@ void EVENT_USB_Device_ControlRequest(void)
                 /* Write the report data to the control endpoint */
                 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
                 Endpoint_ClearOUT();
+#ifdef LUFA_DEBUG
+                xprintf("[r%d]", USB_ControlRequest.wIndex);
+#endif
             }
 
             break;
@@ -306,6 +337,9 @@ void EVENT_USB_Device_ControlRequest(void)
 
                     Endpoint_ClearOUT();
                     Endpoint_ClearStatusStage();
+#ifdef LUFA_DEBUG
+                    xprintf("[L%d]", USB_ControlRequest.wIndex);
+#endif
                     break;
                 }
 
@@ -322,6 +356,9 @@ void EVENT_USB_Device_ControlRequest(void)
                     Endpoint_Write_8(keyboard_protocol);
                     Endpoint_ClearIN();
                     Endpoint_ClearStatusStage();
+#ifdef LUFA_DEBUG
+                    print("[p]");
+#endif
                 }
             }
 
@@ -333,11 +370,11 @@ void EVENT_USB_Device_ControlRequest(void)
                     Endpoint_ClearSETUP();
                     Endpoint_ClearStatusStage();
 
-                    keyboard_protocol = ((USB_ControlRequest.wValue & 0xFF) != 0x00);
-#ifdef NKRO_ENABLE
-                    keyboard_nkro = !!keyboard_protocol;
-#endif
+                    keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
                     clear_keyboard();
+#ifdef LUFA_DEBUG
+                    print("[P]");
+#endif
                 }
             }
 
@@ -349,6 +386,9 @@ void EVENT_USB_Device_ControlRequest(void)
                 Endpoint_ClearStatusStage();
 
                 keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
+#ifdef LUFA_DEBUG
+                xprintf("[I%d]%d", USB_ControlRequest.wIndex, (USB_ControlRequest.wValue & 0xFF00) >> 8);
+#endif
             }
 
             break;
@@ -360,6 +400,9 @@ void EVENT_USB_Device_ControlRequest(void)
                 Endpoint_Write_8(keyboard_idle);
                 Endpoint_ClearIN();
                 Endpoint_ClearStatusStage();
+#ifdef LUFA_DEBUG
+                print("[i]");
+#endif
             }
 
             break;
@@ -367,7 +410,7 @@ void EVENT_USB_Device_ControlRequest(void)
 }
 
 /*******************************************************************************
- * Host driver 
+ * Host driver
  ******************************************************************************/
 static uint8_t keyboard_leds(void)
 {
@@ -383,12 +426,12 @@ static void send_keyboard(report_keyboard_t *report)
 
     /* Select the Keyboard Report Endpoint */
 #ifdef NKRO_ENABLE
-    if (keyboard_nkro) {
+    if (keyboard_protocol && keyboard_nkro) {
         /* Report protocol - NKRO */
         Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
 
         /* Check if write ready for a polling interval around 1ms */
-        while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
+        while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(8);
         if (!Endpoint_IsReadWriteAllowed()) return;
 
         /* Write Keyboard Report Data */
@@ -439,6 +482,7 @@ static void send_mouse(report_mouse_t *report)
 
 static void send_system(uint16_t data)
 {
+#ifdef EXTRAKEY_ENABLE
     uint8_t timeout = 255;
 
     if (USB_DeviceState != DEVICE_STATE_Configured)
@@ -456,10 +500,12 @@ static void send_system(uint16_t data)
 
     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
     Endpoint_ClearIN();
+#endif
 }
 
 static void send_consumer(uint16_t data)
 {
+#ifdef EXTRAKEY_ENABLE
     uint8_t timeout = 255;
 
     if (USB_DeviceState != DEVICE_STATE_Configured)
@@ -477,6 +523,7 @@ static void send_consumer(uint16_t data)
 
     Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
     Endpoint_ClearIN();
+#endif
 }
 
 
@@ -487,10 +534,17 @@ static void send_consumer(uint16_t data)
 #define SEND_TIMEOUT 5
 int8_t sendchar(uint8_t c)
 {
+#ifdef LUFA_DEBUG_SUART
+    xmit(c);
+#endif
     // Not wait once timeouted.
     // Because sendchar() is called so many times, waiting each call causes big lag.
     static bool timeouted = false;
 
+    // prevents Console_Task() from running during sendchar() runs.
+    // or char will be lost. These two function is mutually exclusive.
+    CONSOLE_FLUSH_SET(false);
+
     if (USB_DeviceState != DEVICE_STATE_Configured)
         return -1;
 
@@ -524,8 +578,12 @@ int8_t sendchar(uint8_t c)
     Endpoint_Write_8(c);
 
     // send when bank is full
-    if (!Endpoint_IsReadWriteAllowed())
+    if (!Endpoint_IsReadWriteAllowed()) {
+        while (!(Endpoint_IsINReady()));
         Endpoint_ClearIN();
+    } else {
+        CONSOLE_FLUSH_SET(true);
+    }
 
     Endpoint_SelectEndpoint(ep);
     return 0;
@@ -536,6 +594,9 @@ ERROR_EXIT:
 #else
 int8_t sendchar(uint8_t c)
 {
+#ifdef LUFA_DEBUG_SUART
+    xmit(c);
+#endif
     return 0;
 }
 #endif
@@ -544,7 +605,7 @@ int8_t sendchar(uint8_t c)
 /*******************************************************************************
  * main
  ******************************************************************************/
-static void SetupHardware(void)
+static void setup_mcu(void)
 {
     /* Disable watchdog if enabled by bootloader/fuses */
     MCUSR &= ~(1 << WDRF);
@@ -552,7 +613,10 @@ static void SetupHardware(void)
 
     /* Disable clock division */
     clock_prescale_set(clock_div_1);
+}
 
+static void setup_usb(void)
+{
     // Leonardo needs. Without this USB device is not recognized.
     USB_Disable();
 
@@ -560,13 +624,23 @@ static void SetupHardware(void)
 
     // for Console_Task
     USB_Device_EnableSOFEvents();
-    print_set_sendchar(sendchar);
 }
 
 int main(void)  __attribute__ ((weak));
 int main(void)
 {
-    SetupHardware();
+    setup_mcu();
+
+#ifdef LUFA_DEBUG_SUART
+    SUART_OUT_DDR |= (1<<SUART_OUT_BIT);
+    SUART_OUT_PORT |= (1<<SUART_OUT_BIT);
+#endif
+    print_set_sendchar(sendchar);
+    print("\r\ninit\n");
+
+    hook_early_init();
+    keyboard_setup();
+    setup_usb();
     sei();
 
     /* wait for USB startup & debug output */
@@ -577,6 +651,17 @@ int main(void)
         USB_USBTask();
 #endif
     }
+
+    /* wait for Console startup */
+    // TODO: long delay often works anyhoo but proper startup would be better
+    uint16_t delay = 2000;
+    while (delay--) {
+#ifndef INTERRUPT_CONTROL_ENDPOINT
+        USB_USBTask();
+#endif
+        _delay_ms(1);
+    }
+
     print("USB configured.\n");
 
     /* init modules */
@@ -587,13 +672,13 @@ int main(void)
 #endif
 
     print("Keyboard start.\n");
+    hook_late_init();
     while (1) {
         while (USB_DeviceState == DEVICE_STATE_Suspended) {
+#ifdef LUFA_DEBUG
             print("[s]");
-            suspend_power_down();
-            if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
-                    USB_Device_SendRemoteWakeup();
-            }
+#endif
+            hook_usb_suspend_loop();
         }
 
         keyboard_task();
@@ -603,3 +688,54 @@ int main(void)
 #endif
     }
 }
+
+
+/* hooks */
+__attribute__((weak))
+void hook_early_init(void) {}
+
+__attribute__((weak))
+void hook_late_init(void) {}
+
+static uint8_t _led_stats = 0;
+ __attribute__((weak))
+void hook_usb_suspend_entry(void)
+{
+    // Turn LED off to save power
+    // Set 0 with putting aside status before suspend and restore
+    // it after wakeup, then LED is updated at keyboard_task() in main loop
+    _led_stats = keyboard_led_stats;
+    keyboard_led_stats = 0;
+    led_set(keyboard_led_stats);
+
+    matrix_clear();
+    clear_keyboard();
+#ifdef SLEEP_LED_ENABLE
+    sleep_led_enable();
+#endif
+}
+
+__attribute__((weak))
+void hook_usb_suspend_loop(void)
+{
+    suspend_power_down();
+    if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
+        USB_Device_SendRemoteWakeup();
+    }
+}
+
+__attribute__((weak))
+void hook_usb_wakeup(void)
+{
+    suspend_wakeup_init();
+#ifdef SLEEP_LED_ENABLE
+    sleep_led_disable();
+#endif
+
+    // Restore LED status
+    // BIOS/grub won't recognize/enumerate if led_set() takes long(around 40ms?)
+    // Converters fall into the case and miss wakeup event(timeout to reply?) in the end.
+    //led_set(host_keyboard_leds());
+    // Instead, restore stats and update at keyboard_task() in main loop
+    keyboard_led_stats = _led_stats;
+}