@@ -9,22 +9,56 @@ export class DeviceService {
9
9
10
10
constructor ( ) { }
11
11
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
+
12
47
async requestPort ( ) : Promise < void > {
13
48
try {
14
49
const port = await navigator . serial . requestPort ( ) ;
15
50
this . port = port ;
16
51
17
52
// Check if the port is open by another application (or ourselves in another tab)
18
53
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');
23
57
}
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 ) ;
26
61
}
27
- this . transport = new Transport ( port ) ;
28
62
29
63
} catch ( err ) {
30
64
console . error ( '[requestPort]: Failed to get port:' , err ) ;
0 commit comments