Skip to content

Instantly share code, notes, and snippets.

@kurai021
Created January 6, 2015 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurai021/ccec970bd8c4421bad26 to your computer and use it in GitHub Desktop.
Save kurai021/ccec970bd8c4421bad26 to your computer and use it in GitHub Desktop.
Javascript Doorbell
function getUuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
var deviceId = getUuid();
var wsOpen = false;
var ws;
function connect() {
ws = new WebSocket('ws://192.168.2.100:8322');
ws.onopen = () => {
wsOpen = true;
};
ws.onclose = () => {
wsOpen = false;
connect();
};
}
connect();
window.addEventListener('deviceproximity', function(e) {
if (wsOpen) {
ws.send(JSON.stringify({
type: 'deviceproximity',
deviceId: deviceId,
value: e.value
}));
}
});
var devices = {};
var audio = new Audio('http://www.soundjay.com/door/sounds/doorbell-6.mp3');
var ws = new WebSocket('ws://' + location.hostname + ':8322');
ws.onmessage = function(e){
var data = e.data;
if (typeof data === "string") data = JSON.parse(data);
if(data & data.type === "deviceproximity"){
if (!devices[data.deviceId]){
audio.mozAudioChannelType = 'normal';
audio.volume.normal = 15;
}
if (data.value <= 5){
audio.play();
console.log("activado");
}
}
};
var connect = require("connect");
var serveStatic = require("serve-static");
connect()
.use(serveStatic(__dirname))
.listen(8321, '0.0.0.0');
var ws = require("nodejs-websocket");
var server = ws.createServer(function(conn){
console.log("new connection");
conn.on("text", function(str){
console.log("Received " + str);
broadcast(str);
});
conn.on("close", function(code, reason){
console.log("Connection closed");
});
}).listen(8322, "0.0.0.0");
function broadcast(msg){
server.connections.forEach(function(conn){
conn.sendText(msg);
});
}
console.log('listening on port ', 8321, 8322);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment