forked from bnielsen1965/node-pi-buttons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (59 loc) · 1.92 KB
/
index.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
'use strict';
const net = require('net');
const events = require('events');
const SOCKET_PATH = "/var/run/pi-buttons.sock";
const RECONNECT_TIMEOUT = 3000;
module.exports = function (config) {
config = config || {};
config.socketPath = config.socketPath || SOCKET_PATH;
config.reconnectTimeout = config.reconnectTimeout || RECONNECT_TIMEOUT;
let emitter = new events.EventEmitter();
emitter.piButtonsSocket = null;
// expose function to destroy underlying socket
emitter.destroySocket = function () {
emitter.piButtonsSocket.destroy();
}
// create client connected to pi-buttons socket path
function createClient() {
emitter.piButtonsSocket = net.createConnection(config.socketPath, function () {
// on first connect establish client listening events
clientListener(emitter.piButtonsSocket);
});
}
// create listeners on client socket connection
function clientListener(piButtonsSocket) {
piButtonsSocket
.on('end', function () {
// lost connection, try to reconnect after a delay
setTimeout(createClient, config.reconnectTimeout);
})
.on('data', function (data) {
// may be more than one message packet
let packets = data.toString().split(/\r?\n/);
packets.forEach(function (packet) { parsePacket(packet); });
})
}
// parse a packet received from the pi-buttons socket
function parsePacket(packet) {
// split packet into event and JSON
let parts = /^([^{]+)\s({.*})/.exec(packet);
if (parts) {
try {
var d = JSON.parse(parts[2]);
switch(parts[1]) {
case 'error':
emitter.emit(parts[1], d);
break;
default:
// emit event with event type, gpio number, event JSON data
emitter.emit(parts[1], d.gpio, d);
break;
}
}
catch (e) {}
}
}
// init by creating the first client connection
createClient()
return emitter;
}