Created
March 7, 2020 03:38
-
-
Save kyubuns/99e4d70508e7d30b2b9425ce4a98b89b to your computer and use it in GitHub Desktop.
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
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