Skip to content

Conversation

@X9X0
Copy link
Owner

@X9X0 X9X0 commented Nov 28, 2025

Summary

Fixes equipment readings returning 404 Not Found errors and implements proper protocol support for BK Precision 1900B series power supplies.

Problems Fixed

1. Equipment 404 Errors

  • Equipment IDs were randomly generated using UUID, causing them to change on every reconnection
  • Resulted in 404 Not Found errors when trying to access equipment readings after reconnection

2. Invalid VISA Session Errors

  • Discovery scans would invalidate active equipment VISA sessions
  • No auto-reconnection mechanism to recover from invalid sessions
  • Resource manager would also become invalid, preventing reconnection

3. BK Precision Communication Failures

  • BK Precision 1900B series doesn't support SCPI commands
  • All commands (*IDN?, MEAS:VOLT?, etc.) timed out after 10 seconds
  • Required switching to proprietary BK Precision protocol

4. Serial Port Resource Leaks

  • Old instruments weren't properly closed before reconnection
  • Caused file descriptor corruption and NoneType errors

5. Response Buffer Contamination

  • PyVISA read_termination stopped at first \r, leaving OK\r in buffer
  • Subsequent reads got contaminated data instead of actual responses

Changes Made

Deterministic Equipment IDs

  • Generate equipment IDs using SHA256 hash of resource string
  • Same resource always produces same ID (e.g., ASRL/dev/ttyUSB0::INSTRps_56fdd3df)
  • Updated all equipment classes to use deterministic ID generation

Auto-Reconnection System

  • Added _is_instrument_valid() to detect invalid VISA sessions
  • Added _ensure_connected() to auto-reconnect on invalid sessions
  • Added _is_resource_manager_valid() to detect invalid resource managers
  • Added _refresh_resource_manager() to create new resource manager when needed
  • Integrated into all _write(), _query(), and _query_binary() operations

BK Precision Protocol Support

  • Switched from SCPI to BK Precision proprietary protocol
  • Changed line endings from \r\n to \r only
  • Implemented correct command format:
    • GMAX - Get max voltage/current (format: VVVCCC)
    • GETS - Get voltage/current settings (format: VVVCCC)
    • GETD - Get display readings (format: VVVVIIIIIM)
    • GOUT - Get output state (0=OFF, 1=ON)
    • VOLT{vvv} - Set voltage (voltage × 10)
    • CURR{ccc} - Set current (current × 10)
    • SOUT0/SOUT1 - Set output (0=ON, 1=OFF)
  • All responses end with \rOK\r which is properly parsed

Proper Resource Cleanup

  • Close old instruments before opening new ones
  • Prevents file descriptor leaks and corruption
  • Properly handles exceptions during cleanup

Response Buffer Handling

  • Read full BK responses byte-by-byte until OK\r terminator
  • No longer relies on read_termination for BK protocol
  • Eliminates buffer contamination issues

Testing

Tested with BK Precision 1902B power supply:

  • ✅ Equipment connects successfully
  • ✅ Deterministic ID generated correctly
  • ✅ Readings return valid data (voltage, current, output state, CV/CC mode)
  • ✅ Auto-reconnection works after discovery scans
  • ✅ Resource manager refresh works
  • ✅ No timeouts or buffer errors

Commits

  • 2140b60 - Generate deterministic equipment IDs to prevent 404 errors
  • 27a6e9a - Add automatic VISA session recovery to prevent InvalidSession errors
  • ea3b8a5 - Refresh resource manager during auto-reconnection
  • d6a9191 - Call _refresh_resource_manager() in BK power supply connect method
  • 09da3e5 - Properly close old instrument before reconnection
  • 3bf6cf7 - Update BK Precision driver to use proprietary protocol instead of SCPI
  • 408a45c - Read full BK Precision response including OK terminator

Breaking Changes

None - all changes are backward compatible improvements to existing functionality.

…rors

Equipment was failing with "InvalidSession: The resource might be closed" errors
when the VISA resource manager was recreated (e.g., during discovery or when
validating resource manager health). This happened because:

