Skip to content

Instantly share code, notes, and snippets.

@blia
Created May 10, 2017 14:42
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/2f14703d302282164d73941f2afe4520 to your computer and use it in GitHub Desktop.
Save blia/2f14703d302282164d73941f2afe4520 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>
<button class="bt">BT</button>
<script>
let lamp = null
const log = console.log.bind(console);
const [button] = document.getElementsByClassName('bt')
const toBuff = str => {
const buf = new ArrayBuffer(str.length)
const view = new Uint8Array(buf)
for (var i=0; i < str.length; i++) {
bufView[i] = str.charCodeAt(i)
}
return buf
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length);
var bufView = new Uint8Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
const handleNotifications = evt => {
let v = event.target.value;
let w = Math.round((v.getUint16(1, true) / 100) / 2)
log(w.toString());
log(lamp)
let command = `255,255,255,${w}`
for (var j = command.length; j < 18; j++) {
command += ','
}
log(command)
lamp && lamp.writeValue(str2ab(command))
}
button.addEventListener('pointerup', function(event) {
log('called')
navigator.bluetooth.requestDevice({ filters: [{ services: ['weight_scale'] }] })
.then(device => (log(device), device.gatt.connect()))
.then(server => (log(server), server.getPrimaryService(0x181d)))
.then(service => (log(service), service.getCharacteristic(0x2a9d) ))
.then(ch => (log(ch), ch ))
.then(characteristic => {
myCharacteristic = characteristic;
return myCharacteristic.startNotifications().then(_ => {
log('> Notifications started');
myCharacteristic.addEventListener('characteristicvaluechanged',
handleNotifications);
});
})
.catch(error => { log(error); });
});
</script>
<button class="bt2">lamp</button>
<script>
const [button2] = document.getElementsByClassName('bt2')
button2.addEventListener('pointerup', function(event) {
log('called', 0xFFF0)
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(characteristic => {
lamp = characteristic
})
.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