前言

记上一篇文章[vue2和electron构建应用]

  1. background.js 添加如下代码
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 mainWindow.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
        // console.log(event,'<---evnet')
        console.log(portList,'<----portList')
        // console.log(webContents,'<---webContents')
        // console.log(callback,'<-----callback')
        // Add listeners to handle ports being added or removed before the callback for `select-serial-port`
        // is called.
        // 串口设备插入监听
        mainWindow.webContents.session.on('serial-port-added', (event, port) => {
          console.log('serial-port-added FIRED WITH', port)
          // Optionally update portList to add the new port
        })
       
        // 串口设备拔出监听
        mainWindow.webContents.session.on('serial-port-removed', (event, port) => {
          console.log('serial-port-removed FIRED WITH', port)
          // Optionally update portList to remove the port
        })
    
        event.preventDefault()
        // 监听到设备进行设备选择
        if (portList && portList.length > 0) {
          callback(portList[0].portId)
        } else {
          // eslint-disable-next-line standard/no-callback-literal
          callback('') // Could not find any matching devices
        }
      })
    
      mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
        if (permission === 'serial' && details.securityOrigin === 'file:///') {
          return true
        }
    
        return false
      })
    
      mainWindow.webContents.session.setDevicePermissionHandler((details) => {
        if (details.deviceType === 'serial' && details.origin === 'file://') {
          return true
        }
    
        return false
      })
  1. 在 vue 文件里添加如下代码
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<template>
    <div>
        <div class="btn" @click="test">串口测试</div>
        <div id="device-name"></div>
    </div>
</template>

<script>
export default {
    methods: {

        async test() {
            if ("serial" in navigator) {
                console.log('浏览器支持串口通信')
            } else {
                return
            }
            try {
                // 请求串口访问权限
                const port = await navigator.serial.requestPort();
                console.log(port,'<---')

                // 打开串口
                await port.open({
                    dataBits: 8, // 数据位
                    stopBits: 1, // 停止位
                    parity: "none", // 奇偶校验
                    baudRate: 9600, // 波特率
                });

                // 创建一个读取器对象
                const reader = port.readable.getReader();

                // 读取串口数据
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;
                    console.log('收到数据:' + new TextDecoder().decode(value));
                }

                // 发送数据到串口
                const writer = port.writable.getWriter();
                await writer.write(new TextEncoder().encode('Hello World!'));
                await writer.close();
            } catch (ex) {
                if (ex.name === 'NotFoundError') {
                    document.getElementById('device-name').innerHTML = 'Device NOT found'
                } else {
                    document.getElementById('device-name').innerHTML = ex
                }
            }
        },

    }
}
</script>
<style scoped>
.btn {
    width: 120px;
    height: 60px;
    border-radius: 20px;
    text-align: center;
    line-height: 60px;
    cursor: pointer;
}
</style>
  1. vue 使用msgpack 进行把数据处理为二进制数据
1
npm install msgpack5 --save
  1. 引入 msgpack5
1
import msgpack from 'msgpack5';