Skip to content

Navigation Menu

Sign in
Sign up
This repository was archived by the owner on May 21, 2026. It is now read-only.

Fix: Explicitly detect PSLab device on Windows 11 (Fixes #269) - #711

Open
saurabh24thakur wants to merge 1 commit into
fossasia:development from
saurabh24thakur:fix-windows-connection
Open

Fix: Explicitly detect PSLab device on Windows 11 (Fixes #269) #711
saurabh24thakur wants to merge 1 commit into
fossasia:development from
saurabh24thakur:fix-windows-connection

Conversation

@saurabh24thakur

@saurabh24thakur saurabh24thakur commented Dec 26, 2025
edited by sourcery-ai Bot
Loading

Copy link
Copy Markdown
  • Please check if the PR fulfills these requirements
  • The commit message follows our guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)
  • Bug fix
  • Feature implementation
  • Doc updates
  • What changes have you introduced?

  • Does this PR introduce a breaking change?

  • Preview / Steps to verify your work:

Summary by Sourcery

Improve PSLab device connection handling by explicitly scanning serial ports for the device VID/PID and using a safer connection fallback path, particularly for Windows 11.

Bug Fixes:

  • Detect PSLab devices by USB VID/PID before connecting, improving reliability on systems like Windows 11 where automatic detection may fail.
  • Prevent crashes when connecting if the ScienceLab constructor signature or instantiation fails by falling back to auto-detection or a dummy disconnected device.

sourcery-ai Bot commented Dec 26, 2025
edited
Loading

Copy link
Copy Markdown

Reviewer's Guide

Explicitly scans serial ports for the PSLab USB VID/PID on connection, preferentially connects using the detected port, and adds defensive handling/fallbacks when ScienceLab instantiation fails or doesn’t accept a port parameter, preventing crashes in device detection on Windows 11.

Sequence diagram for updated async_connect device detection and connection

sequenceDiagram
 participant DeviceDetector
 participant SerialPorts as list_ports
 participant ScienceLab
 participant DummyDevice
 participant Stderr as sys_stderr
 DeviceDetector->>SerialPorts: comports()
 SerialPorts-->>DeviceDetector: found_ports
 DeviceDetector->>Stderr: write("Scanning N ports")
 loop for each port in found_ports
 DeviceDetector->>Stderr: write("port.device VID=vid PID=pid")
 alt port matches PSLab VID/PID
 DeviceDetector->>DeviceDetector: set pslab_port = port.device
 end
 end
 alt pslab_port is not None
 DeviceDetector->>Stderr: write("Attempting to connect to PSLab on pslab_port")
 DeviceDetector->>ScienceLab: __init__(port=pslab_port)
 else pslab_port is None
 DeviceDetector->>Stderr: write("PSLab not found, trying auto-detect")
 DeviceDetector->>ScienceLab: __init__()
 end
 alt TypeError raised
 DeviceDetector->>Stderr: write("ScienceLab does not accept port, falling back")
 DeviceDetector->>ScienceLab: __init__()
 else other Exception raised
 DeviceDetector->>Stderr: write("Error during connection: e")
 DeviceDetector->>DummyDevice: create instance
 DeviceDetector->>DeviceDetector: self.device = DummyDevice
 else no exception
 DeviceDetector->>DeviceDetector: self.device = ScienceLab
 end
 DeviceDetector->>DeviceDetector: check self.device.connected
 alt self.device.connected is False
 DeviceDetector->>DeviceDetector: handle no device connected
 else self.device.connected is True
 DeviceDetector->>DeviceDetector: proceed with connected device
 end
Loading

Class diagram for updated device_detection async_connect behavior

classDiagram
 class DeviceDetector {
 +device
 +async_connect()
 +disconnect()
 }
 class ScienceLab {
 +connected bool
 +ScienceLab()
 +ScienceLab(port)
 }
 class DummyDevice {
 +connected bool
 }
 class list_ports {
 +comports()
 }
 DeviceDetector --> ScienceLab : uses
 DeviceDetector --> DummyDevice : fallback
 DeviceDetector --> list_ports : scans_ports
Loading

Flow diagram for async_connect port scanning and connection logic

flowchart TD
 A["Start async_connect"] --> B["Call list_ports.comports and get found_ports"]
 B --> C["Log number of ports to stderr"]
 C --> D["Iterate ports and log VID/PID"]
 D --> E{"port VID==0x04D8 and PID==0x00DF?"}
 E -- "yes" --> F["Set pslab_port to port.device"]
 E -- "no" --> G["Continue scanning"]
 F --> G
 G --> H{"More ports?"}
 H -- "yes" --> D
 H -- "no" --> I{"pslab_port is not None?"}
 I -- "yes" --> J["Log attempt with pslab_port"]
 J --> K["Try ScienceLab(port=pslab_port)"]
 I -- "no" --> L["Log auto-detect attempt"]
 L --> M["Try ScienceLab()"]
 K --> N{"Exception?"}
 M --> N
 N -- "TypeError" --> O["Log port not accepted"]
 O --> P["ScienceLab() without port"]
 N -- "Other Exception" --> Q["Log error message"]
 Q --> R["Create DummyDevice with connected=False"]
 N -- "No exception" --> S["self.device = ScienceLab instance"]
 P --> T["self.device = ScienceLab instance"]
 R --> U["self.device = DummyDevice instance"]
 S --> V{"Check self.device.connected"}
 T --> V
 U --> V
 V --> W{"connected?"}
 W -- "yes" --> X["Proceed with connected device path"]
 W -- "no" --> Y["Handle no device connected path"]
Loading

File-Level Changes

Change Details Files
Add explicit PSLab port scanning and VID/PID-based selection before creating the ScienceLab device.
  • Enumerates available serial ports via list_ports.comports() and logs the count to stderr.
  • Logs each port’s device name, VID, and PID for debugging purposes.
  • Identifies the PSLab port by matching the known USB VID 0x04D8 and PID 0x00DF and stores its device path.
scripts/device_detection.py
Prefer connecting to PSLab using the detected port, with fallbacks for compatibility and robustness.
  • Attempts to instantiate ScienceLab with the detected PSLab port if found, otherwise falls back to default auto-detection.
  • Catches TypeError if ScienceLab does not support a port argument and retries instantiation without it.
  • Catches generic exceptions during connection, logs the error, and substitutes a DummyDevice with connected = False to avoid attribute access crashes when checking connection state.
scripts/device_detection.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues, and left some high level feedback:

  • Accessing p.vid and p.pid directly in the port scan can raise AttributeError on some platforms/adapters; consider using getattr(p, "vid", None) / getattr(p, "pid", None) to make the detection more robust.
  • The detailed sys.stderr.write logging in async_connect looks like diagnostic output; if this is intended to remain, consider routing it through the existing logging/debug mechanism or gating it behind a verbosity flag to avoid noisy stderr in normal use.
  • Catching a broad Exception when instantiating ScienceLab and then substituting a DummyDevice may hide real connection/setup issues; it might be safer to either narrow the exception types or propagate/log more context so failures are visible to callers.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Accessing `p.vid` and `p.pid` directly in the port scan can raise `AttributeError` on some platforms/adapters; consider using `getattr(p, "vid", None)` / `getattr(p, "pid", None)` to make the detection more robust.
- The detailed `sys.stderr.write` logging in `async_connect` looks like diagnostic output; if this is intended to remain, consider routing it through the existing logging/debug mechanism or gating it behind a verbosity flag to avoid noisy stderr in normal use.
- Catching a broad `Exception` when instantiating `ScienceLab` and then substituting a `DummyDevice` may hide real connection/setup issues; it might be safer to either narrow the exception types or propagate/log more context so failures are visible to callers.
## Individual Comments
### Comment 1
<location> `scripts/device_detection.py:33-42` </location>
<code_context>
+
  # First connection attempt
-  self.device = ScienceLab()
+  try:
+  if pslab_port:
+  sys.stderr.write(f"Attempting to connect to PSLab on {pslab_port}\n")
+  self.device = ScienceLab(port=pslab_port)
+  else:
+  sys.stderr.write("PSLab not found in port scan, trying auto-detect\n")
+  self.device = ScienceLab()
+  except TypeError:
+  sys.stderr.write("ScienceLab does not accept 'port' argument, falling back to auto-detect\n")
+  self.device = ScienceLab()
+  except Exception as e:
+  sys.stderr.write(f"Error during connection: {e}\n")
+  # Create a dummy device object if instantiation failed completely
</code_context>
<issue_to_address>
**issue (bug_risk):** Catching a broad Exception here can hide real issues and make failures harder to diagnose.
This blanket `except Exception` will also catch unrelated programming or environment errors in `ScienceLab(...)`, potentially causing the code to continue with a `DummyDevice` and obscure real failures. Prefer catching only the specific connection/serial exceptions `ScienceLab` can raise, or at minimum log a full traceback so unexpected errors remain visible.
</issue_to_address>
### Comment 2
<location> `scripts/device_detection.py:40-42` </location>
<code_context>
+  else:
+  sys.stderr.write("PSLab not found in port scan, trying auto-detect\n")
+  self.device = ScienceLab()
+  except TypeError:
+  sys.stderr.write("ScienceLab does not accept 'port' argument, falling back to auto-detect\n")
+  self.device = ScienceLab()
+  except Exception as e:
+  sys.stderr.write(f"Error during connection: {e}\n")
</code_context>
<issue_to_address>
**suggestion (bug_risk):** The TypeError fallback may mask other constructor issues, not just a missing 'port' parameter.
Catching bare `TypeError` here will also hide unrelated bugs thrown from within `ScienceLab.__init__`. To only handle the "unsupported `port`" case, consider checking the constructor signature ahead of time or filtering on the exception message before falling back to `ScienceLab()`; otherwise genuine errors will be treated as a normal auto-detect path.
```suggestion
 except TypeError as e:
 # Only treat this as a "no port argument" case if the error is about an
 # unexpected or unsupported 'port' keyword argument. Otherwise, re-raise
 # so genuine constructor bugs are not silently ignored.
 msg = str(e)
 if (
 "unexpected keyword argument 'port'" in msg
 or "got an unexpected keyword argument 'port'" in msg
 or ("port" in msg and "keyword" in msg and "argument" in msg)
 ):
 sys.stderr.write(
 "ScienceLab does not accept 'port' argument, falling back to auto-detect\n"
 )
 self.device = ScienceLab()
 else:
 raise
```
</issue_to_address>
### Comment 3
<location> `scripts/device_detection.py:45-49` </location>
<code_context>
+  self.device = ScienceLab()
+  except Exception as e:
+  sys.stderr.write(f"Error during connection: {e}\n")
+  # Create a dummy device object if instantiation failed completely
+  # so that self.device.connected check doesn't crash
+  class DummyDevice:
+  connected = False
+  self.device = DummyDevice()
+
  output = None
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Creating DummyDevice inside the exception block is a bit heavy and may be incomplete if more attributes are used later.
Defining `DummyDevice` in the `except` block creates a new class on every failure and only provides `connected`. If other `self.device` members are used later, this can turn a connection failure into harder-to-debug attribute errors. Consider a lightweight placeholder (e.g. `types.SimpleNamespace(connected=False)`) or a single module-level `DummyDevice` that implements the minimal interface expected downstream.
Suggested implementation:
```python
 except Exception as e:
 sys.stderr.write(f"Error during connection: {e}\n")
 # Create a lightweight dummy device object if instantiation failed completely
 # so that self.device.connected check doesn't crash
 self.device = types.SimpleNamespace(connected=False)
```
You will also need to ensure `types` is imported at the top of `scripts/device_detection.py`, for example:
- Add `import types` alongside the other imports, or
- If there is an existing `import types` line, no further changes are needed.
If other attributes on `self.device` are required elsewhere (e.g. `self.device.read`, `self.device.write`), you may extend the `SimpleNamespace` to include them, for example:
`types.SimpleNamespace(connected=False, read=lambda *a, **k: None, write=lambda *a, **k: None)`.
</issue_to_address>
### Comment 4
<location> `scripts/device_detection.py:24-29` </location>
<code_context>
  def async_connect(self):
+  # Debug: List all ports
+  found_ports = list_ports.comports()
+  sys.stderr.write(f"Scanning {len(found_ports)} ports:\n")
+  pslab_port = None
+  for p in found_ports:
+  sys.stderr.write(f" - {p.device}: VID={p.vid}, PID={p.pid}\n")
+  if p.vid == 0x04D8 and p.pid == 0x00DF:
+  pslab_port = p.device
+
</code_context>
<issue_to_address>
**suggestion:** Unconditional verbose logging to stderr may be noisy in production environments.
This will emit the full port scan (`Scanning...`, `VID/PID`, and connection attempts) to `stderr` on every `async_connect()` call, which can be noisy in GUI apps or where `stderr` is user-visible. Consider gating this behind a debug/verbose flag or routing it through the existing logging system at an appropriate log level instead of using `sys.stderr.write` directly.
Suggested implementation:
```python
 self.device_detection_thread.join()
 def async_connect(self):
 # Debug: List all ports (only logs when DEBUG is enabled)
 found_ports = list_ports.comports()
 if logger.isEnabledFor(logging.DEBUG):
 logger.debug("Scanning %d ports:", len(found_ports))
 pslab_port = None
 for p in found_ports:
 if logger.isEnabledFor(logging.DEBUG):
 logger.debug(" - %s: VID=%s, PID=%s", p.device, p.vid, p.pid)
 if p.vid == 0x04D8 and p.pid == 0x00DF:
 pslab_port = p.device
```
To fully implement this change you should also:
1. Ensure `logging` is imported in `scripts/device_detection.py`, e.g. `import logging`.
2. Ensure a module- or class-level logger named `logger` exists, e.g. `logger = logging.getLogger(__name__)`, or adjust the calls to use whatever logger your codebase already uses (for example, `self.logger` instead of `logger`).
3. Optionally configure the logging level externally (e.g., via your app’s logging config) so that these messages only appear when DEBUG logging is enabled.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +33 to +42
try:
if pslab_port:
sys.stderr.write(f"Attempting to connect to PSLab on {pslab_port}\n")
self.device = ScienceLab(port=pslab_port)
else:
sys.stderr.write("PSLab not found in port scan, trying auto-detect\n")
self.device = ScienceLab()
except TypeError:
sys.stderr.write("ScienceLab does not accept 'port' argument, falling back to auto-detect\n")
self.device = ScienceLab()

@sourcery-ai sourcery-ai Bot Dec 26, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Catching a broad Exception here can hide real issues and make failures harder to diagnose.

This blanket except Exception will also catch unrelated programming or environment errors in ScienceLab(...), potentially causing the code to continue with a DummyDevice and obscure real failures. Prefer catching only the specific connection/serial exceptions ScienceLab can raise, or at minimum log a full traceback so unexpected errors remain visible.

sourcery-ai[bot] reacted with thumbs up emoji sourcery-ai[bot] reacted with thumbs down emoji
Comment on lines +40 to +42
except TypeError:
sys.stderr.write("ScienceLab does not accept 'port' argument, falling back to auto-detect\n")
self.device = ScienceLab()

@sourcery-ai sourcery-ai Bot Dec 26, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): The TypeError fallback may mask other constructor issues, not just a missing 'port' parameter.

