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