uci-socket/src/consumer.mjs

85 lines
2.2 KiB
JavaScript

import { Socket } from 'net'
import btc from 'better-try-catch'
export default class Consumer extends Socket {
constructor (path, opts={}) {
super()
this.path = path
this.keepAlive = opts.keepAlive ? opts.keepAlive : true
this._ready = false
}
ready() {return this._ready}
async connect (app) {
await this.listen(app)
console.log('consumer: listening')
await super.connect({ path: this.path })
console.log(`consumer: connected to ${this.path}`)
this.setKeepAlive(this.keepAlive)
this.on('error', (error) => {
'client socket error \n ', error.code
})
return await isReady(this.ready.bind(this))
}
async send(packet) {
let [err, strbuf] = btc(JSON.stringify)(packet)
if (!err) {
// await promisify(this.write)(strbuf)
console.log('attempting to send')
// console.log(await this.write(strbuf))
let res = await new Promise((resolve, reject) => { //returning promise
this.write(strbuf, (err) => {
if (err) reject(err)
else resolve('complete')
})
})
console.log('send is', res)
}
else { console.log(`bad packet JSON syntax \n ${packet} \n${err}`)}
}
async listen (app) {
this.on('data', async (buf) => {
let [err, packet] = btc(JSON.parse)(buf.toString())
if (!err) {
if (packet.ready) {
this._ready = true
return }
// set default packet processing - simple print to console of packet
app.ucpp = app.ucpp || 'processPacket'
if (!app[app.ucpp]) {
app.ucpp = 'processPacket'
app.processPacket = async (packet) => {
console.log('incoming packet from socket')
console.dir(packet)
return packet }
}
app[app.ucpp](packet) // process the packet
}
else { console.log(`bad packet JSON syntax \n ${buf.toString()}`)}
})
}
} // end class
// wait for handshake from socket
function isReady(ready) {
let time = 0
return new Promise(function (resolve, reject) {
(function waitReady(){
if (time > 3000) return reject('timeout')
if (ready()) return resolve('ready')
console.log('waiting for 30ms')
time += 30
setTimeout(waitReady, 30)
})()
})
}