Run in video mode unless arguments are supplied
[kaka/cakelight.git] / src / kaka / cakelight / Main.java
1 package kaka.cakelight;
2
3 import org.opencv.core.Core;
4
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.util.HashMap;
8
9 public class Main {
10     public static void main(String[] args) {
11         System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
12
13         Configuration config = Configuration.from("config.properties");
14         log("Running with config:\n" + config);
15
16         CakeLight cakelight = new CakeLight(config, new LedController(config));
17         if (args.length > 0) {
18             cakelight.setMode(new AmbientMode(args));
19         } else {
20             cakelight.setMode(new VideoMode());
21         }
22         cakelight.startLoop();
23         Runtime.getRuntime().addShutdownHook(new Thread(Main::printTimeStats));
24     }
25
26     public static void saveFile(byte[] data, String filepath) {
27         try {
28             FileOutputStream fos = new FileOutputStream(filepath);
29             fos.write(data);
30             fos.close();
31         } catch (IOException e) {
32             e.printStackTrace();
33         }
34     }
35
36     public static void log(String msg, Object... args) {
37         System.out.println(String.format(msg, args));
38     }
39
40     private static HashMap<String, Double> timeDurations = new HashMap<>();
41     private static HashMap<String, Integer> timeCounts = new HashMap<>();
42     public static double timeIt(String tag, Runnable lambda) {
43         long start = System.nanoTime();
44         lambda.run();
45         long end = System.nanoTime();
46         double duration = (end - start) * 0.000001;
47 //      log("duration (ms): " + tag + " = " + duration);
48
49         if (!timeDurations.containsKey(tag)) {
50             timeDurations.put(tag, 0.0);
51             timeCounts.put(tag, 0);
52         }
53         timeDurations.put(tag, timeDurations.get(tag) + duration);
54         timeCounts.put(tag, timeCounts.get(tag) + 1);
55         return duration;
56     }
57
58     private static void printTimeStats() {
59         log("Average times in ms:");
60         timeDurations.forEach((tag, duration) -> {
61             log("%s: %s", tag, duration / timeCounts.get(tag));
62         });
63     }
64 }
65
66 /*
67 FrameGrabber läser frames asynkront
68 skickar frame till FrameConverter
69 sparas i huvudklassen
70 läses av FrameProcessor/CakeLight
71  */