ble-server/server.js
2017-12-15 22:58:04 +08:00

141 lines
3.0 KiB
JavaScript

const Koa = require('koa')
const fs = require('fs')
const path = require('path')
const localEvent = require('./localEvent')
const WebSocket = require('ws')
const exec = require('child_process').exec
const Printer = require('./PrinterDev')
// koa middleware
const KoaLogger = require('koa-morgan')
const KoaEjs = require('koa-ejs')
const KoaMount = require('koa-mount')
const KoaStatic = require('koa-static')
const KoaRouter = require('koa-router')
const Kcors = require('kcors')
const app = new Koa()
let config = {}
let setupMode = false
try {
let chk = new Promise((resolve, reject) => {
fs.access(path.resolve(process.env.PROJECT_ROOT, 'config.json'), (err) => {
if (err) {
setupMode = true
resolve(0)
return
}
config = require('./config.json')
resolve(1)
})
})
await chk //eslint-disable-line
} catch (err) {
setupMode = true
}
const server = app.listen(config.port || 10230, () => {
console.log(`Server start on port ${server.address().port}`)
})
const ws = new WebSocket.Server({ server })
app.use(Kcors())
app.use(KoaLogger('short'))
app.use(KoaStatic(path.resolve(__dirname, 'public')))
KoaEjs(app, {
root: path.resolve(__dirname, 'views'),
layout: false,
viewExt: 'ejs',
cache: false,
debug: false
})
let router = null
if (setupMode) {
console.log(`start setup mode`)
router = require('./route/install')
} else {
console.log(`start normal mode`)
router = require('./route/dashboard')
Printer.serial = config.printer.serial
Printer.feed = config.printer.feed
await Printer.connect()
Printer.on('close', ()=>{
console.log('device disconnect')
})
}
if (router !== null) {
// set Route
app.use(router.routes())
app.use(router.allowedMethods())
router.put('/reboot_sys', async (c, n) => {
setTimeout(function () {
process.exit(1)
}, 2000)
c.body = '1'
})
}
// listen print event
localEvent.on('print', async str => {
let chk = await Printer.printerString(str)
localEvent.emit('printResult', chk)
})
let systemStatus = {
printer: {
connect: false,
serial: '',
feed: 0
},
pcount: 0,
lastprint: '',
secret: ''
}
systemStatus.secret = config.api.secret
function getPrinterStatus() {
systemStatus.printer.connect = Printer.isOpen
systemStatus.printer.serial = Printer.serial
systemStatus.printer.feed = Printer.feed
systemStatus.pcount = Printer.count
systemStatus.lastprint = Printer.lastPrint
}
getPrinterStatus()
ws.on('connection', async (client, req) => {
getPrinterStatus()
client.send(JSON.stringify({ type: 'status', data: systemStatus }))
Printer.on('printDone', () => {
getPrinterStatus()
client.send(JSON.stringify({ type: 'status', data: systemStatus }))
})
client.on('message', msg => {
let m = {}
try {
m = JSON.parse(msg)
} catch (err) {
return
}
switch (m.type) {
case 'status':
client.send(JSON.stringify({ type: 'status', data: systemStatus }))
break
}
})
})