1. Resource manager recreation invalidates all instrument sessions opened by the old manager
2. Equipment instances retained references to invalid instrument handles
3. Any subsequent operations on those instruments would fail with InvalidSession

Solution:
- Added `_is_instrument_valid()` method to check if instrument session is still valid
- Added `_ensure_connected()` method to auto-reconnect when invalid session detected
- Updated `_write()`, `_query()`, and `_query_binary()` to validate and reconnect
- Added `_is_connecting` flag to prevent recursion during connection

Benefits:
- Equipment automatically recovers from invalid sessions
- No manual reconnection required when resource manager is recreated
- Transparent to API consumers - operations just work
- Proper logging when auto-reconnection occurs

This fixes the 500 Internal Server Error on /api/equipment/{id}/readings endpoint
that occurred after resource manager recreation.
The auto-reconnect logic was failing because when the resource manager
was recreated (e.g., during discovery), equipment instances still held
references to the old, invalid resource manager.

When equipment tried to reconnect after detecting an invalid session,
the reconnection would fail with the same InvalidSession error because
self.resource_manager.open_resource() was called on a closed manager.

Solution:
- Added _is_resource_manager_valid() to check if resource manager is valid
- Added _refresh_resource_manager() to create a new manager if invalid
- Updated connect() to refresh resource manager before opening instruments

This ensures that auto-reconnection can always succeed by creating a
fresh resource manager when needed.
The BK power supply class overrides the base connect() method but wasn't
calling _refresh_resource_manager() before opening the instrument. This
caused auto-reconnection to fail when the resource manager became invalid.

This fix ensures that the resource manager is validated and refreshed
before attempting to open the instrument connection, preventing
InvalidSession errors during auto-reconnection.
When reconnecting after an invalid session, the old instrument wasn't
being closed before opening a new one. This caused the serial port's
file descriptor to become None, leading to TypeError during reads.

Changes:
- Close old instrument in base.connect() before opening new resource
- Close old instrument in BKPowerSupplyBase.connect() before opening
- Close old instrument in _ensure_connected() before reconnecting

This ensures proper cleanup of file descriptors and prevents conflicts
when the same resource is opened multiple times.
…f SCPI

The BK Precision 1900B series (including 1902B) doesn't support SCPI commands.
They use a proprietary protocol with different command format and line endings.

Changes:
- Changed termination from '\r\n' (CR+LF) to '\r' (CR only)
- Replaced SCPI commands with BK Precision commands:
  * *IDN? → GMAX (for verification)
  * VOLT <value> → VOLT{vvv} (voltage * 10, 3 digits)
  * CURR <value> → CURR{ccc} (current * 10, 3 digits)
  * OUTP ON/OFF → SOUT0/SOUT1 (0=ON, 1=OFF)
  * MEAS:VOLT?/MEAS:CURR? → GETD (returns VVVVIIIIIM format)
  * VOLT?/CURR? → GETS (returns VVVCCC format)
  * OUTP? → GOUT (returns 0=OFF or 1=ON)

Response parsing:
- GMAX/GETS format: VVVCCC (voltage÷10, current÷10)
- GETD format: VVVVIIIIIM (voltage÷100, current÷1000, mode 0/1)
- All responses end with \rOK\r which is stripped

This fixes timeout errors where the BK1902B wasn't responding to SCPI
commands because it doesn't understand that protocol.
When read_termination is set to '\r', PyVISA stops at the FIRST '\r'
and leaves the rest ('OK\r') in the buffer. This caused subsequent
reads to get 'OK' instead of actual data, resulting in empty responses.

Changes:
- Modified _bk_query to read full response byte-by-byte until 'OK\r'
- Added asyncio import for event loop timing
- No longer relies on read_termination for parsing BK responses
- Properly handles the complete response format: DATA\rOK\r

This fixes "Invalid GETD response:" errors where the response was
empty due to buffer contamination from previous reads.
@X9X0 X9X0 merged commit b468671 into main Nov 28, 2025
25 checks passed
@X9X0 X9X0 deleted the claude/fix-equipment-readings-404-011YNFgs3A54537srRvDcAe6 branch November 28, 2025 20:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants