uci-base/examples/four-in-one.js

88 lines
2.5 KiB
JavaScript

import Base from '../src/base'
// const USOCKET = __dirname + '/sample.sock'
const socketfuncs = {
switch: {
on: function(packet){
return new Promise( async (resolve) => {
packet.cmd='status/on'
this.push(packet) // push to all active socket servers
let res = { response:'status pushed on to all clients'}
return resolve(res)
})
},
off: function(packet){
return new Promise( async (resolve) => {
packet.cmd='status/off'
this.push(packet) // push to all active socket servers
let res = { response:'status pushed off to all clients'}
return resolve(res)
})
},
toggle: function(packet){
return new Promise( async (resolve) => {
// would check status before deciding what to push
if (packet.status===null) packet.status = Math.random()>=.5 ? 'on' : 'off'
else packet.status = (packet.status==='on' ? 'off' : 'on')
packet.cmd ='status/'+ packet.status
this.push(packet) // push to all active socket servers
let res = { cmd:'reply', response:`command ${packet.cmd} with id:${packet.id} pushed to all consumers(clients)`}
return resolve(res)
})
}
}
}
const clientfuncs = {
reply: packet => {
return new Promise( async (resolve) => {
console.log('==============Reply Processor at Consumer==========')
console.dir(packet.response)
return resolve()
})
},
status: {
on: packet => {
return new Promise( async (resolve) => {
console.log('==============Pushed to Consumer==========')
console.log(`Switch ${packet.id} is on`)
return resolve()
})
},
off: packet => {
return new Promise( async (resolve) => {
console.log('==============Pushed to Consumer==========')
console.log(`Switch ${packet.id} is off`)
return resolve()
})
}
}
}
let fio = new Base({sockets:'uc#c>n,us#s>n,tc#c>t,ts#s>t,mqtts#s>m,webs#s>w', tc:{port:8100}, ts:{port:8100}, webs:{ port:8090 }, mqtts:{ topics:['switch/#']}, id:'four-in-one'})
fio.s = socketfuncs
fio.c = clientfuncs
;
(async () => {
let res = await fio.init()
console.log('initialize errors',res)
console.log('waiting for packets')
let packet = {}
console.log('=============sending============')
packet = {cmd:'switch/on', id:'1'}
console.log('sending to socket uc',packet)
await fio.send('uc',packet)
})().catch(err => {
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
process.kill(process.pid, 'SIGTERM')
})