Skip to content

Instantly share code, notes, and snippets.

@tanepiper
Last active January 29, 2021 14:05
Show Gist options
  • Save tanepiper/8255054d593d4fddaf257f61461328c2 to your computer and use it in GitHub Desktop.
Save tanepiper/8255054d593d4fddaf257f61461328c2 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head></head>
<body>
<button class="start">Start Serial Request</button>
<button class="send">Send Signal</button>
</body>
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
<script type="module">
const { from, Observable, fromEvent } = rxjs;
const { tap, switchMap, mapTo } = rxjs.operators;
function fromWebSerial(port, baudRate = 9600, signal) {
return new Observable((subscriber) => {
port.open({ baudRate }).then(async () => {
const encoder = new TextEncoderStream();
const outputDone = encoder.readable.pipeTo(port.writable);
const outputStream = encoder.writable;
const writer = outputStream.getWriter();
signal.pipe(
switchMap((value) => {
return writer.write(value)
})
).subscribe()
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// |reader| has been canceled.
break;
}
subscriber.next(value);
// Do something with |value|...
}
} catch (error) {
subscriber.error(error)
} finally {
reader.releaseLock();
!subscriber.closed && subscriber.complete();
}
}
});
});
}
// Starter
const startButton = document.querySelector(".start");
const sendButton = document.querySelector(".send");
const signal$ = fromEvent(sendButton, 'click').pipe(mapTo('Toot'))
startButton.addEventListener("click", async (event) => {
try {
const port = await navigator.serial.requestPort();
fromWebSerial(port, 9600, signal$).pipe(tap(console.log)).subscribe();
} catch (e) {
// The prompt has been dismissed without selecting a device.
}
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment