Example
Here is an example of how to use the Webserial API to interact with a Boardroid device.
src/webserial/boardroid.js
import {Boardroid} from '@danidoble/webserial';
const machine = new Boardroid();
machine.on('serial:disconnected', event => {
document.getElementById('disconnected').style.display = 'block';
});
machine.on('serial:connected', event => {
document.getElementById('disconnected').style.display = 'none';
document.getElementById('need-permission').style.display = 'none';
});
machine.on('serial:need-permission', event => {
document.getElementById('need-permission').style.display = 'block';
});
machine.on('serial:soft-reload', event => {
// reset your variables
});
machine.on('serial:unsupported', event => {
document.getElementById('unsupported').style.display = 'block';
});
function tryConnect(){
machine.connect().then(() => {
}).catch(console.error);
}
document.addEventListener("DOMContentLoaded", () => {
tryConnect();
document.getElementById('connect').addEventListener('click', tryConnect);
});
// i don't recommend expose machine object since it's a global object and has control over the machine
//window.machine = machine;
index.html
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example</title>
<script src="./src/webserial/boardroid.js" type="module"></script>
</head>
<body>
<button id="connect">Connect to serial</button>
<div id="need-permission" style="display: none">
Woooah! It seems that you need to give permission to access the serial port.
Please, click the button to try again.
</div>
<div id="disconnected">
The machine is disconnected. Please, check the connection.
</div>
<div id="unsupported">
This browser does not support the WebSerial API. Please, use a compatible browser.
</div>
</body>
</html>