This repository was archived by the owner on Jun 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (65 loc) · 2 KB
/
server.js
File metadata and controls
73 lines (65 loc) · 2 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
import chalk from 'chalk';
import { defaultsDeep, pick } from 'lodash/object';
import setUpConnection from './serial';
import log from './util/logging';
import {oneMinute} from './util/time';
const tags = {
open: (string) => chalk`{cyan.bold [Open]:} {green ${string}}`,
close: (string) => chalk`{cyan.bold [Close]:} {red ${string}}`,
data: (string) => chalk`{cyan.bold [Data]:} {magenta ${string}}`,
error: (string) => chalk`{red.bold [Error]:} ${string}`,
info: (string) => chalk`{yellow.bold [Info]:} {cyan ${string}}`,
};
const sleep = (millis) => new Promise(resolve => setTimeout(resolve, millis));
``
class Server {
static defaultConfig = {
portPath: '',
setUpConnection: setUpConnection,
connectionOptions: {
autoOpen: false,
baudRate: 9600,
},
handlers: {
open: () => log(tags.open('Port opened')),
close: () => log(tags.close('Port closed')),
data: (data) => log(tags.data(data.toString())),
error: (err) => log(tags.error(err.message)),
}
};
constructor(config) {
const acceptedConfig = pick(config, ['portPath', 'connectionOptions']);
this.config = {};
Object.assign(this.config, acceptedConfig);
defaultsDeep(this.config, Server.defaultConfig);
}
async openPort() {
let retryCount = 10;
let port;
while (port === undefined && retryCount > 0) {
try {
port = await this.connect();
}
catch (e) {
log(tags.error(e));
retryCount--;
log(tags.info('Failed to open port retrying in 1 minute'));
await sleep(oneMinute);
}
}
return port;
}
async connect() {
const { portPath, connectionOptions, handlers } = this.config;
this.port = await setUpConnection(portPath, connectionOptions, handlers);
return this.port;
}
async idle() {
if (this.port === undefined ) throw 'Cannot idle; port is not open';
while (this.port.isOpen) {
await sleep(oneMinute);
await port.writeAsync('Idling\n');
}
}
}
export default Server;