Made the ambient mode nicer
[kaka/cakelight.git] / src / kaka / cakelight / AmbientMode.java
1 package kaka.cakelight;
2
3 public class AmbientMode extends Mode { // TODO split into DynamicAmbient and StaticAmbient?
4     private Thread thread; // TODO move to a dynamic sub class
5     private Configuration config;
6
7     @Override
8     public void enter(Configuration config) {
9         this.config = config;
10         startThread();
11     }
12
13     @Override
14     public void exit() {
15         stopThread();
16     }
17
18     public void startThread() {
19         thread = new Thread() {
20             public void run() {
21                 try {
22                     long start = System.currentTimeMillis();
23                     int index = 0;
24                     while (!isInterrupted()) {
25                         LedFrame frame = LedFrame.from(config);
26                         updateFrame(frame, System.currentTimeMillis() - start, index);
27                         updateWithFrame(frame);
28                         index = (index + 1) % config.leds.getCount();
29                         Thread.sleep(0);
30                     }
31                 } catch (InterruptedException e) {
32                 }
33             }
34         };
35         thread.start();
36     }
37
38     public void stopThread() {
39         thread.interrupt();
40     }
41
42     /**
43      * @param frame
44      * @param time  Time in milliseconds since start
45      * @param count Goes from 0 to number of LEDs - 1
46      */
47     private void updateFrame(LedFrame frame, long time, int count) {
48         for (int i = 0; i < config.leds.getCount(); i++) {
49             double r = Math.sin(2 * i * Math.PI / config.leds.getCount() + time * 0.001) * 0.5 + 0.5;
50             double g = Math.cos(2 * i * Math.PI / config.leds.getCount() + time * 0.002) * 0.5 + 0.5;
51             frame.setLedColor(i, Color.rgb(r, g, 0));
52         }
53     }
54 }