Skip to content

Instantly share code, notes, and snippets.

@lupomontero
Last active May 24, 2019 19:11
Show Gist options
  • Save lupomontero/fdc8a9290126540dd83ee26c6addef28 to your computer and use it in GitHub Desktop.
Save lupomontero/fdc8a9290126540dd83ee26c6addef28 to your computer and use it in GitHub Desktop.
Archivos usados en demo de charla sobre webthings... http://tiny.cc/uui86y
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Light Switch</title>
</head>
<body>
<button type="button">Toggle</button>
<script>
const ws = new WebSocket('ws://127.0.0.1:8888/');
const btn = document.getElementsByTagName('button')[0];
let state = false;
ws.addEventListener('message', (e) => {
const parsed = JSON.parse(e.data);
state = !!parsed.data.on;
document.body.style.backgroundColor = (state) ? 'yellow' : 'white';
});
btn.addEventListener('click', () => {
ws.send(JSON.stringify({
messageType: 'setProperty',
data: { on: !state },
}));
});
</script>
</body>
</html>
const { Board, Button, Led } = require('johnny-five');
const {
Property,
SingleThing,
Thing,
Value,
WebThingServer,
} = require('webthing');
const makeThing = (led) => {
const light = new Thing(
'Light switch',
['Light'],
'Nodebot light switch',
);
const onOffValue = new Value(false, v => (v ? led.on() : led.off()));
const onOffProperty = new Property(light, 'on', onOffValue, {
'@type': 'OnOffProperty',
title: 'On/Off',
type: 'boolean',
description: 'Whether the light is turned on',
});
light.addProperty(onOffProperty);
return light;
};
const runWebThingServer = (thing) => {
const server = new WebThingServer(new SingleThing(thing), 8888);
process.on('SIGINT', () => (
server.stop()
.then(() => process.exit())
.catch(() => process.exit())
));
server.start()
.catch(console.error);
};
Board().on('ready', () => {
const btn = new Button({ pin: 5, invert: true });
const led = new Led(9);
const thing = makeThing(led);
btn.on('release', () => {
led.toggle();
thing.properties.on.value.notifyOfExternalUpdate(led.value);
});
runWebThingServer(thing);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment