<template>
<div class="home">
<div>
<input type="text" v-model="inputData" placeholder="输入要发送的数据" />
<button @click="sendData">发送</button>
</div>
<div>
<textarea v-model="receivedData" readonly></textarea>
</div>
<button @click="initSerial">Initialize Serial Connection</button>
</div>
</template>
<script>
export default {
data() {
return {
port: null,
inputData: "", // 用于存储输入的数据
receivedData: "", // 用于存储接收到的数据
};
},
created() {
},
methods: {
async initSerial() {
try {
this.port = await navigator.serial.requestPort();
console.log("port: ", this.port);
await this.port.open({ baudRate: 115200 });
this.readData();
// 监听设备连接
navigator.serial.addEventListener("connect", (event) => {
console.log("设备已连接");
});
// 监听设备断开
navigator.serial.addEventListener("disconnect", (event) => {
console.log("设备已断开");
});
} catch (error) {
console.error("Serial connection error:", error);
}
},
async readData() {
const decoder = new TextDecoder("utf-8"); // 指定字符编码方式
const reader = this.port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
const decodedString = decoder.decode(value); // 将字节数组解码为字符串
// 处理接收到的数据
console.log("Received data:", decodedString);
this.receivedData += decodedString;
}
} catch (error) {
console.error("Serial read error:", error);
} finally {
reader.releaseLock();
}
},
async sendData() {
console.log("data: ", this.inputData);
const writer = this.port.writable.getWriter();
const encoder = new TextEncoder();
const dataArray = encoder.encode(this.inputData);
try {
await writer.write(dataArray);
writer.releaseLock();
} catch (error) {
console.error("Serial write error:", error);
}
this.inputData = "";
},
async disconnectSerialPort(port) {
try {
await port.close(); // 关闭串口连接
console.log("Serial port disconnected.");
} catch (error) {
console.error("Error disconnecting serial port:", error);
}
},
},
};
</script>
Web Serial API:Web Serial API
WebUSB API:WebUSB API - Web APIs | MDN
Serial Terminal : https://googlechromelabs.github.io/serial-terminal/
相关文章:
什么,网页也能直接与硬件通信?Web Serial API!|8月更文挑战 什么,网页也能直接与硬件通信?Web Serial API!|8月更文挑战 - 掘金
【10. 连接硬件设备至 web 应用】 10. 连接硬件设备至 web 应用_哔哩哔哩_bilibili
使用 Web Serial API 在浏览器上实现基于 WEB 的串口通信 GitHub - WangTiantian139/serial-logger-and-plotter文章来源:https://www.toymoban.com/news/detail-683718.html
跨越嵌入式到云端的新型容器:WebAssembly Micro Runtime 跨越嵌入式到云端的新型容器:WebAssembly Micro Runtime_开源_王鑫_InfoQ精选文章文章来源地址https://www.toymoban.com/news/detail-683718.html
到了这里,关于[VUE] Web Serial API的简单示例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!