ble-server/app.js

59 lines
1.2 KiB
JavaScript

const bleno = require('bleno')
const config = require('./config.json')
const adapterName = 'BLE_Printer'
const serverUUID = config.uuid.main
const localEvent = require('./localEvent')
const fs = require('fs')
const MainService = require('./main-service')
const printer = require('./PrinterDev')
async function initSystem(){
try{
await printer.connect()
}catch(err){
throw err
}
}
initSystem()
bleno.on('stateChange', state => {
console.log(`bt device state ${state}`)
if (state == 'poweredOn') {
bleno.startAdvertising(adapterName, [serverUUID], (error) => {
})
} else {
bleno.stopAdvertising()
}
})
bleno.on('advertisingStart', function (error) {
console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
if (!error) {
bleno.setServices([new MainService()], error => {
console.log('set service', error)
})
}
})
localEvent.on('print', async (str) => {
let status = false
if (printer.isOpen) {
try {
status = await printer.printerString(str)
} catch (err) {
status = false
}
}
localEvent.emit('printResult', status)
})
process.on('SIGINT', () => {
printer.close()
process.exit(0)
})