Created
January 6, 2015 12:39
-
-
Save kurai021/ccec970bd8c4421bad26 to your computer and use it in GitHub Desktop.
Javascript Doorbell
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
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 | |
})); | |
} | |
}); |
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
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"); | |
} | |
} | |
}; |
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
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