uci-base/src/base.mjs

99 lines
3.0 KiB
JavaScript

// import { Socket, Consumer } from '@uci/socket'
import { Socket, Consumer } from '../../uci-socket/src'
import packet from './packet.mjs'
import EventEmitter from 'events'
const USOCKET = __dirname + '/unix.sock'
const delay = time => new Promise(res=>setTimeout(()=>res(),time))
export default class Base extends EventEmitter {
constructor(opts={}) {
super()
opts.path = opts.path || USOCKET
this.id = opts.id // a unique ecosystem wide id, could be generated
this.desc = opts.desc // additional details for humans
// attach unix socket OR consumer(default) only if path is supplied
this.socket={}
opts.sockets.split(/[,:|\s]+/).forEach( sock => {
opts.name = this.id +':'+sock
if (!opts[sock]) opts[sock] = {}
switch (sock) {
case
'us':
opts.us.path = opts.us.path || opts.path
this.socket[sock] = new Socket(opts.us.path,opts)
break
case 'uc':
opts.uc.path = opts.uc.path || opts.path
this.socket[sock] = new Consumer(opts.uc.path,opts)
break
case 'ts':
this.socket[sock]= new Socket(opts.ts, opts)
break
case 'tc':
this.socket[sock]= new Consumer(opts.tc,opts)
}
})
} // end constructor
async init (context) {
context = context || this // context is Base for all if not supplied
for(let type of Object.keys(this.socket)){
if (type.indexOf('s')!==-1) {
this.socket[type].packet = Object.assign({},packet.socket) // default packet processing
await this.socket[type].create(context)
// setTimeout(context =>{this.socket[type].create(context)},500)
}
else {
this.socket[type].packet = Object.assign({},packet.consumer) // default packet processing
await this.socket[type].connect(context)
}
}
} // init
registerPacketContext(type, context) {
if (typeof type === 'string') {
this.socket[type].registerPacketContext(Object.assign({},context))
} else {
context=type
for(let type of Object.keys(this.socket)){
this.socket[type].registerPacketContext(context)
}
}
}
amendPacketContext(type, context) {
if (typeof type === 'string') {
Object.assign(this.socket[type].packet.context,context)
} else {
context=type
for(let type of Object.keys(this.socket)){
Object.assign(this.socket[type].packet.context,context)
}
}
}
amendPacketProcessing(type,funcs) {
this.socket[type].packet = Object.assign({},this.socket[type].packet,funcs)
}
registerPacketProcessor(type,func) {
if (typeof type === 'string') {
this.socket[type].packet._process = func
} else {
func = type
for(let type of Object.keys(this.socket)){
this.socket[type].registerPacketProcessor(func)
}
}
}
async send (packet) {
this.emit(packet.cmd, packet)
if (this.socket.uc) await this.socket.uc.send(packet)
if (this.socket.tc) await this.socket.tc.send(packet)
}
} // end class