Skip to content

Instantly share code, notes, and snippets.

@parasquid
Last active November 4, 2020 10:22
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 parasquid/cbf9153b41d7b77579ae0852643eab00 to your computer and use it in GitHub Desktop.
Save parasquid/cbf9153b41d7b77579ae0852643eab00 to your computer and use it in GitHub Desktop.
neolightbulb
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">
<style>
button { font-size: xx-large; }
</style>
<script>
let device = null;
let characteristic = null;
const connectAndSubscribe = async(e) => {
try {
const services = [];
const filters = [{services}]
services.push(0x181C); // user data service
// summon pairing ui
device = await navigator.bluetooth.requestDevice({filters});
// setup callback so we can clean up on disconnection
device.addEventListener('gattserverdisconnected', onDisconnected);
// connect to the lightbulb
const server = await device.gatt.connect();
const service = await server.getPrimaryService('user_data'); // user data service
characteristic = await service.getCharacteristic('string'); // string
// set the bulb's color to grey
characteristic.writeValue(new Uint8Array([0x88, 0x88, 0x88]));
} catch(err) {
console.error({err});
}
};
const disconnect = async(e) => {
if (device && device.gatt.connected) device.gatt.disconnect();
}
const onDisconnected = (event) => {
device = null;
characteristic = null;
console.log("disconnected!")
}
// helper function to convert #123456 to [0x12, 0x34, 0x56]
const hexToRgb = (rgb) => {
const r = parseInt(rgb.substring(1, 3), 16);
const g = parseInt(rgb.substring(3, 5), 16);
const b = parseInt(rgb.substring(5, 7), 16);
return [r, g, b];
};
// send color value to the light bulb
const handleColorChanged = (e) => {
if(!characteristic) return; // guard against null
const color = e.value;
const data = new Uint8Array(hexToRgb(color));
characteristic.writeValue(data);
};
</script>
</head>
<body>
<button onclick="connectAndSubscribe(this)">
Connect to device
</button>
<button onclick="disconnect(this)">
Disconnect from device
</button>
<div>
<input
type="color"
oninput="handleColorChanged(this)"
onchange="handleColorChanged(this)"
value="#888888"
/>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment