-
Notifications
You must be signed in to change notification settings - Fork 0
/
Measurement.lua
103 lines (76 loc) · 2.77 KB
/
Measurement.lua
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
local EventDispatcher = require 'EventDispatcher';
local UltrasonicSensor = require 'UltrasonicSensor';
local Stats = require 'Stats';
local Measurement = {}
Measurement.create = function ()
local export = {};
local splitDistance = 150;
local measurementInterval = 100;
local lastIsOccupied;
local distances = {};
local measurementFinishedListeners = EventDispatcher.create();
local timer = tmr.create();
function export.start()
rtctime.set(0, 0);
timer:register(measurementInterval, tmr.ALARM_SEMI, function ()
UltrasonicSensor.getDistance(function (distance)
table.insert(distances, 1, distance);
local size = table.getn(distances);
if (size > 10) then
table.remove(distances);
end
local currentDistance = Stats.median(distances);
if (currentDistance == nil) then
timer:start();
return;
end
print(string.format('Calculated distance: %d, from: %s', currentDistance, sjson.encode(distances)));
local isOccupied = currentDistance < splitDistance;
if (isOccupied ~= lastIsOccupied) then
lastIsOccupied = isOccupied;
local measurementData = {
currentDistance = currentDistance,
isOccupied = isOccupied
};
measurementFinishedListeners.dispatch(measurementData, function ()
timer:start();
end);
else
timer:start();
end
end, function ()
print('No response from ultrasonic sensor');
timer:start();
end);
end);
timer:start();
end
function export.stop()
timer:stop();
end
function export.setSplitDistance(value)
if (value == nil or value <= 0) then
print('Tried to set incorret split distance value');
return;
end
splitDistance = value;
end
function export.setMeasurementInterval(value)
if (value == nil or value <= 0) then
print('Tried to set incorret measurement interval value');
return;
end
measurementInterval = value;
end
function export.addMeasurementFinishedListener(listener)
measurementFinishedListeners.addListener(listener);
end
function export.removeMeasurementFinishedListener(listener)
measurementFinishedListeners.removeListener(listener);
end
return export;
end
Measurement.destroy = function()
measureTimer.unregister(measureTimer);
end
return Measurement;