Skip to content

Instantly share code, notes, and snippets.

@hputzek
Created February 24, 2020 22:17
Show Gist options
  • Save hputzek/8c70d469e809f29937605d4dd17e8b02 to your computer and use it in GitHub Desktop.
Save hputzek/8c70d469e809f29937605d4dd17e8b02 to your computer and use it in GitHub Desktop.
webserial connect
<!DOCTYPE html>
<html lang="en">
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<button id="portSelect" type="button">Select a port</button>
<div id="connectionInfoDisplay">Connection Information</div>
<button id="disconnectButton" type="button">Disconnect</button>
<script>
let serialSettings = {
bitrate: 115200,
dataBits: "eight",
parityBit: "no",
stopBits: "one",
ctsFlowControl: false
};
function start() {
var portSelect = document.getElementById("portSelect");
portSelect.addEventListener("click", async e => {
e.preventDefault();
console.log("Selecting port");
// Request a port/device from user
const port = await navigator.serial.requestPort();
// Open and begin reading.
await port.open({
baudrate: 115200
});
const reader = port.in.getReader();
while (true) {
const { done, data } = await reader.read();
if (done) break;
console.log(data);
}
});
document.getElementById("disconnectButton").addEventListener("click", e => {
e.preventDefault();
console.log("Clicked disconnect");
});
navigator.serial.getPorts(function(devices) {
buildPortSelect(devices);
openSelectedPort();
});
}
//Leaving out buildPortSelect for brevity
function openSelectedPort() {
let portSelect = document.getElementById("portSelect");
let selectedPort = portSelect.options[portSelect.selectedIndex].value;
let connectionInfoDisplay = document.getElementById("connectionInfoDisplay");
for (let i = 0; i < state.eligiblePorts.length; i++) {
if (selectedPort == state.eligiblePorts[i].path) {
connectionInfoDisplay.innerText = "Connected to: " + selectedPort;
navigator.serial.connect(selectedPort, serialSettings, onConnect);
break;
}
}
}
const onConnect = function(connectionInfo) {
// The serial port has been opened. Save its id to use later.
connectionId = connectionInfo.connectionId;
};
start();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment