Diff of /python/mouse_control.py [000000] .. [a32498]

Switch to unified view

a b/python/mouse_control.py
1
#!/usr/bin/python
2
# Example of using the gyro values to control mouse movement.
3
# May or may not work?
4
import ctypes
5
import platform
6
import time
7
from ctypes import cdll
8
9
if platform.system() == "Windows":
10
    pass
11
12
from emokit.emotiv import Emotiv
13
14
15
class Xlib:
16
    def __init__(self):
17
        self.xlib = cdll.LoadLibrary('libX11.so')
18
19
        display = self.xlib.XOpenDisplay(None)
20
        dflt_screen_num = self.xlib.XDefaultScreen(display)
21
        default_screen = self.xlib.XScreenOfDisplay(display, dflt_screen_num)
22
23
        self.width = self.xlib.XWidthOfScreen(default_screen)
24
        self.height = self.xlib.XHeightOfScreen(default_screen)
25
        self.xlib.XCloseDisplay(display)
26
27
    def move_mouse(self, x, y):
28
        display = self.xlib.XOpenDisplay(None)
29
        root = self.xlib.XDefaultRootWindow(display)
30
        self.xlib.XWarpPointer(display, None, root, 0, 0, 0, 0, x, y)
31
        self.xlib.XCloseDisplay(display)
32
33
34
class WinMouse:
35
    def __init__(self):
36
        user32 = ctypes.windll.user32
37
        self.width = user32.GetSystemMetrics(0)
38
        self.height = user32.GetSystemMetrics(1)
39
40
    def click(self, x, y):
41
        ctypes.windll.user32.SetCursorPos(x, y)
42
        ctypes.windll.user32.mouse_event(2, 0, 0, 0, 0) # left down
43
        ctypes.windll.user32.mouse_event(4, 0, 0, 0, 0) # left up
44
45
    def move_mouse(self, x, y):
46
        ctypes.windll.user32.SetCursorPos(x, y)
47
48
49
def main():
50
    if not platform.system() == 'Windows':
51
        screen = Xlib()
52
    else:
53
        screen = WinMouse()
54
    width = screen.width
55
    height = screen.height
56
57
    cursor_x, cursor_y = width // 2, height // 2
58
    while True:
59
        updated = False
60
        packet = headset.dequeue()
61
        if abs(packet.sensors['X']['value']) > 1:
62
            cursor_x -= packet.sensors['X']['value']
63
            updated = True
64
        if abs(packet.sensors['Y']['value']) > 1:
65
            cursor_y += packet.sensors['Y']['value']
66
            updated = True
67
        cursor_x = max(0, min(cursor_x, width))
68
        cursor_y = max(0, min(cursor_y, height))
69
        if updated:
70
            screen.move_mouse(cursor_x, cursor_y)
71
        time.sleep(0.001)
72
73
if __name__ == "__main__":
74
    with Emotiv() as headset:
75
        main()