forked from electricimp/ConnectionManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionManager.lib.nut
More file actions
401 lines (327 loc) · 12.1 KB
/
ConnectionManager.lib.nut
File metadata and controls
401 lines (327 loc) · 12.1 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
396
397
398
399
400
401
// MIT License
// Copyright 2015-2017 Electric Imp
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
class ConnectionManager {
static VERSION = "2.0.0";
static BLINK_ALWAYS = 0;
static BLINK_NEVER = 1;
static BLINK_ON_CONNECT = 2;
static BLINK_ON_DISCONNECT = 3;
static FLUSH_TIMEOUT = 30;
static START_NO_ACTION = 0;
static START_CONNECTED = 1;
static START_DISCONNECTED = 2;
// Settings
_connectTimeout = null;
_checkTimeout = null;
_stayConnected = null;
_blinkupBehavior = null;
_retryOnTimeout = null;
// Global Handlers
_onConnect = null;
_onTimeout = null;
_onDisconnect = null;
// Connection State
_connected = null;
_connecting = null;
// The onConnected task queue and logs
_queue = null;
_logs = null;
constructor(settings = {}) {
// Grab settings
_checkTimeout = ("checkTimeout" in settings) ? settings.checkTimeout : 5;
_connectTimeout = ("connectTimeout" in settings) ? settings.connectTimeout : 60;
_stayConnected = ("stayConnected" in settings) ? settings.stayConnected : false;
_blinkupBehavior = ("blinkupBehavior" in settings) ? settings.blinkupBehavior : BLINK_ON_DISCONNECT;
_retryOnTimeout = ("retryOnTimeout" in settings) ? settings.retryOnTimeout : true;
local startBehavior = ("startBehavior" in settings) ? settings.startBehavior : START_NO_ACTION;
local ackTimeout = ("ackTimeout" in settings) ? settings.ackTimeout : 1;
// Initialize the onConnected task queue and logs
_queue = [];
_logs = [];
// Set the timeout policy + disconnect if required
server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, ackTimeout);
switch (startBehavior) {
case START_NO_ACTION:
// Do nothing
break;
case START_CONNECTED:
// Start connecting if they ask for it
imp.wakeup(0, connect.bindenv(this));
break;
case START_DISCONNECTED:
// Disconnect if required
imp.wakeup(0, disconnect.bindenv(this));
break;
}
// Get the initial state and set BlinkUp accordingly
_setBlinkUpState();
// Start the watchdog
_watchdog();
}
// Sets an onConnect handler that fires everytime we connect. Passing
// null to this function removes the onConnect handler
//
// Parameters:
// callback: The onConnect handler (no parameters)
//
// Returns: this
function onConnect(callback) {
_onConnect = callback;
return this;
}
// Sets an onTimeout handler that fires when a connection attempt fails. Passing
// null to this function removes the onTimeout handler
//
// Parameters:
// callback: The onTimeout handler (no parameters)
//
// Returns: this
function onTimeout(callback) {
_onTimeout = callback;
return this;
}
// Sets a onDisconnect handler that fires everytime we disconnect. Passing
// null to this function removes the onDisconnect handler
//
// Parameters:
// callback: The onDisconnectHandler with 1 parameter:
// expected True - when onDisconnect was called because of a disconnect()
// False - otherwise
//
// Returns: this
function onDisconnect(callback) {
_onDisconnect = callback;
return this;
}
// Returns the ConnectionManager's view of if we're connected or not
function isConnected() {
return _connected;
}
// Attempts to connect. If the server is already connected, or the
// connection attempt was successful, run the onConnect handler, and
// any other onConnected tasks
function connect() {
// If we're connecting/disconnecting, try again in 0.5 seconds
if (_connecting) return false;
// If we're already connected: invoke the onConnectedFlow and return
if (_connected) {
_onConnectedFlow();
return true;
}
// Otherwise, try to connect...
// Set the _connecting flag at the start
_connecting = hardware.millis();
server.connect(function(result) {
// clear connecting flag when we're done trying to connect
_connecting = false;
if (result == SERVER_CONNECTED) {
// If it worked, run the onConnectedFlow
_connected = true;
_onConnectedFlow();
} else {
// Otherwise, restart the connection process
_onTimeoutFlow();
}
}.bindenv(this), _connectTimeout);
// Catch a race condition where server.connect() won't throw the callback if its already connected
if (server.isconnected()) {
_connecting = false;
_connected = true;
_onConnectedFlow();
}
return true;
}
// Disconnects, and runs the onDisconnected handler
function disconnect() {
// If we're connecting / disconnecting, try again in 0.5 seconds
if (_connecting) { return false; }
// If we're already disconnected: invoke the onDisconnectedFlow and return
if (!_connected) {
_onDisconnectedFlow(true);
return true;
}
// Disconnect
server.flush(FLUSH_TIMEOUT);
server.disconnect();
// Set the flag
_connected = false;
// Run the onDisconnectedFlow
_onDisconnectedFlow(true);
return true;
}
// Pushes a task onto the onConnected task queue that will
// be executed the next time the device connects. if the device
// is already connected, it will be executed immediatly
//
// Parameters:
// callback The task to execute
//
// Returns: this
function onNextConnect(callback) {
_queue.push(callback);
_processQueue();
return this;
}
// Queues the callback to run on next connect, then connects,
// runs all queued tasks and disconnects
function connectFor(callback) {
local cb = _connectForCallbackFactory(callback);
_queue.push(cb);
connect();
}
// Sets the BlinkUp behavior to one of the preconfigured options
//
// Parameters:
// state: BLINK_ALWAYS | BLINK_NEVER | BLINK_ON_CONNECT | BLINK_ON_DISCONNECT
//
// Returns: this
function setBlinkUpBehavior(state) {
_blinkupBehavior = state;
_setBlinkUpState();
return this;
}
function log(obj, error = false) {
if (_connected) {
if (error) {
server.error(obj.tostring());
} else {
server.log(obj.tostring());
}
} else {
_logs.push({ "ts": time(), "error": error, "log": obj.tostring() });
}
}
function error(obj) {
log(obj, true);
}
//-------------------- PRIVATE METHODS --------------------//
// Wraps a callback function so it executes, then immediatly
// disconnects.
function _connectForCallbackFactory(callback) {
return function() {
callback();
disconnect();
}.bindenv(this);
}
// Watches for changes in connection state, and invokes the
// onConnectedFlow and onDisconnectedFlow where appropriate
function _watchdog() {
// Schedule _watchdog to run again
imp.wakeup(_checkTimeout, _watchdog.bindenv(this));
// Don't do anything if we're connecting (unless there is a timeout of course)
if (_connecting) {
if (hardware.millis() - _connecting > (_connectTimeout*1000)) {
_onTimeoutFlow()
}
return;
}
// Check if we're connected
local connected = server.isconnected()
// If the state hasn't changed, we're done
if (_connected == connected) return;
// Set the new connected state
_connected = connected;
// Run the appropriate flow
if (connected) {
_onConnectedFlow();
} else {
_onDisconnectedFlow(false);
}
}
// Runs whenever we connect or call connect()
function _onConnectedFlow() {
// Set the BlinkUp State
_setBlinkUpState();
while(_logs.len() > 0) {
local log = _logs.remove(0);
if (!log.error) {
server.log(log.ts + " - " + log.log)
} else {
server.error(log.ts + " - " + log.log)
}
}
// Run the global onConnected Handler if it exists
if (_onConnect != null) {
imp.wakeup(0, function() { _onConnect(); }.bindenv(this));
}
_processQueue();
}
// Runs whenever we disconnect, or call disconnect()
function _onDisconnectedFlow(expected) {
// Set the BlinkUp State
_setBlinkUpState();
// Run the global onDisconnected Handler if it exists
if (_onDisconnect != null) {
imp.wakeup(0, function() { _onDisconnect(expected); }.bindenv(this));
}
if (_stayConnected) {
imp.wakeup(0, connect.bindenv(this));
} else {
// Brutally stop trying to connect
server.disconnect();
}
}
// Runs whenever a call to connect times out
function _onTimeoutFlow() {
// Set the BlinkUp State
_setBlinkUpState();
_connecting = false;
_connected = false;
if (_onTimeout != null) {
imp.wakeup(0, function() { _onTimeout(); }.bindenv(this));
}
if (_retryOnTimeout) {
// We have a timeout trying to connect. We need to retry;
imp.wakeup(0, connect.bindenv(this));
}
}
// Helper function for _onConnectedFlow that processes all the tasks
// in the onConnected _queue or quits once we're no longer connected
function _processQueue() {
// If we're done, are connecting/disconnecting, or are disconnected
if (_queue.len() == 0 || _connecting || !_connected) return;
local cb = _queue.remove(0);
imp.wakeup(0, function() {
// Invoke the next queued task
cb();
// Do it again!!
_processQueue();
}.bindenv(this));
}
// Enables of disables BlinkUp based on _blinkupBehavior and _connected
function _setBlinkUpState() {
// If it's set to always blinkup
if (_blinkupBehavior == BLINK_ALWAYS) {
imp.enableblinkup(true);
return;
}
// If it's set to never blinkup
if (_blinkupBehavior == BLINK_NEVER) {
imp.enableblinkup(false);
return;
}
// If it's set to blinkup on a specific state
if ((_connected && _blinkupBehavior == BLINK_ON_CONNECT)
|| (!_connected && _blinkupBehavior == BLINK_ON_DISCONNECT)) {
imp.enableblinkup(true);
} else {
imp.enableblinkup(false);
}
}
}