Skip to content

Commit e1d08ae

Browse files
committed
Improve events
1 parent 8c10a46 commit e1d08ae

File tree

9 files changed

+502
-27
lines changed

9 files changed

+502
-27
lines changed

src/js/msp/MSPHelper.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1779,13 +1779,17 @@ MspHelper.prototype.process_data = function (dataHandler) {
17791779

17801780
// remove object from array
17811781
dataHandler.callbacks.splice(i, 1);
1782-
if (!crcError) {
1783-
// fire callback
1784-
if (callback) {
1782+
// Always invoke callback and pass crcError flag. Previously callbacks were skipped
1783+
// when crcError was true; tests and callers expect the callback to still be notified.
1784+
if (callback) {
1785+
try {
17851786
callback({ command: code, data: data, length: data.byteLength, crcError: crcError });
1787+
} catch (e) {
1788+
console.error(`callback for code ${code} threw:`, e);
17861789
}
1787-
} else {
1788-
console.warn(`code: ${code} - crc failed. No callback`);
1790+
}
1791+
if (crcError) {
1792+
console.warn(`code: ${code} - callback invoked despite crc failure`);
17891793
}
17901794
}
17911795
}

src/js/protocols/WebSerial.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,67 @@ class WebSerial extends EventTarget {
220220
}
221221
} catch (error) {
222222
console.error(`${logHead} Error connecting:`, error);
223+
224+
// If the port is already open (InvalidStateError) we can attempt to
225+
// recover by attaching to the already-open port. Some browser
226+
// implementations throw when open() is called concurrently but the
227+
// underlying port is already usable. Try to initialize reader/writer
228+
// and proceed as a successful connection.
229+
if (
230+
error &&
231+
(error.name === "InvalidStateError" ||
232+
(typeof error.message === "string" && error.message.includes("already open")))
233+
) {
234+
try {
235+
const connectionInfo = this.port?.getInfo ? this.port.getInfo() : null;
236+
this.connectionInfo = connectionInfo;
237+
this.isNeedBatchWrite = this.checkIsNeedBatchWrite();
238+
239+
// Attempt to obtain writer/reader if available
240+
try {
241+
if (this.port?.writable && !this.writer) {
242+
this.writer = this.port.writable.getWriter();
243+
}
244+
} catch (e) {
245+
console.warn(`${logHead} Could not get writer from already-open port:`, e);
246+
}
247+
248+
try {
249+
if (this.port?.readable && !this.reader) {
250+
this.reader = this.port.readable.getReader();
251+
}
252+
} catch (e) {
253+
console.warn(`${logHead} Could not get reader from already-open port:`, e);
254+
}
255+
256+
if (connectionInfo) {
257+
this.connected = true;
258+
this.connectionId = path;
259+
this.bitrate = options.baudRate;
260+
this.bytesReceived = 0;
261+
this.bytesSent = 0;
262+
this.failed = 0;
263+
this.openRequested = false;
264+
265+
this.port.addEventListener("disconnect", this.handleDisconnect);
266+
this.addEventListener("receive", this.handleReceiveBytes);
267+
268+
console.log(`${logHead} Recovered already-open serial port, ID: ${this.connectionId}`);
269+
this.dispatchEvent(new CustomEvent("connect", { detail: connectionInfo }));
270+
271+
// Start read loop if not already running
272+
if (!this.reading) {
273+
this.reading = true;
274+
this.readLoop();
275+
}
276+
277+
return true;
278+
}
279+
} catch (e) {
280+
console.warn(`${logHead} Failed to recover already-open port:`, e);
281+
}
282+
}
283+
223284
this.openRequested = false;
224285
this.dispatchEvent(new CustomEvent("connect", { detail: false }));
225286
return false;

src/js/serial.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,71 @@ class Serial extends EventTarget {
191191
return this._protocol.connect(path, options, callback);
192192
}
193193

194+
// If a connect/open is already in progress on the protocol, wait for it
195+
// to finish instead of returning immediately. This avoids race
196+
// conditions while allowing callers to await connection completion.
197+
if (this._protocol.openRequested) {
198+
console.warn(`${this.logHead} Protocol connection already in progress, waiting for completion`);
199+
// Wait for either a 'connect' or 'disconnect' event dispatched
200+
// at the Serial level, then re-evaluate state.
201+
const waited = await new Promise((resolve) => {
202+
const onConnect = () => {
203+
cleanup();
204+
resolve(true);
205+
};
206+
const onDisconnect = () => {
207+
cleanup();
208+
resolve(false);
209+
};
210+
const cleanup = () => {
211+
try {
212+
this.removeEventListener("connect", onConnect);
213+
this.removeEventListener("disconnect", onDisconnect);
214+
} catch {
215+
/* ignore */
216+
}
217+
};
218+
this.addEventListener("connect", onConnect, { once: true });
219+
const timer = setTimeout(() => {
220+
cleanup();
221+
resolve(null);
222+
}, 5000);
223+
const wrap =
224+
(fn) =>
225+
(...args) => {
226+
clearTimeout(timer);
227+
fn(...args);
228+
};
229+
this.addEventListener("connect", wrap(onConnect), { once: true });
230+
this.addEventListener("disconnect", wrap(onDisconnect), { once: true });
231+
});
232+
233+
// Optional: if timed out, re-evaluate state to proceed safely
234+
if (waited === null && this._protocol.connected && this._protocol.getConnectedPort?.()?.path === path) {
235+
return true;
236+
}
237+
238+
// After the in-flight attempt finished, if we're already connected to
239+
// the requested port, return success. Otherwise, fall-through and
240+
// attempt to connect now that the protocol is no longer in the
241+
// 'openRequested' state.
242+
const connectedPort = this._protocol.getConnectedPort?.();
243+
if (this._protocol.connected && connectedPort?.path === path) {
244+
console.log(`${this.logHead} Already connected to the requested port after waiting`);
245+
return true;
246+
}
247+
248+
// If connected to a different port after waiting, disconnect first
249+
if (this._protocol.connected && connectedPort?.path !== path) {
250+
console.log(`${this.logHead} Connected to different port after waiting, disconnecting first`);
251+
const success = await this.disconnect();
252+
if (!success) {
253+
console.error(`${this.logHead} Failed to disconnect before reconnecting`);
254+
return false;
255+
}
256+
}
257+
}
258+
194259
console.log(`${this.logHead} Connecting to port:`, path, "with options:", options);
195260
return this._protocol.connect(path, options, callback);
196261
}

