type export advancement
[svn42.git] / go / r3-eventbroker_zmq / metamovement.go
1 // (c) Bernhard Tittelbach, 2013
2
3 package main
4
5 import (
6     "time"
7     //~ "./brain"
8     pubsub "github.com/tuxychandru/pubsub"
9     "container/ring"
10     )
11
12 type SomethingReallyIsMoving struct {
13     Movement bool
14     Ts int64
15 }
16
17
18 func MetaEventRoutine_Movement(ps *pubsub.PubSub, granularity, gran_duration int , threshold uint32) {
19     var last_movement int64
20     movement_window := ring.New(granularity+1)
21     events_chan := ps.Sub("movement")
22     myticker := time.NewTicker(time.Duration(gran_duration) * time.Second)
23
24     for { select {
25         case event := <- events_chan:
26             switch event.(type) {
27                 case MovementSensorUpdate:
28                     movement_window.Value =  (uint32) (movement_window.Value.(uint32)  + 1)
29             }
30         case <- myticker.C:
31             movement_window.Prev().Value = (uint32) (0)
32             movement_window = movement_window.Next()
33             var movsum uint32 = 0
34             movement_window.Do(func(v interface{}){if v != nil {movsum += v.(uint32)}})
35             ts :=  time.Now().Unix()
36             if movsum > threshold {
37                 ps.Pub( SomethingReallyIsMoving{true,ts}, "movement")
38                 last_movement = ts
39             }
40
41             if last_movement > 0 && ts - last_movement < 3600*6 && ts - last_movement > 3600*3 {
42                 last_movement = 0
43                 ps.Pub( SomethingReallyIsMoving{false, ts}, "movement")
44             }
45     } }
46 }