ble-server/route/install.js
2017-09-13 08:06:57 +08:00

125 lines
3.0 KiB
JavaScript

/* eslint-disable no-throw-literal */
const KoaRouter = require('koa-router')
const router = new KoaRouter()
const fs = require('fs')
const path = require('path')
const Printer = require('../PrinterDev')
const KoaBody = require('koa-body')
const uuid = require('uuid')
router.use(async (c, n) => {
c.data = {
title: 'Printer System Setup'
}
let status = 1
try {
await n()
} catch (err) {
status = 0
if (typeof err === 'string') {
c.body = err
} else {
c.body = err.toString()
}
}
if (c.async) {
c.body = {
status,
msg: c.body
}
}
})
router
.get('/', async (c, n) => {
c.redirect('/install')
})
.get('/install', async (c, n) => {
// get ttys
let ttys = await new Promise((resolve, reject) => {
fs.readdir(path.resolve('/dev'), (err, list) => {
if (err) return resolve([])
let arr = []
for (let it of list) {
if (/^tty[A-z]/.test(it)) {
arr.push(path.resolve('/dev', it))
}
}
resolve(arr)
})
})
c.data.ttys = ttys
await c.render('install/index', c.data)
})
.post('/install/printer_test', KoaBody(), async (c, n) => {
c.async = true
let arr = c.request.body
if (!arr.device) throw '請輸入印表機連接埠'
let device = arr.device
let feed = arr.feed || 8
if (!isFinite(feed) || feed < 0) throw '切紙前換行必須是整數'
feed = typeof feed !== 'number' ? Math.floor(parseInt(feed)) : feed
Printer.serial = device
Printer.feed = feed
let status = await Printer.printTestPage()
if (!status) c.body = '測試失敗'
else c.body = '測試成功'
})
.post('/install/write_config', KoaBody(), async (c, n) => {
c.async = true
let arr = c.request.body
if (!arr.tty) throw '請輸入印表機連接埠'
if (!arr.ble || (arr.ble !== 'yes' && arr.ble !== 'no')) throw '請輸入藍牙啟用設定'
let feed = arr.feed || 8
if (!isFinite(feed) || feed < 0) throw '切紙前換行必須是整數'
feed = typeof feed !== 'number' ? Math.floor(parseInt(feed)) : feed
let json = {
ble: {
enable: false,
uuid: {
main: '',
service: '',
characteristic: ''
}
},
printer: {
serial: '',
feed: 8
},
api: {
secret: ''
}
}
json.ble.enable = arr.ble === 'yes'
json.ble.uuid.main = uuid.v4()
json.ble.uuid.service = uuid.v4()
json.ble.uuid.characteristic = uuid.v4()
json.printer.serial = arr.tty
json.printer.feed = feed
json.api.secret = arr.secret || ''
let wconfig = await new Promise((resolve, reject) => {
fs.writeFile(path.resolve(process.env.PROJECT_ROOT, 'config.json'), JSON.stringify(json, null, 2), {
mode: 0o664,
encoding: 'utf8',
flag: 'w'
}, err => {
if (err) return resolve(false)
return resolve(true)
})
})
if (!wconfig) throw '設定檔寫入失敗'
c.body = '設定檔寫入成功'
})
module.exports = router