Skip to content

Commit dc8d85a

Browse files
committed
Improve direct serial connection error handling
1 parent 8eb1242 commit dc8d85a

File tree

2 files changed

+28
-12
lines changed

2 files changed

+28
-12
lines changed

electron/osrSerial.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,14 +93,14 @@ export class OsrSerialManager {
9393
}
9494
this.emitState()
9595

96-
const port = new SerialPortStream({
97-
binding: getSerialPortBinding(),
98-
path: targetPath,
99-
baudRate,
100-
autoOpen: false,
101-
})
102-
96+
let port: RuntimeSerialPort
10397
try {
98+
port = new SerialPortStream({
99+
binding: getSerialPortBinding(),
100+
path: targetPath,
101+
baudRate,
102+
autoOpen: false,
103+
})
104104
await openPort(port)
105105
} catch (error) {
106106
this.state = {
@@ -207,12 +207,13 @@ export class OsrSerialManager {
207207

208208
port.on('close', () => {
209209
if (port !== this.port) return
210+
const wasActive = this.state.connectionState === 'connected' || this.state.connectionState === 'connecting'
210211
this.port = null
211212
this.state = {
212213
connectionState: 'disconnected',
213214
connectedPortPath: null,
214215
baudRate,
215-
error: null,
216+
error: wasActive ? 'Serial port closed unexpectedly.' : null,
216217
}
217218
this.emitState()
218219
})

src/services/osrSerial.ts

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,25 @@ export class OsrSerialService {
7171
}
7272
this.onStateChange?.(this.state)
7373

74-
const nextState = await window.electronAPI.osrSerialConnect(portPath, baudRate)
75-
this.state = nextState
76-
this.onStateChange?.(nextState)
77-
return nextState.connectionState === 'connected'
74+
try {
75+
const nextState = await window.electronAPI.osrSerialConnect(portPath, baudRate)
76+
this.state = nextState
77+
this.onStateChange?.(nextState)
78+
return nextState.connectionState === 'connected'
79+
} catch (error) {
80+
const message = error instanceof Error && error.message
81+
? error.message
82+
: 'Failed to open serial port.'
83+
const nextState: OsrSerialState = {
84+
connectionState: 'error',
85+
connectedPortPath: null,
86+
baudRate,
87+
error: message,
88+
}
89+
this.state = nextState
90+
this.onStateChange?.(nextState)
91+
return false
92+
}
7893
}
7994

8095
async disconnect(): Promise<boolean> {

0 commit comments

Comments
 (0)