-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathboard.js
More file actions
129 lines (105 loc) · 2.74 KB
/
board.js
File metadata and controls
129 lines (105 loc) · 2.74 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
var webduino = require('webduino-js'),
undef = void 0;
module.exports = function (RED) {
'use strict';
var map = {
mqtt: 'device',
serial: 'path',
bluetooth: 'address',
websocket: 'url'
};
function Board(n) {
var node = this;
RED.nodes.createNode(node, n);
node.transport = n.transport;
node.device = n.device;
node.path = n.path;
node.address = n.address;
node.url = n.url;
node.nodes = [];
node.onInits = [];
node.mount = function (node, initFunc) {
this.nodes.push(node);
this.onInits.push(initFunc);
setDisconnected(this);
};
node.opts = {
transport: node.transport,
multi: true
};
n.board && (node.opts.board = n.board);
node.opts[map[node.transport]] = node[map[node.transport]];
boardReady(node, function () {
setConnected(node);
doInit(node.onInits, node.board);
});
node.on('close', function () {
if (node.board) {
node.board.disconnect();
}
});
}
function boardReady(node, autoReconnect, callback) {
var callback = (typeof autoReconnect === 'function' ? autoReconnect : callback),
board = createBoard(node.opts),
terminate = function () {
node.board = null;
delete node.board;
if (autoReconnect === true) {
setTimeout(function () {
boardReady(node, autoReconnect, callback);
}, 5000);
}
};
node.board = board;
board.once(webduino.BoardEvent.ERROR, function (err) {
if (board.isConnected) {
board.once(webduino.BoardEvent.DISCONNECT, terminate);
board.disconnect();
} else {
terminate();
}
});
board.once(webduino.BoardEvent.READY, callback);
board.on(webduino.BoardEvent.ERROR, function () {
setDisconnected(node);
});
board.on(webduino.BoardEvent.DISCONNECT, function () {
setDisconnected(node);
});
}
function createBoard(opts) {
if (opts.board) {
return new webduino.board[opts.board](opts);
}
if (opts.transport === 'mqtt') {
return new webduino.WebArduino(opts);
}
return new webduino.Arduino(opts);
}
function setConnected(boardNode) {
setStatus(boardNode.nodes, {
fill: 'green',
shape: 'dot',
text: 'connected'
});
}
function setDisconnected(boardNode) {
setStatus(boardNode.nodes, {
fill: 'yellow',
shape: 'ring',
text: 'disconnected'
});
}
function setStatus(nodes, status) {
nodes.forEach(function (n) {
n.status(status);
});
}
function doInit(onInits, board) {
onInits.forEach(function (initFunc) {
initFunc.apply(undef, [board]);
});
}
RED.nodes.registerType('board', Board);
};