Skip to content

Instantly share code, notes, and snippets.

@blia
Created February 15, 2017 14:05
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 blia/629e2ff62588ad45fca97d8c220ec876 to your computer and use it in GitHub Desktop.
Save blia/629e2ff62588ad45fca97d8c220ec876 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bluetooth Web API</title>
</head>
<body>
<input class="range" id="r" value="255" max="255" type="range"/>
<input class="range" id="g" value="255" max="255" type="range"/>
<input class="range" id="b" value="255" max="255" type="range"/>
<input class="range" id="o" value="100" type="range"/>
<input type="color" class="color" value="#FFFFFF">
<button class="bt">connect</button>
<script>
const log = console.log.bind(console);
const [button] = document.getElementsByClassName('bt')
const [color] = document.getElementsByClassName('color')
const [r, g, b, o] = document.getElementsByClassName('range')
const toBuff = str => {
const buf = new ArrayBuffer(str.length)
const view = new Uint8Array(buf)
for (var i=0; i < str.length; i++) {
view[i] = str.charCodeAt(i)
}
return buf
}
const send = (lamp, r = 255, g = 255, b = 255, o = 100) => {
let command = `${r},${g},${b},${o}`
for (var j = command.length; j < 18; j++) {
command += ','
}
log(command)
lamp && lamp.writeValue(toBuff(command))
}
const change = lamp => evt => {
log(lamp, evt.target.value)
send(lamp, r.value, g.value, b.value, o.value)
}
button.addEventListener('pointerup', function(event) {
navigator.bluetooth.requestDevice({ filters: [{ services: [0xFFF0] }] })
.then(device => (log(device), device.gatt.connect())) //
.then(server => (log(server), server.getPrimaryService(0xFFF0)))
.then(service => (log(service), service.getCharacteristic(0xFFF1) ))
.then(ch => (log(ch), ch ))
.then(lamp => {
const bound = change(lamp)
r.addEventListener('change', bound)
g.addEventListener('change', bound)
b.addEventListener('change', bound)
o.addEventListener('change', bound)
color.addEventListener('change', evt => {
const [_, rx, gx, bx] = /#(.{2})(.{2})(.{2})/.exec(evt.target.value)
send(lamp, parseInt(rx, 16), parseInt(gx, 16), parseInt(bx, 16), o.value)
})
})
.catch(error => { log(error); });
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment