split_util.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include "split_util.h"
  2. #include "matrix.h"
  3. #include "keyboard.h"
  4. #include "config.h"
  5. #include "timer.h"
  6. #include "transport.h"
  7. #include "quantum.h"
  8. #ifdef EE_HANDS
  9. # include "eeconfig.h"
  10. #endif
  11. #if defined(RGBLIGHT_ENABLE) && defined(RGBLED_SPLIT)
  12. # include "rgblight.h"
  13. #endif
  14. #ifndef SPLIT_USB_TIMEOUT
  15. # define SPLIT_USB_TIMEOUT 2500
  16. #endif
  17. volatile bool isLeftHand = true;
  18. bool waitForUsb(void) {
  19. for (uint8_t i = 0; i < (SPLIT_USB_TIMEOUT / 100); i++) {
  20. // This will return true of a USB connection has been established
  21. #if defined(__AVR__)
  22. if (UDADDR & _BV(ADDEN)) {
  23. #else
  24. if (usbGetDriverStateI(&USBD1) == USB_ACTIVE) {
  25. #endif
  26. return true;
  27. }
  28. wait_ms(100);
  29. }
  30. return false;
  31. }
  32. __attribute__((weak)) bool is_keyboard_left(void) {
  33. #if defined(SPLIT_HAND_PIN)
  34. // Test pin SPLIT_HAND_PIN for High/Low, if low it's right hand
  35. setPinInput(SPLIT_HAND_PIN);
  36. return readPin(SPLIT_HAND_PIN);
  37. #elif defined(EE_HANDS)
  38. return eeconfig_read_handedness();
  39. #elif defined(MASTER_RIGHT)
  40. return !is_keyboard_master();
  41. #endif
  42. return is_keyboard_master();
  43. }
  44. __attribute__((weak)) bool is_keyboard_master(void) {
  45. static enum { UNKNOWN, MASTER, SLAVE } usbstate = UNKNOWN;
  46. // only check once, as this is called often
  47. if (usbstate == UNKNOWN) {
  48. #if defined(SPLIT_USB_DETECT) || defined(PROTOCOL_CHIBIOS)
  49. usbstate = waitForUsb() ? MASTER : SLAVE;
  50. #elif defined(__AVR__)
  51. USBCON |= (1 << OTGPADE); // enables VBUS pad
  52. wait_us(5);
  53. usbstate = (USBSTA & (1 << VBUS)) ? MASTER : SLAVE; // checks state of VBUS
  54. #else
  55. usbstate = MASTER;
  56. #endif
  57. }
  58. return (usbstate == MASTER);
  59. }
  60. static void keyboard_master_setup(void) {
  61. #if defined(USE_I2C) || defined(EH)
  62. # ifdef SSD1306OLED
  63. matrix_master_OLED_init();
  64. # endif
  65. #endif
  66. transport_master_init();
  67. }
  68. static void keyboard_slave_setup(void) { transport_slave_init(); }
  69. // this code runs before the keyboard is fully initialized
  70. void keyboard_split_setup(void) {
  71. isLeftHand = is_keyboard_left();
  72. #if defined(RGBLIGHT_ENABLE) && defined(RGBLED_SPLIT)
  73. uint8_t num_rgb_leds_split[2] = RGBLED_SPLIT;
  74. if (isLeftHand) {
  75. rgblight_set_clipping_range(0, num_rgb_leds_split[0]);
  76. } else {
  77. rgblight_set_clipping_range(num_rgb_leds_split[0], num_rgb_leds_split[1]);
  78. }
  79. #endif
  80. if (is_keyboard_master()) {
  81. keyboard_master_setup();
  82. } else {
  83. keyboard_slave_setup();
  84. }
  85. }