Add command control via named pipe
[kaka/cakelight.git] / src / kaka / cakelight / CakeLight.java
1 package kaka.cakelight;
2
3 import kaka.cakelight.mode.Mode;
4 import org.jnativehook.GlobalScreen;
5 import org.jnativehook.NativeHookException;
6 import org.jnativehook.keyboard.NativeKeyAdapter;
7 import org.jnativehook.keyboard.NativeKeyEvent;
8 import org.jnativehook.mouse.NativeMouseEvent;
9 import org.jnativehook.mouse.NativeMouseMotionAdapter;
10
11 public class CakeLight {
12     private Configuration config;
13     private Mode mode;
14     private LedController ledController;
15
16     public CakeLight(Configuration config, LedController ledController) {
17         this.config = config;
18         this.ledController = ledController;
19         Color.calculateGammaCorrection(config.gamma);
20     }
21
22     public void setMode(Mode mode) {
23         cleanup();
24         this.mode = mode;
25         mode.setFrameListener(ledController::onFrame);
26         mode.enter(config);
27     }
28
29     public void cleanup() {
30         if (this.mode != null) {
31             this.mode.setFrameListener(ledFrame -> {}); // To avoid any frame being sent to the controller while the thread is exiting
32             this.mode.exit();
33         }
34     }
35
36     public void startLoop() {
37         Console console = Console.start(this, config);
38         PipeController.start(console);
39         initNativeHook();
40         // TODO
41 //        FrameGrabber grabber = FrameGrabber.from(config);
42 //        grabber.prepare();
43 //        VideoFrame frame = grabber.grabFrame();
44 //        double time = 0;
45 //        for (int i = 0; i < 100; i++) {
46 //            time += timeIt("frame", () -> grabber.grabFrame());
47 //        }
48 //        System.out.println("time = " + time);
49 //        grabber.close();
50 //      byte[] data = frame.getData();
51 //      saveFile(data, "/home/kaka/test.img");
52     }
53
54     private void initNativeHook() {
55         try {
56             GlobalScreen.registerNativeHook();
57             GlobalScreen.addNativeKeyListener(new NativeKeyAdapter() {
58                 @Override
59                 public void nativeKeyPressed(NativeKeyEvent e) {
60                     System.out.println("key code = " + e.getKeyCode() + ", key text = '" + NativeKeyEvent.getKeyText(e.getKeyCode()) + "'");
61                 }
62             });
63             GlobalScreen.addNativeMouseMotionListener(new NativeMouseMotionAdapter() {
64                 @Override
65                 public void nativeMouseMoved(NativeMouseEvent e) {
66                     System.out.println("mouse point = " + e.getPoint());
67                 }
68             });
69         } catch (NativeHookException e) {
70             e.printStackTrace();
71         }
72     }
73
74     public void turnOff() {
75         cleanup();
76         ledController.onFrame(LedFrame.from(config).fillColor(0, 0, 0));
77     }
78 }