/
socketreader.js
96 lines (80 loc) · 1.8 KB
/
socketreader.js
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
/*
* socketreader
*
* this script just scans GPIO pins and pings the movement URLs
*/
var Gpio = require('onoff').Gpio,
pinA = new Gpio(17, 'in', 'both', {debounceTimeout: 0}),
pinB = new Gpio(27, 'in', 'both', {debounceTimeout: 0});
var request = require('request');
function exit() {
pinA.unexport();
pinB.unexport();
console.log('pins unexported');
process.exit();
}
var rotaryA = 0;
var rotaryB = 0;
var newState = 0;
var lastState = 0;
var prevDelta = 0;
pinA.watch(function (err, value) {
if (err) {
throw err;
}
if(value != rotaryA) {
rotaryA = value;
updateClient();
}
});
pinB.watch(function (err, value) {
if (err) {
throw err;
}
if(value != rotaryB) {
rotaryB = value;
updateClient();
}
});
function updateClient() {
var xorVal = rotaryA ^ rotaryB;
// Get the new rotary encoder state
var newState = (rotaryA * 4) + (rotaryB * 2) + (xorVal * 1);
// Get the delta (difference) between the previous state and the new state
var delta = (newState - lastState) % 4;
// Store the state for next time around
lastState = newState;
//delta:
// 0 = no change
// 1 = one step clockwise
// 2 = two steps in either direction
// 3 = one step counter clockwise
switch(delta) {
case 1:
right();
prevDelta = delta;
//console.log(count);
break;
case 3:
left();
prevDelta = delta;
//console.log(count);
break;
case 2:
//console.log('-');
if(prevDelta == 1) {
right();
}
if(prevDelta == 3) {
left();
}
break;
}
}
function right() {
request('http://localhost:5000/movement/right', function(err,res,body) {});
}
function left() {
request('http://localhost:5000/movement/left', function(err,res,body) {});
}
process.on('SIGINT', exit);