Add command control via named pipe
[kaka/cakelight.git] / src / kaka / cakelight / PipeController.java
diff --git a/src/kaka/cakelight/PipeController.java b/src/kaka/cakelight/PipeController.java
new file mode 100644 (file)
index 0000000..10ed6be
--- /dev/null
@@ -0,0 +1,42 @@
+package kaka.cakelight;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+
+public class PipeController extends Thread {
+    private static final String PIPE = "cakectrl";
+    private Console console;
+
+    public static void start(Console console) {
+       new PipeController(console).start();
+    }
+
+    private PipeController(Console console) {
+        this.console = console;
+    }
+
+    @Override
+    public void run() {
+        while (true) {
+            createPipe();
+            try (BufferedReader reader = new BufferedReader(new FileReader(new File(PIPE)))) {
+                String input;
+                while ((input = reader.readLine()) != null) {
+                    console.handleInput(input);
+                }
+            } catch (IOException e) {
+                System.out.println("Error reading from pipe '" + PIPE + "'");
+            }
+        }
+    }
+
+    private void createPipe() {
+        try {
+            Runtime.getRuntime().exec("mkfifo " + PIPE);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+}