Skip to content

Commit a33910e

Browse files
committed
Improve events
1 parent 8c10a46 commit a33910e

File tree

9 files changed

+498
-27
lines changed

9 files changed

+498
-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: 120 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,84 @@ 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(`${this.logHead} Detected USB device:`, device);
54+
console.log(`${this.logHead} Reboot mode: %s, flash on connect`, STM32.rebootMode, isFlashOnConnect);
55+
56+
// If another operation is in progress, ignore port events (unless we're resuming from a reboot)
57+
if (GUI.connect_lock && !STM32.rebootMode) {
58+
console.log(`${this.logHead} Port event ignored due to active operation (connect_lock)`);
59+
return;
60+
}
61+
62+
// Proceed if we're resuming a reboot sequence or if flash-on-connect is enabled and no operation is active
63+
if (STM32.rebootMode || isFlashOnConnect) {
64+
const wasReboot = !!STM32.rebootMode;
65+
STM32.rebootMode = 0;
66+
// Only clear the global connect lock when we are resuming from a reboot
67+
// so we don't accidentally interrupt another active operation.
68+
if (wasReboot) {
69+
GUI.connect_lock = false;
70+
}
71+
this.startFlashing?.();
72+
}
73+
},
74+
detectedSerialDevice: function () {
75+
AutoDetect.verifyBoard();
76+
},
77+
onPortChange: function (port) {
78+
// Clear any pending debounce timer so rapid port events don't re-enter the handler.
79+
if (firmware_flasher.portChangeTimer) {
80+
clearTimeout(firmware_flasher.portChangeTimer);
81+
firmware_flasher.portChangeTimer = null;
82+
}
83+
84+
console.log(`${self.logHead} Port changed to:`, port);
85+
86+
if (GUI.connect_lock) {
87+
console.log(`${this.logHead} Port change ignored during active operation (connect_lock set)`);
88+
return;
89+
}
90+
91+
// Auto-detect board when port changes and we're on firmware flasher tab
92+
if (port && port !== "0" && $("input.flash_on_connect").is(":checked") === false && !STM32.rebootMode) {
93+
console.log(`${self.logHead} Auto-detecting board for port change (debounced)`);
94+
95+
// Debounced verification: re-check connect lock when the timeout fires
96+
firmware_flasher.portChangeTimer = setTimeout(() => {
97+
firmware_flasher.portChangeTimer = null;
98+
if (GUI.connect_lock) {
99+
console.log(`${this.logHead} Skipping auto-detect due to active operation at timeout`);
100+
return;
101+
}
102+
AutoDetect.verifyBoard();
103+
}, PORT_CHANGE_DEBOUNCE_MS);
104+
} else if (!port || port === "0") {
105+
if (!GUI.connect_lock) {
106+
console.log(`${this.logHead} Clearing board selection - no port selected`);
107+
$('select[name="board"]').val("0").trigger("change");
108+
} else {
109+
console.log(`${this.logHead} Not clearing board selection because operation in progress`);
110+
}
111+
}
112+
},
113+
onDeviceRemoved: function (devicePath) {
114+
console.log(`${this.logHead} Device removed:`, devicePath);
115+
116+
// Avoid clearing when removal is expected during flashing/reboot
117+
if (GUI.connect_lock || STM32.rebootMode) {
118+
return;
119+
}
120+
121+
$('select[name="board"]').val("0").trigger("change");
122+
this.clearBufferedFirmware?.();
123+
},
43124
};
44125

45126
firmware_flasher.initialize = async function (callback) {
@@ -60,8 +141,6 @@ firmware_flasher.initialize = async function (callback) {
60141
self.intel_hex = undefined;
61142
self.parsed_hex = undefined;
62143

63-
self.logHead = "[FIRMWARE_FLASHER]";
64-
65144
function getExtension(key) {
66145
if (!key) {
67146
return undefined;
@@ -742,20 +821,10 @@ firmware_flasher.initialize = async function (callback) {
742821
return output.join("").split("\n");
743822
}
744823

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);
824+
EventBus.$on("port-handler:auto-select-usb-device", firmware_flasher.detectedUsbDevice);
825+
EventBus.$on("port-handler:auto-select-serial-device", firmware_flasher.detectedSerialDevice);
826+
EventBus.$on("ports-input:change", firmware_flasher.onPortChange);
827+
EventBus.$on("port-handler:device-removed", firmware_flasher.onDeviceRemoved);
759828

760829
async function saveFirmware() {
761830
const fileType = self.firmware_type;
@@ -1389,6 +1458,12 @@ firmware_flasher.initialize = async function (callback) {
13891458
}
13901459
}
13911460

1461+
// Expose the local startFlashing implementation to module callers/tests so
1462+
// module-scoped handlers can safely call firmware_flasher.startFlashing()
1463+
// even if those callers ran before initialize() completed.
1464+
firmware_flasher.startFlashing = startFlashing;
1465+
firmware_flasher.clearBufferedFirmware = clearBufferedFirmware;
1466+
13921467
$("a.flash_firmware").on("click", async function () {
13931468
if (GUI.connect_lock) {
13941469
return;
@@ -1472,6 +1547,17 @@ firmware_flasher.initialize = async function (callback) {
14721547
$("a.exit_dfu").removeClass("disabled");
14731548
}
14741549

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

@@ -1490,6 +1576,24 @@ firmware_flasher.cleanup = function (callback) {
14901576
$(document).unbind("keypress");
14911577
$(document).off("click", "span.progressLabel a");
14921578

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

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)