src/js/tabs/firmware_flasher.js

Lines changed: 124 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ import { EventBus } from "../../components/eventBus";
2121
import { ispConnected } from "../utils/connection.js";
2222
import FC from "../fc";
2323

24+
const PORT_CHANGE_DEBOUNCE_MS = 500;
25+
const AUTO_DETECT_DELAY_MS = 1000;
26+
2427
const firmware_flasher = {
2528
targets: null,
2629
buildApi: new BuildApi(),
@@ -40,6 +43,88 @@ const firmware_flasher = {
4043
// Properties to preserve firmware state during flashing
4144
preFlashingMessage: null,
4245
preFlashingMessageType: null,
46+
// Single debounce timer shared across instances
47+
portChangeTimer: null,
48+
logHead: "[FIRMWARE_FLASHER]",
49+
// Event handlers to allow removal on tab change
50+
detectedUsbDevice: function (device) {
51+
const isFlashOnConnect = $("input.flash_on_connect").is(":checked");
52+
53+
console.log(`${firmware_flasher.logHead} Detected USB device:`, device);
54+
console.log(
55+
`${firmware_flasher.logHead} Reboot mode: %s, flash on connect`,
56+
STM32.rebootMode,
57+
isFlashOnConnect,
58+
);
59+
60+
// If another operation is in progress, ignore port events (unless we're resuming from a reboot)
61+
if (GUI.connect_lock && !STM32.rebootMode) {
62+
console.log(`${firmware_flasher.logHead} Port event ignored due to active operation (connect_lock)`);
63+
return;
64+
}
65+
66+
// Proceed if we're resuming a reboot sequence or if flash-on-connect is enabled and no operation is active
67+
if (STM32.rebootMode || isFlashOnConnect) {
68+
const wasReboot = !!STM32.rebootMode;
69+
STM32.rebootMode = 0;
70+
// Only clear the global connect lock when we are resuming from a reboot
71+
// so we don't accidentally interrupt another active operation.
72+
if (wasReboot) {
73+
GUI.connect_lock = false;
74+
}
75+
firmware_flasher.startFlashing?.();
76+
}
77+
},
78+
detectedSerialDevice: function () {
79+
// AutoDetect.verifyBoard();
80+
},
81+
onPortChange: function (port) {
82+
// Clear any pending debounce timer so rapid port events don't re-enter the handler.
83+
if (firmware_flasher.portChangeTimer) {
84+
clearTimeout(firmware_flasher.portChangeTimer);
85+
firmware_flasher.portChangeTimer = null;
86+
}
87+
88+
console.log(`${firmware_flasher.logHead} Port changed to:`, port);
89+
90+
if (GUI.connect_lock) {
91+
console.log(`${firmware_flasher.logHead} Port change ignored during active operation (connect_lock set)`);
92+
return;
93+
}
94+
95+
// Auto-detect board when port changes and we're on firmware flasher tab
96+
if (port && port !== "0" && $("input.flash_on_connect").is(":checked") === false && !STM32.rebootMode) {
97+
console.log(`${firmware_flasher.logHead} Auto-detecting board for port change (debounced)`);
98+
99+
// Debounced verification: re-check connect lock when the timeout fires
100+
firmware_flasher.portChangeTimer = setTimeout(() => {
101+
firmware_flasher.portChangeTimer = null;
102+
if (GUI.connect_lock) {
103+
console.log(`${firmware_flasher.logHead} Skipping auto-detect due to active operation at timeout`);
104+
return;
105+
}
106+
AutoDetect.verifyBoard();
107+
}, PORT_CHANGE_DEBOUNCE_MS);
108+
} else if (!port || port === "0") {
109+
if (!GUI.connect_lock) {
110+
console.log(`${firmware_flasher.logHead} Clearing board selection - no port selected`);
111+
$('select[name="board"]').val("0").trigger("change");
112+
} else {
113+
console.log(`${firmware_flasher.logHead} Not clearing board selection because operation in progress`);
114+
}
115+
}
116+
},
117+
onDeviceRemoved: function (devicePath) {
118+
console.log(`${firmware_flasher.logHead} Device removed:`, devicePath);
119+
120+
// Avoid clearing when removal is expected during flashing/reboot
121+
if (GUI.connect_lock || STM32.rebootMode) {
122+
return;
123+
}
124+
125+
$('select[name="board"]').val("0").trigger("change");
126+
firmware_flasher.clearBufferedFirmware?.();
127+
},
43128
};
44129

45130
firmware_flasher.initialize = async function (callback) {
@@ -60,8 +145,6 @@ firmware_flasher.initialize = async function (callback) {
60145
self.intel_hex = undefined;
61146
self.parsed_hex = undefined;
62147

63-
self.logHead = "[FIRMWARE_FLASHER]";
64-
65148
function getExtension(key) {
66149
if (!key) {
67150
return undefined;
@@ -742,20 +825,10 @@ firmware_flasher.initialize = async function (callback) {
742825
return output.join("").split("\n");
743826
}
744827

745-
function detectedUsbDevice(device) {
746-
const isFlashOnConnect = $("input.flash_on_connect").is(":checked");
747-
748-
console.log(`${self.logHead} Detected USB device:`, device);
749-
console.log(`${self.logHead} Reboot mode: %s, flash on connect`, STM32.rebootMode, isFlashOnConnect);
750-
751-
if (STM32.rebootMode || isFlashOnConnect) {
752-
STM32.rebootMode = 0;
753-
GUI.connect_lock = false;
754-
startFlashing();
755-
}
756-
}
757-
758-
EventBus.$on("port-handler:auto-select-usb-device", detectedUsbDevice);
828+
EventBus.$on("port-handler:auto-select-usb-device", firmware_flasher.detectedUsbDevice);
829+
EventBus.$on("port-handler:auto-select-serial-device", firmware_flasher.detectedSerialDevice);
830+
EventBus.$on("ports-input:change", firmware_flasher.onPortChange);
831+
EventBus.$on("port-handler:device-removed", firmware_flasher.onDeviceRemoved);
759832

760833
async function saveFirmware() {
761834
const fileType = self.firmware_type;
@@ -1389,6 +1462,12 @@ firmware_flasher.initialize = async function (callback) {
13891462
}
13901463
}
13911464

1465+
// Expose the local startFlashing implementation to module callers/tests so
1466+
// module-scoped handlers can safely call firmware_flasher.startFlashing()
1467+
// even if those callers ran before initialize() completed.
1468+
firmware_flasher.startFlashing = startFlashing;
1469+
firmware_flasher.clearBufferedFirmware = clearBufferedFirmware;
1470+
13921471
$("a.flash_firmware").on("click", async function () {
13931472
if (GUI.connect_lock) {
13941473
return;
@@ -1472,6 +1551,17 @@ firmware_flasher.initialize = async function (callback) {
14721551
$("a.exit_dfu").removeClass("disabled");
14731552
}
14741553

1554+
// Auto-detect board if drone is already connected when tab becomes active
1555+
if (
1556+
(PortHandler.portAvailable && !$('select[name="board"]').val()) ||
1557+
$('select[name="board"]').val() === "0"
1558+
) {
1559+
console.log(`${self.logHead} Auto-detecting board for already connected device`);
1560+
setTimeout(() => {
1561+
AutoDetect.verifyBoard();
1562+
}, AUTO_DETECT_DELAY_MS);
1563+
}
1564+
14751565
GUI.content_ready(callback);
14761566
}
14771567

@@ -1490,6 +1580,24 @@ firmware_flasher.cleanup = function (callback) {
14901580
$(document).unbind("keypress");
14911581
$(document).off("click", "span.progressLabel a");
14921582

1583+
const cleanupHandler = (evt, property) => {
1584+
const handler = firmware_flasher[property];
1585+
if (handler) {
1586+
EventBus.$off(evt, handler);
1587+
}
1588+
};
1589+
1590+
cleanupHandler("port-handler:auto-select-usb-device", "detectedUsbDevice");
1591+
cleanupHandler("port-handler:auto-select-serial-device", "detectedSerialDevice");
1592+
cleanupHandler("ports-input:change", "onPortChange");
1593+
cleanupHandler("port-handler:device-removed", "onDeviceRemoved");
1594+
1595+
// Clear any pending debounce timer so it cannot fire after cleanup
1596+
if (firmware_flasher.portChangeTimer) {
1597+
clearTimeout(firmware_flasher.portChangeTimer);
1598+
firmware_flasher.portChangeTimer = null;
1599+
}
1600+
14931601
if (callback) callback();
14941602
};
14951603

src/js/utils/AutoDetect.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ class AutoDetect {
5454
serial.connectionId,
5555
serial.openCanceled,
5656
);
57-
serial.disconnect();
5857
return;
5958
}
6059

0 commit comments

Comments
 (0)