-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathsensor.js
More file actions
395 lines (337 loc) · 9.72 KB
/
sensor.js
File metadata and controls
395 lines (337 loc) · 9.72 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
const Board = require("./board");
const Fn = require("./fn");
const Collection = require("./mixins/collection");
const Withinable = require("./mixins/withinable");
// Sensor instance private data
const priv = new Map();
// To reduce noise in sensor readings, sort collected samples
// from high to low and select the value in the center.
function median(input) {
// faster than default comparitor (even for small n)
const sorted = input.sort((a, b) => a - b);
const len = sorted.length;
const half = Math.floor(len / 2);
// If the length is odd, return the midpoint m
// If the length is even, return average of m & m + 1
return len % 2 ? sorted[half] : (sorted[half - 1] + sorted[half]) / 2;
}
/**
* Sensor
* @constructor
*
* @description Generic analog or digital sensor constructor
*
* @param {Object} options Options: pin, freq, range
*/
class Sensor extends Withinable {
constructor(options) {
super();
// Defaults to 10-bit resolution
let resolution = 0x3FF;
let raw = null;
let last = -1;
const samples = [];
Board.Component.call(
this, options = Board.Options(options)
);
if (!options.type) {
options.type = "analog";
}
if (this.io.RESOLUTION &&
(this.io.RESOLUTION.ADC &&
(this.io.RESOLUTION.ADC !== resolution))) {
resolution = this.io.RESOLUTION.ADC;
}
// Set the pin to ANALOG (INPUT) mode
this.mode = options.type === "digital" ?
this.io.MODES.INPUT :
this.io.MODES.ANALOG;
this.io.pinMode(this.pin, this.mode);
// Create a "state" entry for privately
// storing the state of the sensor
const state = {
enabled: typeof options.enabled === "undefined" ? true : options.enabled,
booleanBarrier: options.type === "digital" ? 0 : null,
intervalId: null,
scale: null,
value: 0,
median: 0,
freq: options.freq || 25,
previousFreq: options.freq || 25,
};
// Put a reference where the prototype methods defined in this file have access
priv.set(this, state);
// Sensor instance properties
this.range = options.range || [0, resolution];
this.limit = options.limit || null;
this.threshold = options.threshold === undefined ? 1 : options.threshold;
this.isScaled = false;
this.isScaledRounded = !!options.isScaledRounded;
this.io[`${options.type}Read`](this.pin, data => {
raw = data;
// Only append to the samples when noise filtering can/will be used
if (options.type !== "digital") {
samples.push(raw);
}
});
// Throttle
// TODO: The event (interval) processing function should be outside of the Sensor
// constructor function (with appropriate passed (and bound?) arguments), to
// avoid creating a separate copy (of the function) for each Sensor instance.
const eventProcessing = () => {
let err;
let boundary;
err = null;
// For digital sensors, skip the analog
// noise filtering provided below.
if (options.type === "digital") {
this.emit("data", raw);
/* istanbul ignore else */
if (last !== raw) {
this.emit("change", raw);
last = raw;
}
return;
}
// Keep the previous calculated value if there were no new readings
if (samples.length > 0) {
// Filter the accumulated sample values to reduce analog reading noise
state.median = median(samples);
}
const roundMedian = Math.round(state.median);
this.emit("data", roundMedian);
// If the filtered (state.median) value for this interval is at least ± the
// configured threshold from last, fire change events
if (state.median <= (last - this.threshold) || state.median >= (last + this.threshold)) {
this.emit("change", roundMedian);
// Update the instance-local `last` value (only) when a new change event
// has been emitted. For comparison in the next interval
last = state.median;
}
if (this.limit) {
if (state.median <= this.limit[0]) {
boundary = "lower";
}
if (state.median >= this.limit[1]) {
boundary = "upper";
}
if (boundary) {
this.emit("limit", {
boundary,
value: roundMedian
});
this.emit(`limit:${boundary}`, roundMedian);
}
}
// Reset samples
samples.length = 0;
}; // ./function eventProcessing()
Object.defineProperties(this, {
raw: {
get() {
return raw;
}
},
analog: {
get() {
if (options.type === "digital") {
return raw;
}
return raw === null ? 0 :
Fn.map(this.raw, 0, resolution, 0, 255) | 0;
},
},
constrained: {
get() {
if (options.type === "digital") {
return raw;
}
return raw === null ? 0 :
Fn.constrain(this.raw, 0, 255);
}
},
boolean: {
get() {
const state = priv.get(this);
let booleanBarrier = state.booleanBarrier;
const scale = state.scale || [0, resolution];
if (booleanBarrier === null) {
booleanBarrier = scale[0] + (scale[1] - scale[0]) / 2;
}
return this.value > booleanBarrier;
}
},
scaled: {
get() {
let mapped, constrain;
if (state.scale && raw !== null) {
if (options.type === "digital") {
// Value is either 0 or 1, use as an index
// to return the scaled value.
return state.scale[raw];
}
mapped = Fn.fmap(raw, this.range[0], this.range[1], state.scale[0], state.scale[1]);
if (this.isScaledRounded) {
mapped = Math.round(mapped);
}
constrain = Fn.constrain(mapped, state.scale[0], state.scale[1]);
return constrain;
}
return this.constrained;
}
},
freq: {
get() {
return state.freq;
},
set(newFreq) {
state.freq = newFreq;
if (state.intervalId) {
clearInterval(state.intervalId);
}
if (state.freq !== null) {
state.intervalId = setInterval(eventProcessing, newFreq);
}
}
},
value: {
get() {
if (state.scale) {
this.isScaled = true;
return this.scaled;
}
return raw;
}
},
resolution: {
get() {
return resolution;
}
}
});
/* istanbul ignore else */
if (!!process.env.IS_TEST_MODE) {
Object.defineProperties(this, {
state: {
get() {
return priv.get(this);
}
}
});
}
// Set the freq property only after the get and set functions are defined
// and only if the sensor is not `enabled: false`
if (state.enabled) {
this.freq = state.freq;
}
}
/**
* enable Enable a disabled sensor.
*
* @return {Object} instance
*
*/
enable() {
const state = priv.get(this);
/* istanbul ignore else */
if (!state.enabled) {
this.freq = state.freq || state.previousFreq;
}
return this;
}
/**
* disable Disable an enabled sensor.
*
* @return {Object} instance
*
*/
disable() {
const state = priv.get(this);
/* istanbul ignore else */
if (state.enabled) {
state.enabled = false;
state.previousFreq = state.freq;
this.freq = null;
}
return this;
}
/**
* scale/scaleTo Set a value scaling range
*
* @param {Number} low Lowerbound
* @param {Number} high Upperbound
* @return {Object} instance
*
* @param {Array} [ low, high] Lowerbound
* @return {Object} instance
*
*/
scale(low, high) {
this.isScaled = true;
priv.get(this).scale = Array.isArray(low) ?
low : [low, high];
return this;
}
/**
* scaleTo Scales value to integer representation
* @param {Number} low An array containing a lower and upper bound
*
* @param {Number} low A number to use as a lower bound
* @param {Number} high A number to use as an upper bound
* @return {Number} The scaled value
*/
scaleTo(low, high) {
const scale = Array.isArray(low) ? low : [low, high];
return Fn.map(this.raw, 0, this.resolution, scale[0], scale[1]);
}
/**
* fscaleTo Scales value to single precision float representation
* @param {Number} low An array containing a lower and upper bound
*
* @param {Number} low A number to use as a lower bound
* @param {Number} high A number to use as an upper bound
* @return {Number} The scaled value
*/
fscaleTo(low, high) {
const scale = Array.isArray(low) ? low : [low, high];
return Fn.fmap(this.raw, 0, this.resolution, scale[0], scale[1]);
}
/**
* booleanAt Set a midpoint barrier value used to calculate returned value of
* .boolean property.
*
* @param {Number} barrier
* @return {Object} instance
*
*/
booleanAt(barrier) {
priv.get(this).booleanBarrier = barrier;
return this;
}
}
/**
* Sensors()
* new Sensors()
*
* Constructs an Array-like instance of all servos
*/
class Sensors extends Collection.Emitter {
constructor(numsOrObjects) {
super(numsOrObjects);
}
get type() {
return Sensor;
}
}
Collection.installMethodForwarding(
Sensors.prototype, Sensor.prototype
);
// Assign Sensors Collection class as static "method" of Sensor.
Sensor.Collection = Sensors;
/* istanbul ignore else */
if (!!process.env.IS_TEST_MODE) {
Sensor.purge = () => {
priv.clear();
};
}
module.exports = Sensor;