-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbin.js
executable file
·147 lines (116 loc) · 2.54 KB
/
bin.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
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
#!/usr/bin/env node
import fs from 'fs'
import { connect } from 'mqtt'
import yaml from 'js-yaml'
import debug from 'debug'
const log = debug('prusa-mqtt')
const nullbyte = Buffer.allocUnsafe(0)
function PrusaPrinter(host, apiKey) {
async function req(url, method = 'GET', headers = {}) {
const req = await fetch(host + '/api' + url, {
method,
headers: {
'X-Api-Key': apiKey,
...headers,
}
})
const json = await req.json()
return json
}
const self = {
async info() {
const job = await req('/job')
return job
}
}
return self
}
console.log('Starting...')
let config
try {
config = yaml.load(fs.readFileSync(process.argv.pop(), 'utf8'))
} catch (e) {
throw e
}
const client = connect(config.mqtt)
function Daemon(client, { display, ip, key, topic }) {
const printer = PrusaPrinter("http://" + ip, key)
let lock
let cleared = false
async function clear() {
if (cleared) return log('@%s: Skip clear', display)
log('@%s: Clearing', display)
await client.publishAsync(topic, nullbyte, {
retain: true
})
cleared = true
}
let queued = false
async function wrapper() {
if (queued) return
try {
queued = true
await lock
} catch (e) {
// noop
}
queued = false
if (!intv) return
lock = main()
}
async function main() {
let info
try {
info = await printer.info()
} catch (e) {
log('@%s: Failed to fetch info: %o', display, String(e))
await clear()
return
}
if (info.state === 'Printing' || info.state === 'Finished') {
log('@%s: Publishing job %s', display, info.job.file.display)
await client.publishAsync(topic, JSON.stringify({
Printer: display,
Job: info.job.file.display,
Elapsed_time_s: info.progress.printTime,
Progress_percent: Math.floor(info.progress.completion * 100)
}))
cleared = false
} else {
await clear()
}
}
let intv
return {
start() {
log('@%s: Starting', display)
if (!intv) intv = setInterval(wrapper, 1000)
},
async stop() {
log('@%s: Stopping', display)
clearInterval(intv)
await lock
await clear()
intv = null
log('@%s: Stopped', display)
}
}
}
let daemons = []
for (const printer of config.printers) {
daemons.push(Daemon(client, printer))
}
for (const daemon of daemons) {
daemon.start()
}
console.log('Started!')
async function stop() {
console.log('Stopping...')
for (const daemon of daemons) {
await daemon.stop()
}
await client.endAsync()
console.log('Stopped!')
}
process.on('SIGINT', stop)
process.on('SIGTERM', stop)