uci-base/examples/client.js

75 lines
2.0 KiB
JavaScript

/*
simple generic client sending an ack
*
*/
import Base from '../src/base'
const delay = time => new Promise(res=>setTimeout(()=>res(),time))
let opts={id:'simple-client', useRootNS:true}
// if nothing set will be localhost:8080
if (process.env.UCI_HOST || process.env.UCI_PORT || !process.env.UCI_PATH ) {
opts.host = process.env.UCI_HOST
opts.port = process.env.UCI_PORT
} else {
opts.path = process.env.UCI_PATH==='true' ? true : process.env.UCI_PATH
}
(async () => {
let client = new Base(opts)
client.on('status',ev => {
switch (ev.level) {
case 'warning':
case 'error':
case 'fatal':
console.log(ev.level.toUpperCase(),'\n',ev)
break
}
})
function log (packet) {
if (packet.ack) {
console.log('socket acknowledged')
let {_header, cmd, ...rest} = packet
console.log('reply:',rest)
}
else {
console.log('process at socket did not acknowledge')
console.log(packet._header)
}
console.log('------ END REPLY------')
}
// example return processor using a namespace, will take precidence over default and root namespaces
client.cmds = { reply: (packet) => {
console.log('------REPLY--via cmds namespace----')
log(packet) }
}
client.addNamespace('cmds','c') // comment this out to process via root namespace
// alt example return process function making us of root namspace, useRootNS must be set true in options to do this
client.reply = function (packet) {
console.log('------REPLY--via root namespace----')
log(packet)
}
client.addSocket(`client:${opts.path ? 'named-pipe':'tcp'}`,'c',opts.path?'n':'t',opts)
let res = await client.init()
if (res.error) {
console.log('errors during init')
process.kill(process.pid, 'SIGTERM')
}
console.log('connected proceed with ack')
await client.send({cmd:'ack'})
delay(2000)
process.kill(process.pid, 'SIGTERM')
})().catch(err => {
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
process.kill(process.pid, 'SIGTERM')
})