admin
2024-06-15 8cfe20288690f2ba46c804f41f39e8aa48c2dea0
提交 | 用户 | 时间
93feb8 1
2 export default class MySerialPort  {
3   constructor() {
4     this.state = {
5       portIndex: undefined,
6       ports: [],
7       isOpen: false,
8       writeType: 1,
9       readType: 1,
10       isScroll: true,
11       readValue: [],
12       status:false,
13       //port参数
14       baudRate: "9600",
15       dataBits: "8",
16       stopBits: "1",
17       parity: "none",
18       flowControl: "none",
19     };
20     this.keepReading=false;
21     this.getPorts = this.getPorts.bind(this);
22     this.handleRequestPort = this.handleRequestPort.bind(this);
23     this.handleChildrenChange = this.handleChildrenChange.bind(this);
24     this.readText = this.readText.bind(this);
25     this.writeText = this.writeText.bind(this);
26     this.handleClear = this.handleClear.bind(this);
27     this.a2hex = this.a2hex.bind(this);
28     this.hex2a = this.hex2a.bind(this);
29     this.hex2atostr=this.hex2atostr.bind(this);
30     this.reader={};
31     this.closed;
32   }
33
34   async getPorts() {
35     // 获取已授权的全部串口
36     let ports = await navigator.serial.getPorts();
37     this.setState({
38       ports,
39     });
40   }
41   async handleRequestPort() {
42     // 请求授权
43     try {
44       await navigator.serial.requestPort();
45       await this.getPorts();
46     } catch (e) {
47       this.$message.error(e.toString());
48     }
49   }
50   async openPort(portIndex, isOpen,callBack=null) {
51     // 打开串口
52     let port = this.state.ports[portIndex];
53     if (!isOpen) {
54       // 关闭串口
55       this.keepReading = false;
56       this.reader.cancel();
57       await this.closed;
58       this.handlePortOpen({
59         portIndex,
60         isOpen,
61       });
62     } else {
63       await port.open({
64         baudRate: this.state.baudRate,
65         dataBits: this.state.dataBits,
66         stopBits: this.state.stopBits,
67         parity: this.state.parity,
68         flowControl: this.state.flowControl,
69       });
70       this.handlePortOpen({
71         portIndex,
72         isOpen,
73       });
74       this.keepReading = true;
75       this.closed=this.readUntilClosed(portIndex,callBack);
76     }
77   }
78   async readUntilClosed(portIndex,callBack=null) {
79     let port = this.state.ports[portIndex];
80     while (port.readable && this.keepReading) {
81       this.reader = port.readable.getReader();
82       try {
83         let readCache=[]
84         while (true) {
85           const { value, done } = await this.reader.read();
86           if (done) {
87             break;
88           }
89           readCache.push(...value)
90           setTimeout(() => {
91             if(readCache.length>0){
92               this.readText(readCache);
93               callBack(readCache)
94               readCache=[]
95             }
96           }, 300);//串口缓存
97         }
98       } catch (error) {
99         this.$message.error(error.toString());
100       } finally {
101         this.reader.releaseLock();
102       }
103       await port.close();
104     }
105   }
106   handlePortOpen({ portIndex, isOpen }) {
107     // 处理打开串口
108     this.setState({
109       portIndex,
110       isOpen,
111     });
112   }
113   handleChildrenChange(type, value) {
114     this.setState({
115       [type]: value,
116     });
117   }
118   portWrite(value) {
119     return new Promise(async (resolve, reject) => {
120       if (!this.state.isOpen) {
121         this.$message.error("串口未打开");
122         reject();
123         return;
124       } else {
125         let port = this.state.ports[this.state.portIndex];
126         const writer = port.writable.getWriter();
127         await writer.write(new Uint8Array(value));
128         writer.releaseLock();
129         resolve(value);
130       }
131     });
132   }
133   readText(value) {
134     console.log(value, "读取");
135     let newValue = this.state.readValue.concat({
136       value,
137       type: 1,
138     });
139     this.setState({
140       readValue: newValue,
141     });
142   }
143   writeText(value) {
144     console.log(value, "写入");
145     this.portWrite(value).then((res) => {
146       let newValue = this.state.readValue.concat({
147         value: res,
148         type: 2,
149       });
150       this.setState({
151         readValue: newValue,
152       });
153     });
154   }
155   handleClear() {
156     this.setState({
157       readValue: [],
158     });
159   }
160   componentDidMount() {
161     this.getPorts();
162   }
163   handleState(status) {
164     this.setState({
165       status,
166     });
167   }
168   setState(obj){
169     Object.keys(this.state).forEach(key => {
170       if(obj[key]!=undefined){
171         this.state[key]=obj[key]
172       }
173     });
174   }
175   //字节转字符串
176   hex2atostr(arr) {
177     return String.fromCharCode.apply(String,arr);
178   }
179   hex2a(hexx) {
180     return String.fromCharCode(hexx);
181   }
182   //字符转16进制
183   a2hex(str) {
184     return str.charCodeAt(0);
185   }
186 }