1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others.
   Copyright 2015-2016 Teeming Society. Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except in compliance with the License.
   You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and limitations under the License.*/

define.class('$server/service', function() {

    this.attributes = {
        // Current list of beacons visible with the repeater
        // Clients will see the all the visible beacons regardless of when they joined.
        beacons: Config({type: Object, value: {}, flow:'out'}),

        // Most recent list of changes to the beacon attribute sent from the server
        // Clients will only see the latest changes added since they join.
        changes: Config({type:Array, value:[], flow:'out'}),

        // Keep track of usage by device. The key is the device uuid and the
        // value is a hash of beacon_uuid to the beacon data. Old data is removed
        // from the structure.
        device_data: Config({type:Object, value:{}}),

        // Keep track of usage by beacon id. The key is the beacon id and the value
        // is a hash of device_uuid to the beacon data. Old data is removed
        // from the structure.
        beacon_data: Config({type:Object, value:{}})
    };

    this.init = function() {
        setInterval(this.expire_beacon_data, 10000);
    };

    // Keep track of location by device and beacon.
    // The beacon_id is the concatenation of the uuid and major and minor number.
    this.postBeacons = function(json) {
         // Use the server timestamp, not the timestamp received from device
        var ts = Date.now();

        var device = json['device'];
        var device_uuid = device['platform'] + ':' + device['uuid'];

        var beacons = json['beacons'];
        for (var beacon_id in beacons) {
            var beacon = beacons[beacon_id];
            var beacon_uuid = beacon['proximityUUID'] + ':' + beacon['major'] + ':' + beacon['minor'];

            // Create an array for each beacon and device, as needed
            if (!(beacon_uuid in this.beacon_data)) {
                this.beacon_data[beacon_uuid] = {};
            }

            if (!(device_uuid in this.device_data)) {
                this.device_data[device_uuid] = {};
            }

            // Store the same record for both beacon and device structures.
            this.beacon_data[beacon_uuid][device_uuid] = {ts: ts, device_uuid: device_uuid, beacon_uuid: beacon_uuid, beacon: beacon};
            this.device_data[device_uuid][beacon_uuid] = {ts: ts, device_uuid: device_uuid, beacon_uuid: beacon_uuid, beacon: beacon};
            //xxx set some last ts value changed
        }

        this.expire_beacon_data();

        this.findChanges();

        return this.beacons;
    };

    this.expire_beacon_data = function(age) {
        age = age || 20000;

        var ts = Date.now();

        for (var beacon_uuid in this.beacon_data) {
            for (var device_uuid in this.beacon_data[beacon_uuid]) {
                var delta = ts - this.beacon_data[beacon_uuid][device_uuid]['ts'];
                if (delta > age) {
                    delete this.beacon_data[beacon_uuid][device_uuid];
                    if (Object.keys(this.beacon_data[beacon_uuid]).length == 0) {
                        delete this.beacon_data[beacon_uuid]
                    }
                }
            }
        }

        for (var device_uuid in this.device_data) {
            for (var beacon_uuid in this.device_data[device_uuid]) {
                var delta = ts - this.device_data[device_uuid][beacon_uuid]['ts'];
                if (delta > age) {
                    delete this.device_data[device_uuid][beacon_uuid];
                    if (Object.keys(this.device_data[device_uuid]).length == 0) {
                        delete this.device_data[device_uuid]
                    }
                }
            }
        }
    };


    this.checkMovement = function(distances) {
        if (distances.length < 4) {
            return 0.0;
        }

        var median1 = distances.slice(0,3).sort()[1];
        var median2 = distances.slice(1,4).sort()[1];

        return median2 - median1
    };

    // Find intersection of current and previous beacons.
    this.intersection = function intersection(a, b) {
        var ai=0, bi=0;
        var result = [];

        while (ai < a.length && bi < b.length) {
            if (a[ai] < b[bi]) {
                ai++;
            } else if (a[ai] > b[bi] ) {
                bi++;
            } else {
                result.push(a[ai]);
                ai++;
                bi++;
            }
        }

        return result;
    };

    this.findChanges = function() {

        var changelist = [];

        // Unroll the data into a single hash of beacon|device => data
        // To smooth the data (it can be pretty noisy), a distances array of the
        // previous 3 values is maintained, and the median value is selected.
        var unrolled = {};
        for (var beacon_id in this.beacon_data) {
            if (this.beacon_data.hasOwnProperty(beacon_id)) {
                var devices = this.beacon_data[beacon_id];
                for (var device_id in devices) {
                    if (devices.hasOwnProperty(device_id)) {
                        var id = beacon_id + '||' + device_id;
                        unrolled[id] = devices[device_id];
                    }
                }
            }
        }

        var both = this.intersection(Object.keys(unrolled), Object.keys(this.beacons));

        for (var key in unrolled) {
            if (unrolled.hasOwnProperty(key)) {
                var data = unrolled[key];
                var distance_current = data.beacon.distance;
                if (key in both) {
                    // Get the median distance stored (uses a clone of the object)
                    var distances = this.beacons[key].distances.slice(0);

                    distances.push(distance_current);
                    if (distances.length > 4) {
                        distances.shift();
                    }
                    var movement = 0.0;
                    if (distances.length >= 4) {
                        movement = this.checkMovement(distances)
                    }

                    // See if the distance has changed
                    if (movement <= -0.9) {
                        // Distance is smaller than before
                        unrolled[key].distances = [distance_current];
                        data.distances = distances;
                        changelist.push({change: '+movement', movement: movement, data: data})
                    } else if (movement >= 0.9) {
                        // Distance is greater than before
                        unrolled[key].distances = [distance_current];
                        data.distances = distances;
                        changelist.push({change: '-movement', movement: movement, data: data})
                    } else {
                        // Add the distance to the array
                        unrolled[key].distances = distances
                    }
                } else {
                    unrolled[key].distances = [distance_current];
                    changelist.push({change: 'enter', data: data})
                }
            }
        }

        for (var k in this.beacons) {
            if (this.beacons.hasOwnProperty(k)) {
                if (!(k in both)) {
                    changelist.push({change: 'leave', data: data})
                }
            }
        }

        this.changes = changelist;
        this.beacons = unrolled;
    };

});