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

80 lines
2.9 KiB
JavaScript
Raw Normal View History

import Base from '../src/base'
// const USOCKET = __dirname + '/sample.sock'
const socketfuncs = {
switch: {
on: function(packet){
return new Promise( async (resolve) => {
packet.cmd='switch/status'
packet.status='on'
packet.sender= packet.sender || (packet._header ? packet._header.sender.name : 'unknown')
this.push(packet) // push to all active socket servers
let res = { response:'status pushed on to all clients'}
return resolve(res) // this goes back to sender
})
},
off: function(packet){
return new Promise( async (resolve) => {
packet.cmd='switch/status'
packet.status='off'
packet.sender= packet.sender || (packet._header ? packet._header.sender.name : 'unknown')
this.push(packet) // push to all active socket servers
let res = { response:'status pushed off to all clients'}
return resolve(res) // this goes back to sender
})
},
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 ='switch/status'
packet.sender= packet.sender || (packet._header ? packet._header.sender.name : 'unknown')
this.push(packet) // push to all active socket servers
let res = { response:`command ${packet.cmd} with id:${packet.id} pushed to all consumers(clients)`}
return resolve(res) // this goes back to sender
})
}
}
}
function status(state,consumer) {
return (packet) => {
return new Promise( async (resolve) => {
// console.log('complete packet', packet, consumer)
console.log(`Switch ${packet.id} is ${packet.status}, sent by ${packet.sender || packet.data.sender} to ${consumer}`)
return resolve()
})
}
}
let fio = new Base({sockets:'uc#c>n,us#s>n,tc#c>t,ts#s>t', tc:{port:8100}, ts:{port:8100}, webs:{ port:8090 }, mqtts:{ topics:['switch/on','switch/off','switch/toggle']}, mqtt:{ topics:['switch/status']}})
fio.s = socketfuncs
fio.c = { reply: () => {return Promise.resolve()} }
fio.cn = {switch:{status:status('on','named')}}
fio.ct = {switch:{status:status('on','tcp')}}
fio.cm = {switch:{status:status('on','mqtt')}}
;
(async () => {
await fio.addSocket('mqtt','s','m',{ topics:['switch/on','switch/off','switch/toggle']})
let res = await fio.init()
console.log('initialize errors',res)
console.log('waiting for packets')
let packet = {}
packet = {cmd:'switch/toggle', id:'1'}
console.log('=====sending to socket uc======',packet)
console.log('this should get pushed to all listening')
console.log('response back to uc: ',(await fio.send('uc',packet)).response)
})().catch(err => {
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
process.kill(process.pid, 'SIGTERM')
})