<template>
    <div>
        <button @click="connectSerial" :disabled="serialPort !== null">
            连接串口
        </button>
        <button @click="disconnectSerial" :disabled="serialPort === null">
            断开串口
        </button>
        <p v-if="serialPort !== null">已连接到: {{ serialPort.getInfo().usbVendorId }}:{{ serialPort.getInfo().usbProductId
            }}</p>
        <p v-else>未连接</p>
        <p v-if="errorMessage">{{ errorMessage }}</p>
        <pre>{{ receivedData }}</pre>
        <pre>{{ code }}</pre>
    </div>
</template>

<script>
import SCAN from "./scanCode"		// from后面为创建的SCAN类文件地址

export default {
    data() {
        return {
            serialPort: null,
            reader: null,
            writer: null,
            errorMessage: '',
            receivedData: '',
            code: ''
        };
    },
    async created() {
        this.scan = new SCAN(this, 200)
        // 重新注册scanCode事件，
        // this.$bus.$on('scanCode', this.handleCode)
        this.scan.start() //开启监听
    },
    beforeDestroy() {
        // this.$bus.$off('scanCode')
        this.scan.stop()
    },
    activated() {
        // 注销scanCode事件 
        // this.$bus.$off('scanCode')	
        // this.$bus.$on('scanCode', this.handleCode)	
        this.scan.start()
    },
    methods: {
        async connectSerial() {
            try {
                this.serialPort = await navigator.serial.requestPort();
                console.log('选择了串口:', this.serialPort);

                // 检查浏览器是否支持所需的波特率
                const options = { baudRate: 9600 };
                await this.serialPort.open(options);
                console.log('串口已打开');

                // 设置读取器
                this.reader = this.serialPort.readable.getReader();
                this.readLoop();

            } catch (error) {
                console.error('无法打开串口:', error);
                this.errorMessage = `无法打开串口: ${error.message}`;
                this.serialPort = null
            }
        },
        async readLoop() {
            while (true) {
                try {
                    const { value, done } = await this.reader.read();
                    if (done) {
                        console.log('读取完成');
                        break;
                    }
                    // 将接收到的字节数组转换为字符串
                    const decoder = new TextDecoder();
                    const decodedValue = decoder.decode(value, { stream: true });
                    this.receivedData += decodedValue;
                } catch (error) {
                    console.error('读取数据时出错:', error);
                    break;
                }
            }
            // 关闭读取器
            this.reader.releaseLock();
            this.reader = null;
        },
        disconnectSerial() {
            if (this.reader) {
                this.reader.cancel();
                this.reader.releaseLock();
                this.reader = null;
            }
            if (this.writer) {
                this.writer.close();
                this.writer = null;
            }
            if (this.serialPort) {
                this.serialPort.close();
                this.serialPort = null;
                console.log('串口已关闭');
            }
        },
        handleCode(code) {
            code = code.trim()
            if (!code) return
            this.code = code
            this.handleSearchCode()
        },
    },
};
</script>

<style scoped>
button {
    margin: 5px;
}

pre {
    background-color: #f4f4f4;
    padding: 10px;
    border-radius: 5px;
    overflow-y: auto;
    max-height: 200px;
}
</style>
