1 | var Emitter = require("events").EventEmitter;
|
2 | var util = require("util");
|
3 |
|
4 | var Board = require("./board");
|
5 | var Fn = require("./fn");
|
6 | var within = require("./mixins/within");
|
7 |
|
8 | var toFixed = Fn.toFixed;
|
9 |
|
10 | var priv = new Map();
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function Ping(opts) {
|
18 |
|
19 | if (!(this instanceof Ping)) {
|
20 | return new Ping(opts);
|
21 | }
|
22 |
|
23 | var last = null;
|
24 |
|
25 | Board.Component.call(
|
26 | this, opts = Board.Options(opts)
|
27 | );
|
28 |
|
29 | this.pin = opts && opts.pin || 7;
|
30 | this.freq = opts.freq || 20;
|
31 |
|
32 |
|
33 | var state = {
|
34 | value: null
|
35 | };
|
36 |
|
37 |
|
38 | var settings = {
|
39 | pin: this.pin,
|
40 | value: this.io.HIGH,
|
41 | pulseOut: 5
|
42 | };
|
43 |
|
44 | this.io.setMaxListeners(100);
|
45 |
|
46 |
|
47 | setInterval(function() {
|
48 | this.io.pingRead(settings, function(microseconds) {
|
49 | state.value = microseconds;
|
50 | });
|
51 | }.bind(this), 225);
|
52 |
|
53 |
|
54 | setInterval(function() {
|
55 | if (state.value === null) {
|
56 | return;
|
57 | }
|
58 |
|
59 |
|
60 |
|
61 | this.emit("data", state.value);
|
62 |
|
63 |
|
64 |
|
65 | if (state.value !== last) {
|
66 | this.emit("change", state.value);
|
67 | }
|
68 |
|
69 |
|
70 | last = state.value;
|
71 |
|
72 |
|
73 |
|
74 | }.bind(this), this.freq);
|
75 |
|
76 | Object.defineProperties(this, {
|
77 | value: {
|
78 | get: function() {
|
79 | return state.value;
|
80 | }
|
81 | },
|
82 |
|
83 |
|
84 | inches: {
|
85 | get: function() {
|
86 | return toFixed(state.value / 74 / 2, 2);
|
87 | }
|
88 | },
|
89 | in: {
|
90 | get: function() {
|
91 | return this.inches;
|
92 | }
|
93 | },
|
94 | cm: {
|
95 | get: function() {
|
96 | return toFixed(state.value / 29 / 2, 3);
|
97 | }
|
98 | }
|
99 | });
|
100 |
|
101 | priv.set(this, state);
|
102 | }
|
103 |
|
104 | util.inherits(Ping, Emitter);
|
105 |
|
106 | Object.assign(Ping.prototype, within);
|
107 |
|
108 | module.exports = Ping;
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|