Skip to content

Instantly share code, notes, and snippets.

@kyubuns
Created March 7, 2020 03:38
Show Gist options
  • Save kyubuns/99e4d70508e7d30b2b9425ce4a98b89b to your computer and use it in GitHub Desktop.
Save kyubuns/99e4d70508e7d30b2b9425ce4a98b89b to your computer and use it in GitHub Desktop.
class CharacteristicWrapper {
constructor(rawCharacteristic) {
this.rawCharacteristic = rawCharacteristic
this.uuid = rawCharacteristic.uuid.replace(/-/g, "")
this.properties = ["notify"]
}
toBuffer(ab) {
var buf = toio.scanner.Buffer.alloc(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buf.length; ++i) {
buf[i] = view[i];
}
return buf;
}
on(id, e) {
if (id == 'data') {
this.rawCharacteristic.addEventListener('characteristicvaluechanged', message => {
e(this.toBuffer(message.target.value.buffer))
})
}
else {
console.log(`unknown event ${id}`)
}
}
subscribe(e) {
if (e != undefined) {
this.rawCharacteristic.startNotifications().then(_ => {
e()
})
} else {
this.rawCharacteristic.startNotifications()
}
}
unsubscribe(e) {
if (e != undefined) {
this.rawCharacteristic.stopNotifications().then(_ => {
e()
})
} else {
this.rawCharacteristic.stopNotifications()
}
}
write(data) {
this.rawCharacteristic.writeValue(data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment