uci-base/examples/web.js

62 lines
1.6 KiB
JavaScript

import Base from '../src/base'
// const USOCKET = __dirname + '/sample.sock'
let wss = new Base({id:'websocket', useRootNS: true})
wss.switch = {
on: function(packet){
return new Promise( async (resolve) => {
console.log(`turning switch on for id ${packet.id||packet.payload.id}`)
// call switch on here
let res = {}
res.log = `turning switch on for id ${packet.id||packet.payload.id}`
res.cmd='switch/status'
res.status='on'
res.id = packet.id
return resolve(res)
})
},
off: function(packet){
return new Promise( async (resolve) => {
console.log(`turning switch off for id ${packet.id||packet.data}`)
// call switch on here
let res = {}
res.cmd='switch/status'
res.status='off'
res.id = packet.id
return resolve(res)
})
},
toggle: function(packet){
return new Promise( async (resolve) => {
console.log(`toggling switch for id ${packet.id||packet.data}`)
// call switch on here
let res = {}
res.cmd='switch/status'
res.status= (packet.status === 'on')?'off':'on'
res.id = packet.id
console.log('broadcast',res)
this.push(res)
// return only acknowledge to sender, packet went as push
res = { cmd:'ack'}
return resolve(res)
})
}
}
;
(async () => {
await wss.init()
await wss.addSocket('web','s','w')
wss.push({server:'started'})
await wss.addSocket('mqs','s','m')
wss.socket.mqs.subscribe(['switch/on','switch/off','switch/toggle'])
})().catch(err => {
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
process.kill(process.pid, 'SIGTERM')
})