-
Notifications
You must be signed in to change notification settings - Fork 0
/
Model.cs
120 lines (104 loc) · 3.54 KB
/
Model.cs
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
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using System.Text;
using Processing;
namespace ElevatorComfort
{
public struct DataSample
{
public double X, // raw X acceleration
Y, // raw Y acceleration
Z, // raw Z acceleration
Timestamp, // timestamp
DT, // delta time
Acc, // calculated length of acceleration vector
Speed, // calculated speed
Jerk, // calculated jerk
Vibr, // calculated vibration
Sound; // audio pressure level
}
public class Model
{
private const double GRAVITY_ACC = 9.8;
private readonly int _maxCount;
private object _lock = new object();
private List<DataSample> _samples = new List<DataSample>();
private TwoPoleButterworthFilter _filter = new TwoPoleButterworthFilter();
private AccelToSpeed _accelToSpeed = new AccelToSpeed();
private AccelToJerk _accelToJerk = new AccelToJerk();
private ZeroCrossMaximum _vibrationCounter = new ZeroCrossMaximum();
private bool _calibrated = false;
public Model(int maxCount)
{
_maxCount = maxCount;
}
public void AddValues(double x, double y, double z, double sound, double timestamp, double deltaTimestamp)
{
lock (_lock)
{
var acc = _filter.Next(z);
if (timestamp == 0)
{
_filter.Next(acc);
_filter.Next(acc);
_accelToJerk.Next(acc, deltaTimestamp);
}
acc = _filter.Next(acc);
var jerk = _accelToJerk.Next(acc, deltaTimestamp);
var speed = _calibrated ? _accelToSpeed.Next(acc, deltaTimestamp) * GRAVITY_ACC : 0;
var vibr = _vibrationCounter.Next(acc);
_samples.Add(new DataSample() {
X = x,
Y = y,
Z = z,
Timestamp = timestamp,
DT = deltaTimestamp,
Acc = acc,
Speed = speed,
Jerk = jerk / 100,
Vibr = vibr,
Sound = sound
});
while (_samples.Count > _maxCount) { _samples.RemoveAt(0); }
}
}
public DataSample[] GetPoints()
{
lock (_lock)
{
var result = new DataSample[_samples.Count];
_samples.CopyTo(result);
return result;
}
}
public void Reset()
{
lock (_lock)
{
_vibrationCounter.Reset();
_accelToSpeed.Reset();
_samples.Clear();
_calibrated = false;
}
}
public void Calibrate()
{
lock (_lock)
{
if (_samples.Count == 0) { return; }
_accelToSpeed.Calibrate(_samples.Average(a => a.Z));
_calibrated = true;
}
}
public string Serialize()
{
return JsonConvert.SerializeObject(_samples);
}
public void Deserialize(string s)
{
_samples = JsonConvert.DeserializeObject<List<DataSample>>(s);
}
}
}