Created
April 8, 2019 14:05
-
-
Save freaktechnik/4e27ba9b8cf1f9c99d77a5255962b0e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Thing: WebThing, Property, Value, WebThingServer, MultipleThings, Action } = require("webthing"); | |
const express = require("express"); | |
const path = require("path"); | |
const internalIp = require("internal-ip"); | |
const uuid = require("uuid/v4"); | |
const activeThings = []; | |
internalIp.v4().then((ip) => { | |
console.log(ip); | |
const server = new WebThingServer(new MultipleThings(activeThings), 8080, ip, undefined, [ | |
{ | |
path: '/static', | |
handler: express.static(path.join(__dirname, 'static')) | |
}, | |
]); | |
const addSensor = (thing, sensor) => { | |
const desc = { | |
readonly: true, | |
type: 'number', | |
title: sensor.type | |
}; | |
thing.addProperty(new Property(thing, sensor.type, new Value(sensor.value), desc)); | |
}; | |
const updateSensor = (thing, sensor) => { | |
const prop = thing.findProperty(sensor.type); | |
if(prop) { | |
prop.setValue(sensor.value); | |
} | |
}; | |
server.app.ws('/comm/ws', (ws) => { | |
let thing; | |
ws.on('message', (rawMessage) => { | |
const message = JSON.parse(rawMessage); | |
if(message.type !== 'create' && !thing) { | |
ws.send({type: 'error', message: 'You must first initialize the thing.'}); | |
} | |
switch(message.type) { | |
case 'create': | |
thing = new WebThing(message.name, [], 'A web browser'); | |
for(const sensor of message.sensors) { | |
addSensor(thing, sensor); | |
} | |
if(message.can.notify) { | |
thing.addAvailableAction('notify', { | |
title: 'Notify', | |
input: { | |
type: 'string' | |
} | |
}, class NotifyAction extends Action { | |
constructor(thing, input) { | |
console.log("invoke notify"); | |
super(uuid(), thing, 'notify', input); | |
} | |
performAction() { | |
console.log("notify"); | |
ws.send({ | |
type: 'notify', | |
message: this.input | |
}); | |
return super.performAction(); | |
} | |
}); | |
} | |
if(message.can.vibrate) { | |
thing.addAvailableAction('vibrate', { | |
title: 'Vibrate' | |
}, class VibrateAction extends Action { | |
constructor(thing, input) { | |
super(uuid(), thing, 'vibrate', input); | |
} | |
performAction() { | |
ws.send({ | |
type: 'vibrate' | |
}); | |
return super.performAction(); | |
} | |
}); | |
} | |
activeThings.push(thing); | |
break; | |
case 'update': | |
for(const sensor of message.sensors) { | |
updateSensor(thing, sensor); | |
} | |
break; | |
} | |
}); | |
ws.on('close', () => { | |
activeThings[activeThings.findIndex((t) => t === thing)] = undefined; | |
}); | |
}); | |
server.start(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment