1
0
Fork 0
mirror of https://github.com/betaflight/betaflight-configurator.git synced 2025-07-17 13:25:24 +03:00

cleanup and explicit use web prefix for protocols (#4500)

* cleanup

* more cleanup

* Reset connectionInfo

* Fix todo

* Fix default

* More explicit
This commit is contained in:
Mark Haslinghuis 2025-06-14 23:40:40 +02:00 committed by GitHub
parent 52d3b8dbc5
commit 16ae2ac65f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 50 additions and 82 deletions

View file

@ -42,7 +42,7 @@
> >
{{ connectedUsbDevice.displayName }} {{ connectedUsbDevice.displayName }}
</option> </option>
<option v-if="showSerialOption" value="requestpermission"> <option v-if="showSerialOption" value="requestpermissionserial">
{{ $t("portsSelectPermission") }} {{ $t("portsSelectPermission") }}
</option> </option>
<option v-if="showBluetoothOption" value="requestpermissionbluetooth"> <option v-if="showBluetoothOption" value="requestpermissionbluetooth">
@ -173,8 +173,8 @@ export default defineComponent({
const onChangePort = (event) => { const onChangePort = (event) => {
const value = event.target.value; const value = event.target.value;
if (value === "requestpermission") { if (value === "requestpermissionserial") {
EventBus.$emit("ports-input:request-permission"); EventBus.$emit("ports-input:request-permission-serial");
} else if (value === "requestpermissionbluetooth") { } else if (value === "requestpermissionbluetooth") {
EventBus.$emit("ports-input:request-permission-bluetooth"); EventBus.$emit("ports-input:request-permission-bluetooth");
} else if (value === "requestpermissionusb") { } else if (value === "requestpermissionusb") {

View file

@ -11,8 +11,6 @@ const CONFIGURATOR = {
connectionValid: false, connectionValid: false,
connectionValidCliOnly: false, connectionValidCliOnly: false,
bluetoothMode: false,
manualMode: false,
virtualMode: false, virtualMode: false,
virtualApiVersion: "0.0.1", virtualApiVersion: "0.0.1",
cliActive: false, cliActive: false,

View file

@ -50,8 +50,8 @@ const PortHandler = new (function () {
})(); })();
PortHandler.initialize = function () { PortHandler.initialize = function () {
EventBus.$on("ports-input:request-permission-bluetooth", () => this.requestDevicePermission("bluetooth")); EventBus.$on("ports-input:request-permission-bluetooth", () => this.requestDevicePermission("webbluetooth"));
EventBus.$on("ports-input:request-permission", () => this.requestDevicePermission("serial")); EventBus.$on("ports-input:request-permission-serial", () => this.requestDevicePermission("webserial"));
EventBus.$on("ports-input:request-permission-usb", () => this.requestDevicePermission("usb")); EventBus.$on("ports-input:request-permission-usb", () => this.requestDevicePermission("usb"));
EventBus.$on("ports-input:change", this.onChangeSelectedPort.bind(this)); EventBus.$on("ports-input:change", this.onChangeSelectedPort.bind(this));
@ -60,9 +60,9 @@ PortHandler.initialize = function () {
const detail = event.detail; const detail = event.detail;
if (detail?.path?.startsWith("bluetooth")) { if (detail?.path?.startsWith("bluetooth")) {
this.handleDeviceAdded(detail, "bluetooth"); this.handleDeviceAdded(detail, "webbluetooth");
} else { } else {
this.handleDeviceAdded(detail, "serial"); this.handleDeviceAdded(detail, "webserial");
} }
}); });
@ -81,8 +81,8 @@ PortHandler.initialize = function () {
PortHandler.refreshAllDeviceLists = async function () { PortHandler.refreshAllDeviceLists = async function () {
// Update all device lists in parallel // Update all device lists in parallel
return Promise.all([ return Promise.all([
this.updateDeviceList("serial"), this.updateDeviceList("webserial"),
this.updateDeviceList("bluetooth"), this.updateDeviceList("webbluetooth"),
this.updateDeviceList("usb"), this.updateDeviceList("usb"),
]).then(() => { ]).then(() => {
this.selectActivePort(); this.selectActivePort();
@ -112,7 +112,7 @@ PortHandler.removedSerialDevice = function (device) {
if (!devicePath) { if (!devicePath) {
console.warn(`${this.logHead} Device removal event missing path information`, device); console.warn(`${this.logHead} Device removal event missing path information`, device);
// Still update ports, but don't try to use the undefined path // Still update ports, but don't try to use the undefined path
this.updateDeviceList("serial").then(() => { this.updateDeviceList("webserial").then(() => {
this.selectActivePort(); this.selectActivePort();
}); });
return; return;
@ -120,8 +120,8 @@ PortHandler.removedSerialDevice = function (device) {
// Update the appropriate ports list based on the device type // Update the appropriate ports list based on the device type
const updatePromise = devicePath.startsWith("bluetooth") const updatePromise = devicePath.startsWith("bluetooth")
? this.updateDeviceList("bluetooth") ? this.updateDeviceList("webbluetooth")
: this.updateDeviceList("serial"); : this.updateDeviceList("webserial");
const wasSelectedPort = this.portPicker.selectedPort === devicePath; const wasSelectedPort = this.portPicker.selectedPort === devicePath;
@ -177,7 +177,9 @@ PortHandler.requestDevicePermission = function (deviceType) {
PortHandler.sortPorts = function (ports) { PortHandler.sortPorts = function (ports) {
return ports.sort(function (a, b) { return ports.sort(function (a, b) {
return a.path.localeCompare(b.path, window.navigator.language, { const locale = typeof window !== "undefined" && window.navigator ? window.navigator.language : "en";
return a.path.localeCompare(b.path, locale, {
numeric: true, numeric: true,
sensitivity: "base", sensitivity: "base",
}); });
@ -282,7 +284,7 @@ PortHandler.handleDeviceAdded = function (device, deviceType) {
// Update the appropriate device list // Update the appropriate device list
const updatePromise = const updatePromise =
deviceType === "bluetooth" ? this.updateDeviceList("bluetooth") : this.updateDeviceList("serial"); deviceType === "webbluetooth" ? this.updateDeviceList("webbluetooth") : this.updateDeviceList("webserial");
updatePromise.then(() => { updatePromise.then(() => {
const selectedPort = this.selectActivePort(device); const selectedPort = this.selectActivePort(device);
@ -304,9 +306,9 @@ PortHandler.updateDeviceList = async function (deviceType) {
try { try {
switch (deviceType) { switch (deviceType) {
case "bluetooth": case "webbluetooth":
if (this.showBluetoothOption) { if (this.showBluetoothOption) {
ports = await serial.getDevices("bluetooth"); ports = await serial.getDevices("webbluetooth");
} }
break; break;
case "usb": case "usb":
@ -314,9 +316,9 @@ PortHandler.updateDeviceList = async function (deviceType) {
ports = await WEBUSBDFU.getDevices(); ports = await WEBUSBDFU.getDevices();
} }
break; break;
case "serial": case "webserial":
if (this.showSerialOption) { if (this.showSerialOption) {
ports = await serial.getDevices("serial"); ports = await serial.getDevices("webserial");
} }
break; break;
default: default:
@ -329,7 +331,7 @@ PortHandler.updateDeviceList = async function (deviceType) {
// Update the appropriate properties based on device type // Update the appropriate properties based on device type
switch (deviceType) { switch (deviceType) {
case "bluetooth": case "webbluetooth":
this.bluetoothAvailable = orderedPorts.length > 0; this.bluetoothAvailable = orderedPorts.length > 0;
this.currentBluetoothPorts = [...orderedPorts]; this.currentBluetoothPorts = [...orderedPorts];
console.log(`${this.logHead} Found bluetooth port(s)`, orderedPorts); console.log(`${this.logHead} Found bluetooth port(s)`, orderedPorts);
@ -339,12 +341,14 @@ PortHandler.updateDeviceList = async function (deviceType) {
this.currentUsbPorts = [...orderedPorts]; this.currentUsbPorts = [...orderedPorts];
console.log(`${this.logHead} Found DFU port(s)`, orderedPorts); console.log(`${this.logHead} Found DFU port(s)`, orderedPorts);
break; break;
case "serial": case "webserial":
default:
this.portAvailable = orderedPorts.length > 0; this.portAvailable = orderedPorts.length > 0;
this.currentSerialPorts = [...orderedPorts]; this.currentSerialPorts = [...orderedPorts];
console.log(`${this.logHead} Found serial port(s)`, orderedPorts); console.log(`${this.logHead} Found serial port(s)`, orderedPorts);
break; break;
default:
console.warn(`${this.logHead} Unknown device type for updating ports: ${deviceType}`);
return [];
} }
return orderedPorts; return orderedPorts;

View file

@ -44,7 +44,7 @@ class WebBluetooth extends EventTarget {
this.bluetooth.addEventListener("connect", (e) => this.handleNewDevice(e.target)); this.bluetooth.addEventListener("connect", (e) => this.handleNewDevice(e.target));
this.bluetooth.addEventListener("disconnect", (e) => this.handleRemovedDevice(e.target)); this.bluetooth.addEventListener("disconnect", (e) => this.handleRemovedDevice(e.target));
this.bluetooth.addEventListener("gatserverdisconnected", (e) => this.handleRemovedDevice(e.target)); this.bluetooth.addEventListener("gattserverdisconnected", (e) => this.handleRemovedDevice(e.target));
this.loadDevices(); this.loadDevices();
} }

View file

@ -1,7 +1,7 @@
import { webSerialDevices, vendorIdNames } from "./devices"; import { webSerialDevices, vendorIdNames } from "./devices";
import GUI from "../gui"; import GUI from "../gui";
const logHead = "[SERIAL]"; const logHead = "[WEBSERIAL]";
async function* streamAsyncIterable(reader, keepReadingFlag) { async function* streamAsyncIterable(reader, keepReadingFlag) {
try { try {
@ -308,6 +308,7 @@ class WebSerial extends EventTarget {
this.connectionId = false; this.connectionId = false;
this.bitrate = 0; this.bitrate = 0;
this.connectionInfo = null; // Reset connectionInfo
this.closeRequested = false; this.closeRequested = false;
this.dispatchEvent(new CustomEvent("disconnect", { detail: true })); this.dispatchEvent(new CustomEvent("disconnect", { detail: true }));
@ -315,6 +316,8 @@ class WebSerial extends EventTarget {
} catch (error) { } catch (error) {
console.error(`${logHead} Error disconnecting:`, error); console.error(`${logHead} Error disconnecting:`, error);
this.closeRequested = false; this.closeRequested = false;
// Ensure connectionInfo is reset even on error if port was potentially open
this.connectionInfo = null;
this.dispatchEvent(new CustomEvent("disconnect", { detail: false })); this.dispatchEvent(new CustomEvent("disconnect", { detail: false }));
return false; return false;
} finally { } finally {

View file

@ -18,21 +18,18 @@ class Serial extends EventTarget {
// Initialize the available protocols // Initialize the available protocols
this._webSerial = new WebSerial(); this._webSerial = new WebSerial();
this._bluetooth = new WebBluetooth(); this._webBluetooth = new WebBluetooth();
this._websocket = new Websocket(); this._webSocket = new Websocket();
this._virtual = new VirtualSerial(); this._virtual = new VirtualSerial();
// Update protocol map to use consistent naming // Update protocol map to use consistent naming
this._protocolMap = { this._protocolMap = {
serial: this._webSerial, // TODO: should be 'webserial' webserial: this._webSerial,
bluetooth: this._bluetooth, // TODO: should be 'webbluetooth' webbluetooth: this._webBluetooth,
websocket: this._websocket, websocket: this._webSocket,
virtual: this._virtual, virtual: this._virtual,
}; };
// Initialize with default protocol
this.selectProtocol(false);
// Forward events from all protocols to the Serial class // Forward events from all protocols to the Serial class
this._setupEventForwarding(); this._setupEventForwarding();
} }
@ -61,10 +58,10 @@ class Serial extends EventTarget {
if (protocol === this._webSerial) { if (protocol === this._webSerial) {
return "webserial"; return "webserial";
} }
if (protocol === this._bluetooth) { if (protocol === this._webBluetooth) {
return "webbluetooth"; return "webbluetooth";
} }
if (protocol === this._websocket) { if (protocol === this._webSocket) {
return "websocket"; return "websocket";
} }
if (protocol === this._virtual) { if (protocol === this._virtual) {
@ -77,7 +74,7 @@ class Serial extends EventTarget {
* Set up event forwarding from all protocols to the Serial class * Set up event forwarding from all protocols to the Serial class
*/ */
_setupEventForwarding() { _setupEventForwarding() {
const protocols = [this._webSerial, this._bluetooth, this._websocket, this._virtual]; const protocols = [this._webSerial, this._webBluetooth, this._webSocket, this._virtual];
const events = ["addedDevice", "removedDevice", "connect", "disconnect", "receive"]; const events = ["addedDevice", "removedDevice", "connect", "disconnect", "receive"];
protocols.forEach((protocol) => { protocols.forEach((protocol) => {
@ -114,12 +111,12 @@ class Serial extends EventTarget {
} }
/** /**
* Selects the appropriate protocol based on port path or CONFIGURATOR settings * Selects the appropriate protocol based on port path
* @param {string|null} portPath - Optional port path to determine protocol * @param {string|null} portPath - Optional port path to determine protocol
* @param {boolean} forceDisconnect - Whether to force disconnect from current protocol * @param {boolean} forceDisconnect - Whether to force disconnect from current protocol
*/ */
selectProtocol(portPath = null, forceDisconnect = true) { selectProtocol(portPath = null, forceDisconnect = true) {
// Determine which protocol to use based on port path first, then fall back to CONFIGURATOR // Determine which protocol to use based on port path
let newProtocol; let newProtocol;
if (portPath) { if (portPath) {
@ -127,46 +124,15 @@ class Serial extends EventTarget {
if (portPath === "virtual") { if (portPath === "virtual") {
console.log(`${this.logHead} Using virtual protocol (based on port path)`); console.log(`${this.logHead} Using virtual protocol (based on port path)`);
newProtocol = this._virtual; newProtocol = this._virtual;
// Update CONFIGURATOR flags for consistency
CONFIGURATOR.virtualMode = true;
CONFIGURATOR.bluetoothMode = false;
CONFIGURATOR.manualMode = false;
} else if (portPath === "manual") { } else if (portPath === "manual") {
console.log(`${this.logHead} Using websocket protocol (based on port path)`); console.log(`${this.logHead} Using websocket protocol (based on port path)`);
newProtocol = this._websocket; newProtocol = this._webSocket;
// Update CONFIGURATOR flags for consistency
CONFIGURATOR.virtualMode = false;
CONFIGURATOR.bluetoothMode = false;
CONFIGURATOR.manualMode = true;
} else if (portPath.startsWith("bluetooth")) { } else if (portPath.startsWith("bluetooth")) {
console.log(`${this.logHead} Using bluetooth protocol (based on port path: ${portPath})`); console.log(`${this.logHead} Using bluetooth protocol (based on port path: ${portPath})`);
newProtocol = this._bluetooth; newProtocol = this._webBluetooth;
// Update CONFIGURATOR flags for consistency
CONFIGURATOR.virtualMode = false;
CONFIGURATOR.bluetoothMode = true;
CONFIGURATOR.manualMode = false;
} else { } else {
console.log(`${this.logHead} Using web serial protocol (based on port path: ${portPath})`); console.log(`${this.logHead} Using web serial protocol (based on port path: ${portPath})`);
newProtocol = this._webSerial; newProtocol = this._webSerial;
// Update CONFIGURATOR flags for consistency
CONFIGURATOR.virtualMode = false;
CONFIGURATOR.bluetoothMode = false;
CONFIGURATOR.manualMode = false;
}
} else {
// Fall back to CONFIGURATOR flags if no port path is provided
if (CONFIGURATOR.virtualMode) {
console.log(`${this.logHead} Using virtual protocol (based on CONFIGURATOR flags)`);
newProtocol = this._virtual;
} else if (CONFIGURATOR.manualMode) {
console.log(`${this.logHead} Using websocket protocol (based on CONFIGURATOR flags)`);
newProtocol = this._websocket;
} else if (CONFIGURATOR.bluetoothMode) {
console.log(`${this.logHead} Using bluetooth protocol (based on CONFIGURATOR flags)`);
newProtocol = this._bluetooth;
} else {
console.log(`${this.logHead} Using web serial protocol (based on CONFIGURATOR flags)`);
newProtocol = this._webSerial;
} }
} }
@ -184,8 +150,6 @@ class Serial extends EventTarget {
// Set new protocol // Set new protocol
this._protocol = newProtocol; this._protocol = newProtocol;
console.log(`${this.logHead} Protocol switched successfully to:`, this._protocol); console.log(`${this.logHead} Protocol switched successfully to:`, this._protocol);
} else {
console.log(`${this.logHead} Same protocol selected, no switch needed`);
} }
return this._protocol; return this._protocol;
@ -251,8 +215,6 @@ class Serial extends EventTarget {
return false; return false;
} }
console.log(`${this.logHead} Disconnecting from current protocol`, this._protocol);
try { try {
// Handle case where we're already disconnected // Handle case where we're already disconnected
if (!this._protocol.connected) { if (!this._protocol.connected) {
@ -292,7 +254,7 @@ class Serial extends EventTarget {
/** /**
* Get devices from a specific protocol type or current protocol * Get devices from a specific protocol type or current protocol
* @param {string} protocolType - Optional protocol type ('serial', 'bluetooth', 'websocket', 'virtual') * @param {string} protocolType - Optional protocol type ('webserial', 'webbluetooth', 'websocket', 'virtual')
* @returns {Promise<Array>} - List of devices * @returns {Promise<Array>} - List of devices
*/ */
async getDevices(protocolType = null) { async getDevices(protocolType = null) {

View file

@ -125,12 +125,9 @@ function connectDisconnect() {
// Set configuration flags for consistency with other code // Set configuration flags for consistency with other code
CONFIGURATOR.virtualMode = selectedPort === "virtual"; CONFIGURATOR.virtualMode = selectedPort === "virtual";
CONFIGURATOR.bluetoothMode = selectedPort.startsWith("bluetooth");
CONFIGURATOR.manualMode = selectedPort === "manual";
// Select the appropriate protocol based directly on the port path // Select the appropriate protocol based directly on the port path
serial.selectProtocol(selectedPort); serial.selectProtocol(selectedPort);
console.log("Serial protocol selected:", serial._protocol, "using port", portName);
if (CONFIGURATOR.virtualMode) { if (CONFIGURATOR.virtualMode) {
CONFIGURATOR.virtualApiVersion = PortHandler.portPicker.virtualMspVersion; CONFIGURATOR.virtualApiVersion = PortHandler.portPicker.virtualMspVersion;
@ -186,7 +183,11 @@ function finishClose(finishedCallback) {
$("#dialogResetToCustomDefaults")[0].close(); $("#dialogResetToCustomDefaults")[0].close();
} }
serial.disconnect(onClosed); serial.disconnect();
if (CONFIGURATOR.virtualMode) {
onClosed(true);
}
MSP.disconnect_cleanup(); MSP.disconnect_cleanup();
PortUsage.reset(); PortUsage.reset();

View file

@ -108,13 +108,13 @@ export function checkBrowserCompatibility() {
.css({ .css({
height: "100%", height: "100%",
display: "grid", display: "grid",
"background-image": "url(../images/osd-bg-1.jpg", "background-image": "url(../images/osd-bg-1.jpg)",
"background-size": "cover", "background-size": "cover",
"background-repeat": "no-repeat", "background-repeat": "no-repeat",
}) })
.append(newDiv); .append(newDiv);
$("div").append(errorMessage).css({ $(newDiv).append(errorMessage).css({
"font-size": "16px", "font-size": "16px",
"background-color": "var(--surface-200)", "background-color": "var(--surface-200)",
color: "var(--text)", color: "var(--text)",