uci-websocket/examples/server.js

87 lines
3.3 KiB
JavaScript
Raw Normal View History

import Socket from '../src'
const ANONYMOUS = true
const PORT = 8090
function packetProcess (packet) {
const cmd = {
ack: function(packet){
return new Promise( async (resolve) => {
packet.ack = true
packet.sender= packet.sender || (packet._header ? packet._header.sender.name : 'unknown')
packet.msg=`this is acknlowdgement that ${packet.sender} ack was received`
this.push(packet) // push to all active socket servers
return resolve(packet) // this goes back to sender
})
},
switch:{
status: function(packet){
return new Promise( async (resolve) => {
packet.cmd='switch/status'
packet.state=this.switches[packet.id-1]
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
})
},
on: function(packet){
return new Promise( async (resolve) => {
packet.cmd='switch/status'
packet.state='on'
this.switches[packet.id-1] = '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 change - pushed on to all clients', id:packet.id}
return resolve(res) // this goes back to sender
})
},
off: function(packet){
return new Promise( async (resolve) => {
packet.cmd='switch/status'
packet.state='off'
this.switches[packet.id-1] = '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 change - pushed off to all clients'}
return resolve(res) // this goes back to sender
})
},
toggle: function(packet){
return new Promise( async (resolve) => {
this.switches[packet.id-1] = this.switches[packet.id-1]==='on' ? 'off' : 'on'
packet.state = this.switches[packet.id-1]
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:`status change - pushed toggled state of ${packet.state} to all clients`}
return resolve(res) // this goes back to sender
})
}
}
}
// console.log('this in packet processor',packet.cmd)
let cmdProps = packet.cmd.split('/')
let func = cmd[cmdProps[0]]
// console.log(func)
if (cmdProps[1]) func = func[cmdProps[1]]
// console.log(func)
if (typeof func === 'function') return func.call(this,packet)
else {
packet.error='no function for command'
return packet
}
}
// let test = new Test()
let test = new Socket({ port: PORT, allowAnonymous:ANONYMOUS })
test.switches = ['off','off','off','off'] // database to hold switch states
test.registerPacketProcessor(packetProcess)
;(async () => {
console.log(await test.create())
})().catch(err => {
console.error('FATAL: UNABLE TO START SYSTEM!\n', err)
})