forked from samsonmking/epaper.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (62 loc) · 1.85 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
68
69
70
71
72
73
74
const express = require('express');
const devices = require('./devices.js');
const readline = require('readline');
const WebSocket = require('ws');
const renderBrowser = require('./render.js');
const defaultConfig = {
webPort: 3000,
websocketPort: 8080,
staticDirectory: 'static',
url: `http://localhost:3000/index.html`,
};
const defaultRenderCallback = (page, ws) => {
page.onConsoleLog((msg) => console.log(msg));
ws.on('message', async (message) => {
if (message === 'render') {
await page.display();
}
});
};
function setupKeyInput(driver) {
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.addListener('keypress', (key, data) => {
if (data.ctrl && data.name === 'c') {
driver.sleep();
process.exit();
}
});
}
function setupExitOnSignal(driver) {
const handle = () => {
driver.sleep();
process.exit();
};
process.on('SIGINT', handle);
process.on('SIGTERM', handle);
}
function init(
screen = devices.waveshare4in2,
config = {},
renderCallback = defaultRenderCallback
) {
const configWithDefaults = { ...defaultConfig, ...config };
if (process.stdin.isTTY) {
setupKeyInput(screen.driver);
} else {
setupExitOnSignal(screen.driver);
}
const wss = new WebSocket.Server({
port: configWithDefaults.websocketPort,
});
if (!configWithDefaults.skipWebServer) {
const app = express();
app.use(express.static(configWithDefaults.staticDirectory));
app.listen(configWithDefaults.webPort, () => {
renderBrowser(screen, wss, renderCallback, configWithDefaults.url);
});
} else {
renderBrowser(screen, wss, renderCallback, configWithDefaults.url);
}
}
module.exports = { init, devices };