52d3b61c45b84ee60987c355a1cfe5b6bb3bc126
[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         cakelight.setMode(new AmbientMode());
18         cakelight.startLoop();
19         Runtime.getRuntime().addShutdownHook(new Thread(Main::printTimeStats));
20     }
21
22     public static void saveFile(byte[] data, String filepath) {
23         try {
24             FileOutputStream fos = new FileOutputStream(filepath);
25             fos.write(data);
26             fos.close();
27         } catch (IOException e) {
28             e.printStackTrace();
29         }
30     }
31
32     public static void log(String msg, Object... args) {
33         System.out.println(String.format(msg, args));
34     }
35
36     private static HashMap<String, Double> timeDurations = new HashMap<>();
37     private static HashMap<String, Integer> timeCounts = new HashMap<>();
38     public static double timeIt(String tag, Runnable lambda) {
39         long start = System.nanoTime();
40         lambda.run();
41         long end = System.nanoTime();
42         double duration = (end - start) * 0.000001;
43 //      log("duration (ms): " + tag + " = " + duration);
44
45         if (!timeDurations.containsKey(tag)) {
46             timeDurations.put(tag, 0.0);
47             timeCounts.put(tag, 0);
48         }
49         timeDurations.put(tag, timeDurations.get(tag) + duration);
50         timeCounts.put(tag, timeCounts.get(tag) + 1);
51         return duration;
52     }
53
54     private static void printTimeStats() {
55         log("Average times in ms:");
56         timeDurations.forEach((tag, duration) -> {
57             log("%s: %s", tag, duration / timeCounts.get(tag));
58         });
59     }
60 }
61
62 /*
63 FrameGrabber läser frames asynkront
64 skickar frame till FrameConverter
65 sparas i huvudklassen
66 läses av FrameProcessor/CakeLight
67  */