Skip to main content

First Connection

Here you will be able to connect to the Boardroid device for the very first time.

Create a new file to add the code

First of all, create a new file in the src/webserial folder, and name it boardroid.js.

Linux/Mac

touch src/webserial/boardroid.js

Windows

echo "" > src/webserial/boardroid.js

Import the module in your code

If you are using the script tag, you can skip this step.

Module

src/webserial/boardroid.js
import {Boardroid} from '@danidoble/webserial';

New instance of the Boardroid class

Create a new instance of the Boardroid class (by default, is not needed pass any parameter to the constructor.)

src/webserial/boardroid.js
const machine = new Boardroid();

Make a function to connect

Now, let's connect to the device, since the connect method is asynchronous, we need to use await/async or promise to handle the connection. Or you can use the then method to handle the connection.

src/webserial/boardroid.js
function tryConnect() {
machine.connect().then(() => {
}).catch(console.error);
}
Warning

When the async function execute, never finish until the connection is closed, i.e: check this.

Why use tryConnect function?

Webserial API only allow to call request serial if the user interact with the page, so you need to call the function.

Note

Only request user interaction when you need a new serial device, if you previously selected a device, is possible to connect without user interaction.

Usually with a button, you can add the following code to the button:


<button onclick="tryConnect()">Connect</button>

FAQ

Here shows an example of what you should never do. The reason is explained in each example.

Never finish until the connection is closed

If you run the code below, the console never will print the message Connected, because the connection still open. this is because the connection is still open, and the async function never finish, unless the connection is closed or serial not connected.

But when you disconnect the serial or if you not select a device in the prompt, the console will print the message Connected. So please DON'T do this, it's just an example.

async function tryConnect() {
await machine.connect().catch(console.error);
console.log('Connected');
}