Catching bare TypeError here will also hide unrelated bugs thrown from within ScienceLab.__init__. To only handle the "unsupported port" case, consider checking the constructor signature ahead of time or filtering on the exception message before falling back to ScienceLab(); otherwise genuine errors will be treated as a normal auto-detect path.

Suggested change
except TypeError:
sys.stderr.write("ScienceLab does not accept 'port' argument, falling back to auto-detect\n")
self.device = ScienceLab()
except TypeError as e:
# Only treat this as a "no port argument" case if the error is about an
# unexpected or unsupported 'port' keyword argument. Otherwise, re-raise
# so genuine constructor bugs are not silently ignored.
msg = str(e)
if (
"unexpected keyword argument 'port'" in msg
or "got an unexpected keyword argument 'port'" in msg
or ("port" in msg and "keyword" in msg and "argument" in msg)
):
sys.stderr.write(
"ScienceLab does not accept 'port' argument, falling back to auto-detect\n"
)
self.device = ScienceLab()
else:
raise

sourcery-ai[bot] reacted with thumbs up emoji sourcery-ai[bot] reacted with thumbs down emoji
Comment on lines +45 to +49
# Create a dummy device object if instantiation failed completely
# so that self.device.connected check doesn't crash
class DummyDevice:
connected = False
self.device = DummyDevice()

@sourcery-ai sourcery-ai Bot Dec 26, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Creating DummyDevice inside the exception block is a bit heavy and may be incomplete if more attributes are used later.

Defining DummyDevice in the except block creates a new class on every failure and only provides connected. If other self.device members are used later, this can turn a connection failure into harder-to-debug attribute errors. Consider a lightweight placeholder (e.g. types.SimpleNamespace(connected=False)) or a single module-level DummyDevice that implements the minimal interface expected downstream.

Suggested implementation:

 except Exception as e:
 sys.stderr.write(f"Error during connection: {e}\n")
 # Create a lightweight dummy device object if instantiation failed completely
 # so that self.device.connected check doesn't crash
 self.device = types.SimpleNamespace(connected=False)

You will also need to ensure types is imported at the top of scripts/device_detection.py, for example:

  • Add import types alongside the other imports, or
  • If there is an existing import types line, no further changes are needed.

If other attributes on self.device are required elsewhere (e.g. self.device.read, self.device.write), you may extend the SimpleNamespace to include them, for example:
types.SimpleNamespace(connected=False, read=lambda *a, **k: None, write=lambda *a, **k: None).

sourcery-ai[bot] reacted with thumbs up emoji sourcery-ai[bot] reacted with thumbs down emoji
Comment on lines +24 to +29
found_ports = list_ports.comports()
sys.stderr.write(f"Scanning {len(found_ports)} ports:\n")
pslab_port = None
for p in found_ports:
sys.stderr.write(f" - {p.device}: VID={p.vid}, PID={p.pid}\n")
if p.vid == 0x04D8 and p.pid == 0x00DF:

@sourcery-ai sourcery-ai Bot Dec 26, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Unconditional verbose logging to stderr may be noisy in production environments.

This will emit the full port scan (Scanning..., VID/PID, and connection attempts) to stderr on every async_connect() call, which can be noisy in GUI apps or where stderr is user-visible. Consider gating this behind a debug/verbose flag or routing it through the existing logging system at an appropriate log level instead of using sys.stderr.write directly.

Suggested implementation:

 self.device_detection_thread.join()
 def async_connect(self):
 # Debug: List all ports (only logs when DEBUG is enabled)
 found_ports = list_ports.comports()
 if logger.isEnabledFor(logging.DEBUG):
 logger.debug("Scanning %d ports:", len(found_ports))
 pslab_port = None
 for p in found_ports:
 if logger.isEnabledFor(logging.DEBUG):
 logger.debug(" - %s: VID=%s, PID=%s", p.device, p.vid, p.pid)
 if p.vid == 0x04D8 and p.pid == 0x00DF:
 pslab_port = p.device

To fully implement this change you should also:

  1. Ensure logging is imported in scripts/device_detection.py, e.g. import logging.
  2. Ensure a module- or class-level logger named logger exists, e.g. logger = logging.getLogger(__name__), or adjust the calls to use whatever logger your codebase already uses (for example, self.logger instead of logger).
  3. Optionally configure the logging level externally (e.g., via your app’s logging config) so that these messages only appear when DEBUG logging is enabled.

sourcery-ai[bot] reacted with thumbs up emoji sourcery-ai[bot] reacted with thumbs down emoji

Copy link
Copy Markdown
Author

I have submitted a fix in PR #269

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Reviewers

1 more reviewer
@sourcery-ai sourcery-ai[bot] sourcery-ai[bot] left review comments
Reviewers whose approvals may not affect merge requirements

At least 1 approving review is required to merge this pull request.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

1 participant

AltStyle によって変換されたページ (->オリジナル) /