-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSendAndRecieve.js
More file actions
104 lines (79 loc) · 2.29 KB
/
Copy pathSendAndRecieve.js
File metadata and controls
104 lines (79 loc) · 2.29 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
let port;
let reader;
let endLoop = 0;
getCon = async (filters) => {
if (port) {
console.log('Port has already been opened');
port.close();
}
try {
port = await navigator.serial.requestPort({ filters });
await port.open({ baudRate: 115200 });
console.log('Port opened successfully');
// TODO: Send data to Device using port.write()
} catch (error) {
console.log('Failed to open port:', error.message);
if (port) {
port.close();
port = null;
}
}
return port;
}
sendSerialData = async (port, data) => {
const writer = port.writable.getWriter();
await writer.write(data);
writer.releaseLock();
};
sendACommand = async (command) => {
endLoop = 0;
if (!port) {
console.log('Port has not been initialized');
return;
}
// const version_in = encoder.encode(command);
try {
reader = port.readable.getReader();
try {
while (endLoop === 0) {
try {
await this.sendSerialData(port, command)
//console.log('Data sent:', version_in);
} catch (error) {
console.log("Error occured While sending data")
}
await new Promise(r => setTimeout(r, 1000));
const { value, done } = await reader.read();
if (new TextDecoder().decode(value) === null) {
console.log("Device closed or there is comm error")
await port.close()
}
if (done) {
console.log("log done")
reader.cancel();
break;
}
if (value) {
console.log("send command function: " + new TextDecoder().decode(value));
endLoop = 1
console.log('sendACommand finished');
}
reader.releaseLock();
return new TextDecoder().decode(value);
}
} catch (error) {
console.log("There is a error", error + " " + error.message)
}
finally {
// Allow the serial port to be closed later.
if (reader) {
reader.releaseLock();
}
}
}
catch (error) {
console.log("Serial reader already locked")
//if the error occurs release the locks to send data again
//await port.close()
}
}