]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - usb_mouse.c
98292bdd849b556f7aab509176f02cc4b97467ca
[max/tmk_keyboard.git] / usb_mouse.c
1 #include <avr/interrupt.h>
2 #include <util/delay.h>
3 #include "usb_mouse.h"
4 #include "print.h"
5 #include "debug.h"
6
7
8 static bool is_sent = false;
9
10 // which buttons are currently pressed
11 uint8_t mouse_buttons=0;
12
13 // protocol setting from the host.  We use exactly the same report
14 // either way, so this variable only stores the setting since we
15 // are required to be able to report which setting is in use.
16 uint8_t mouse_protocol=1;
17
18
19 // Set the mouse buttons.  To create a "click", 2 calls are needed,
20 // one to push the button down and the second to release it
21 int8_t usb_mouse_buttons(uint8_t left, uint8_t middle, uint8_t right)
22 {
23         uint8_t mask=0;
24
25         if (left) mask |= 1;
26         if (middle) mask |= 4;
27         if (right) mask |= 2;
28         mouse_buttons = mask;
29         return usb_mouse_move(0, 0, 0, 0);
30 }
31
32 // Move the mouse.  x, y and wheel are -127 to 127.  Use 0 for no movement.
33 int8_t usb_mouse_move(int8_t x, int8_t y, int8_t wheel, int8_t hwheel)
34 {
35         uint8_t intr_state, timeout;
36
37         if (!usb_configured()) return -1;
38         if (x == -128) x = -127;
39         if (y == -128) y = -127;
40         if (wheel == -128) wheel = -127;
41         if (hwheel == -128) hwheel = -127;
42         intr_state = SREG;
43         cli();
44         UENUM = MOUSE_ENDPOINT;
45         timeout = UDFNUML + 50;
46         while (1) {
47                 // are we ready to transmit?
48                 if (UEINTX & (1<<RWAL)) break;
49                 SREG = intr_state;
50                 // has the USB gone offline?
51                 if (!usb_configured()) return -1;
52                 // have we waited too long?
53                 if (UDFNUML == timeout) return -1;
54                 // get ready to try checking again
55                 intr_state = SREG;
56                 cli();
57                 UENUM = MOUSE_ENDPOINT;
58         }
59         UEDATX = mouse_buttons;
60         UEDATX = x;
61         UEDATX = y;
62         if (mouse_protocol) {
63             UEDATX = wheel;
64             UEDATX = hwheel;
65         }
66         
67         UEINTX = 0x3A;
68         SREG = intr_state;
69         is_sent = true;
70         return 0;
71 }
72
73 void usb_mouse_clear(void) {
74     is_sent = false;
75 }
76
77 bool usb_mouse_is_sent(void) {
78     return is_sent;
79 }
80
81 void usb_mouse_print(int8_t mouse_x, int8_t mouse_y, int8_t wheel_v, int8_t wheel_h) {
82     if (!debug_mouse) return;
83     print("mouse btn|x y v h: ");
84     phex(mouse_buttons); print("|");
85     phex(mouse_x); print(" ");
86     phex(mouse_y); print(" ");
87     phex(wheel_v); print(" ");
88     phex(wheel_h); print("\n");
89 }