demo-sp/deviceObject.js

38 lines
744 B
JavaScript

const SerialPort = require('serialport')
const EventEmitter = require('events')
class DeviceObject extends EventEmitter {
constructor (port, opts = {}) {
super()
this._port = port
this._spOpts = opts
this._sp = null
this.isOpen = false
}
connect () {
this._sp = new SerialPort(this._port, this._spOpts)
this._sp.open(() => {
this.isOpen = true
this.emit('open')
})
this._sp.on('close', () => {
this.isOpen = false
this.emit('close')
}).on('data', data => {
this.emit('data', data)
})
}
static async getPorts () {
try {
let list = SerialPort.list()
return list
} catch (err) {
return null
}
}
}
module.exports = DeviceObject