Skip to content

cleanup and explicit use web prefix for protocols #4500

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/components/port-picker/PortsInput.vue
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
>
{{ connectedUsbDevice.displayName }}
</option>
<option v-if="showSerialOption" value="requestpermission">
<option v-if="showSerialOption" value="requestpermissionserial">
{{ $t("portsSelectPermission") }}
</option>
<option v-if="showBluetoothOption" value="requestpermissionbluetooth">
Expand Down Expand Up @@ -173,8 +173,8 @@ export default defineComponent({

const onChangePort = (event) => {
const value = event.target.value;
if (value === "requestpermission") {
EventBus.$emit("ports-input:request-permission");
if (value === "requestpermissionserial") {
EventBus.$emit("ports-input:request-permission-serial");
} else if (value === "requestpermissionbluetooth") {
EventBus.$emit("ports-input:request-permission-bluetooth");
} else if (value === "requestpermissionusb") {
Expand Down
2 changes: 0 additions & 2 deletions src/js/data_storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ const CONFIGURATOR = {

connectionValid: false,
connectionValidCliOnly: false,
bluetoothMode: false,
manualMode: false,
virtualMode: false,
virtualApiVersion: "0.0.1",
cliActive: false,
Expand Down
40 changes: 22 additions & 18 deletions src/js/port_handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ const PortHandler = new (function () {
})();

PortHandler.initialize = function () {
EventBus.$on("ports-input:request-permission-bluetooth", () => this.requestDevicePermission("bluetooth"));
EventBus.$on("ports-input:request-permission", () => this.requestDevicePermission("serial"));
EventBus.$on("ports-input:request-permission-bluetooth", () => this.requestDevicePermission("webbluetooth"));
EventBus.$on("ports-input:request-permission-serial", () => this.requestDevicePermission("webserial"));
EventBus.$on("ports-input:request-permission-usb", () => this.requestDevicePermission("usb"));
EventBus.$on("ports-input:change", this.onChangeSelectedPort.bind(this));

Expand All @@ -60,9 +60,9 @@ PortHandler.initialize = function () {
const detail = event.detail;

if (detail?.path?.startsWith("bluetooth")) {
this.handleDeviceAdded(detail, "bluetooth");
this.handleDeviceAdded(detail, "webbluetooth");
} else {
this.handleDeviceAdded(detail, "serial");
this.handleDeviceAdded(detail, "webserial");
}
});

Expand All @@ -81,8 +81,8 @@ PortHandler.initialize = function () {
PortHandler.refreshAllDeviceLists = async function () {
// Update all device lists in parallel
return Promise.all([
this.updateDeviceList("serial"),
this.updateDeviceList("bluetooth"),
this.updateDeviceList("webserial"),
this.updateDeviceList("webbluetooth"),
this.updateDeviceList("usb"),
]).then(() => {
this.selectActivePort();
Expand Down Expand Up @@ -112,16 +112,16 @@ PortHandler.removedSerialDevice = function (device) {
if (!devicePath) {
console.warn(`${this.logHead} Device removal event missing path information`, device);
// Still update ports, but don't try to use the undefined path
this.updateDeviceList("serial").then(() => {
this.updateDeviceList("webserial").then(() => {
this.selectActivePort();
});
return;
}

// Update the appropriate ports list based on the device type
const updatePromise = devicePath.startsWith("bluetooth")
? this.updateDeviceList("bluetooth")
: this.updateDeviceList("serial");
? this.updateDeviceList("webbluetooth")
: this.updateDeviceList("webserial");

const wasSelectedPort = this.portPicker.selectedPort === devicePath;

Expand Down Expand Up @@ -177,7 +177,9 @@ PortHandler.requestDevicePermission = function (deviceType) {

PortHandler.sortPorts = function (ports) {
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,
sensitivity: "base",
});
Expand Down Expand Up @@ -282,7 +284,7 @@ PortHandler.handleDeviceAdded = function (device, deviceType) {

// Update the appropriate device list
const updatePromise =
deviceType === "bluetooth" ? this.updateDeviceList("bluetooth") : this.updateDeviceList("serial");
deviceType === "webbluetooth" ? this.updateDeviceList("webbluetooth") : this.updateDeviceList("webserial");

updatePromise.then(() => {
const selectedPort = this.selectActivePort(device);
Expand All @@ -304,19 +306,19 @@ PortHandler.updateDeviceList = async function (deviceType) {

try {
switch (deviceType) {
case "bluetooth":
case "webbluetooth":
if (this.showBluetoothOption) {
ports = await serial.getDevices("bluetooth");
ports = await serial.getDevices("webbluetooth");
}
break;
case "usb":
if (this.showUsbOption) {
ports = await WEBUSBDFU.getDevices();
}
break;
case "serial":
case "webserial":
if (this.showSerialOption) {
ports = await serial.getDevices("serial");
ports = await serial.getDevices("webserial");
}
break;
default:
Expand All @@ -329,7 +331,7 @@ PortHandler.updateDeviceList = async function (deviceType) {

// Update the appropriate properties based on device type
switch (deviceType) {
case "bluetooth":
case "webbluetooth":
this.bluetoothAvailable = orderedPorts.length > 0;
this.currentBluetoothPorts = [...orderedPorts];
console.log(`${this.logHead} Found bluetooth port(s)`, orderedPorts);
Expand All @@ -339,12 +341,14 @@ PortHandler.updateDeviceList = async function (deviceType) {
this.currentUsbPorts = [...orderedPorts];
console.log(`${this.logHead} Found DFU port(s)`, orderedPorts);
break;
case "serial":
default:
case "webserial":
this.portAvailable = orderedPorts.length > 0;
this.currentSerialPorts = [...orderedPorts];
console.log(`${this.logHead} Found serial port(s)`, orderedPorts);
break;
default:
console.warn(`${this.logHead} Unknown device type for updating ports: ${deviceType}`);
return [];
}

return orderedPorts;
Expand Down
2 changes: 1 addition & 1 deletion src/js/protocols/WebBluetooth.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class WebBluetooth extends EventTarget {

this.bluetooth.addEventListener("connect", (e) => this.handleNewDevice(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();
}
Expand Down
5 changes: 4 additions & 1 deletion src/js/protocols/WebSerial.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { webSerialDevices, vendorIdNames } from "./devices";
import GUI from "../gui";

const logHead = "[SERIAL]";
const logHead = "[WEBSERIAL]";

async function* streamAsyncIterable(reader, keepReadingFlag) {
try {
Expand Down Expand Up @@ -308,13 +308,16 @@ class WebSerial extends EventTarget {

this.connectionId = false;
this.bitrate = 0;
this.connectionInfo = null; // Reset connectionInfo
this.closeRequested = false;

this.dispatchEvent(new CustomEvent("disconnect", { detail: true }));
return true;
} catch (error) {
console.error(`${logHead} Error disconnecting:`, error);
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 }));
return false;
} finally {
Expand Down
64 changes: 13 additions & 51 deletions src/js/serial.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,18 @@ class Serial extends EventTarget {

// Initialize the available protocols
this._webSerial = new WebSerial();
this._bluetooth = new WebBluetooth();
this._websocket = new Websocket();
this._webBluetooth = new WebBluetooth();
this._webSocket = new Websocket();
this._virtual = new VirtualSerial();

// Update protocol map to use consistent naming
this._protocolMap = {
serial: this._webSerial, // TODO: should be 'webserial'
bluetooth: this._bluetooth, // TODO: should be 'webbluetooth'
websocket: this._websocket,
webserial: this._webSerial,
webbluetooth: this._webBluetooth,
websocket: this._webSocket,
virtual: this._virtual,
};

// Initialize with default protocol
this.selectProtocol(false);

// Forward events from all protocols to the Serial class
this._setupEventForwarding();
}
Expand Down Expand Up @@ -61,10 +58,10 @@ class Serial extends EventTarget {
if (protocol === this._webSerial) {
return "webserial";
}
if (protocol === this._bluetooth) {
if (protocol === this._webBluetooth) {
return "webbluetooth";
}
if (protocol === this._websocket) {
if (protocol === this._webSocket) {
return "websocket";
}
if (protocol === this._virtual) {
Expand All @@ -77,7 +74,7 @@ class Serial extends EventTarget {
* Set up event forwarding from all protocols to the Serial class
*/
_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"];

protocols.forEach((protocol) => {
Expand Down Expand Up @@ -114,59 +111,28 @@ 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 {boolean} forceDisconnect - Whether to force disconnect from current protocol
*/
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;

if (portPath) {
// Select protocol based on port path
if (portPath === "virtual") {
console.log(`${this.logHead} Using virtual protocol (based on port path)`);
newProtocol = this._virtual;
// Update CONFIGURATOR flags for consistency
CONFIGURATOR.virtualMode = true;
CONFIGURATOR.bluetoothMode = false;
CONFIGURATOR.manualMode = false;
} else if (portPath === "manual") {
console.log(`${this.logHead} Using websocket protocol (based on port path)`);
newProtocol = this._websocket;
// Update CONFIGURATOR flags for consistency
CONFIGURATOR.virtualMode = false;
CONFIGURATOR.bluetoothMode = false;
CONFIGURATOR.manualMode = true;
newProtocol = this._webSocket;
} else if (portPath.startsWith("bluetooth")) {
console.log(`${this.logHead} Using bluetooth protocol (based on port path: ${portPath})`);
newProtocol = this._bluetooth;
// Update CONFIGURATOR flags for consistency
CONFIGURATOR.virtualMode = false;
CONFIGURATOR.bluetoothMode = true;
CONFIGURATOR.manualMode = false;
newProtocol = this._webBluetooth;
} else {
console.log(`${this.logHead} Using web serial protocol (based on port path: ${portPath})`);
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;
}
}

Expand All @@ -184,8 +150,6 @@ class Serial extends EventTarget {
// Set new protocol
this._protocol = newProtocol;
console.log(`${this.logHead} Protocol switched successfully to:`, this._protocol);
} else {
console.log(`${this.logHead} Same protocol selected, no switch needed`);
}

return this._protocol;
Expand Down Expand Up @@ -251,8 +215,6 @@ class Serial extends EventTarget {
return false;
}

console.log(`${this.logHead} Disconnecting from current protocol`, this._protocol);

try {
// Handle case where we're already disconnected
if (!this._protocol.connected) {
Expand Down Expand Up @@ -292,7 +254,7 @@ class Serial extends EventTarget {

/**
* 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
*/
async getDevices(protocolType = null) {
Expand Down
9 changes: 5 additions & 4 deletions src/js/serial_backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,9 @@ function connectDisconnect() {

// Set configuration flags for consistency with other code
CONFIGURATOR.virtualMode = selectedPort === "virtual";
CONFIGURATOR.bluetoothMode = selectedPort.startsWith("bluetooth");
CONFIGURATOR.manualMode = selectedPort === "manual";

// Select the appropriate protocol based directly on the port path
serial.selectProtocol(selectedPort);
console.log("Serial protocol selected:", serial._protocol, "using port", portName);

if (CONFIGURATOR.virtualMode) {
CONFIGURATOR.virtualApiVersion = PortHandler.portPicker.virtualMspVersion;
Expand Down Expand Up @@ -186,7 +183,11 @@ function finishClose(finishedCallback) {
$("#dialogResetToCustomDefaults")[0].close();
}

serial.disconnect(onClosed);
serial.disconnect();

if (CONFIGURATOR.virtualMode) {
onClosed(true);
}

MSP.disconnect_cleanup();
PortUsage.reset();
Expand Down
4 changes: 2 additions & 2 deletions src/js/utils/checkBrowserCompatibility.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,13 @@ export function checkBrowserCompatibility() {
.css({
height: "100%",
display: "grid",
"background-image": "url(../images/osd-bg-1.jpg",
"background-image": "url(../images/osd-bg-1.jpg)",
"background-size": "cover",
"background-repeat": "no-repeat",
})
.append(newDiv);

$("div").append(errorMessage).css({
$(newDiv).append(errorMessage).css({
"font-size": "16px",
"background-color": "var(--surface-200)",
color: "var(--text)",
Expand Down