Skip to content

Commit aa64ef0

Browse files
dbg
1 parent 3c62a5a commit aa64ef0

File tree

1 file changed

+41
-7
lines changed

1 file changed

+41
-7
lines changed

kernel/src/services/DeviceService.ts

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,56 @@ export class DeviceService {
99

1010
constructor() {}
1111

12+
// Check if port is available (return true if available)
13+
// Don't run if we are already connected from within this tab
14+
async checkPort(): Promise<boolean> {
15+
if (!this.port) {
16+
console.log('[checkPort]: No port selected');
17+
return false;
18+
}
19+
20+
// Return false if the port is already open by us
21+
if (this.port.readable || this.port.writable) {
22+
console.log('[checkPort]: Port is already open by us...skipping check');
23+
return false;
24+
}
25+
26+
// Try opening and closing the port to check if it's available
27+
try {
28+
await this.port.open({ baudRate: 115200 });
29+
}
30+
catch (err) {
31+
if (err instanceof DOMException && err.name === 'InvalidStateError') {
32+
console.error('[checkPort]: Port is already open by another application');
33+
return false;
34+
}
35+
}
36+
finally {
37+
if (this.port) {
38+
await this.port.close();
39+
}
40+
}
41+
42+
// If we reach here, the port is available
43+
console.log('[checkPort]: Port is available');
44+
return true;
45+
}
46+
1247
async requestPort(): Promise<void> {
1348
try {
1449
const port = await navigator.serial.requestPort();
1550
this.port = port;
1651

1752
// Check if the port is open by another application (or ourselves in another tab)
1853

19-
// Perform a quick open and close of port to check if it's already open
20-
if (this.port.readable || this.port.writable) {
21-
console.log('[requestPort]: Port is already open, skipping request');
22-
return;
54+
if (!await this.checkPort()) {
55+
console.log('[requestPort]: Port is already open by another application');
56+
// throw new Error('Port is already open by another application');
2357
}
24-
else {
25-
console.log('[requestPort]: Port is not open, requesting port');
58+
else{
59+
console.log('[requestPort]: Port is available');
60+
this.transport = new Transport(port);
2661
}
27-
this.transport = new Transport(port);
2862

2963
} catch (err) {
3064
console.error('[requestPort]: Failed to get port:', err);

0 commit comments

Comments
 (0)