Migration from legacy SDK ========================= This page is for customers with existing code written against the legacy Bentham SDK - the ``pyBen`` Python module, the ``bendll.h``/``dllerror.h``/``dlltoken.h`` C headers, or the ``BI_*.vi`` LabVIEW wrapper VIs - who want to move to this SDK. The guide covers the languages that both SDKs target: :ref:`Python `, :ref:`C `, :ref:`C++ ` and :ref:`LabVIEW `. What does not change -------------------- Both SDKs are wrappers around the same ``BI_*`` functions exported by the BenHW DLL, so the hardware side of your application carries over unchanged: * Your system configuration (``.cfg``) and setup (``.atr``) files are used as they are. * The call sequence is the same: build the system model, load the setup, initialise, park, zero calibrate, select wavelength, measure, close. See :doc:`model`. * Every token and error code defined in the legacy ``dlltoken.h``/``dllerror.h`` exists in this SDK with the same name and the same numeric value. See :doc:`tokens` and :doc:`errors`. * Component IDs passed to ``get``/``set`` and other functions are the IDs in your ``.cfg`` file, as before. What changes is how you load the library, how results come back, and how errors are reported. ---- .. _migration_python: Python: ``pyBen`` to ``benhw`` ------------------------------ Installation ^^^^^^^^^^^^ Uninstall the ``pyBen`` wheel or MSI installer and install ``benhw`` from PyPI. ``benhw`` requires Python 3.12 or later and bundles the BenHW DLLs, so nothing needs to be copied onto ``PATH``. .. code-block:: bash pip uninstall pyBen pip install benhw Overview of the differences ^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. list-table:: :header-rows: 1 :widths: 30 35 35 * - Topic - ``pyBen`` - ``benhw`` * - Import - ``import pyBen`` - ``from benhw import BenHW, tokens, SdkException`` * - Calling a function - Module-level function: ``pyBen.initialise()`` - Method on an instance: ``hw = BenHW()`` then ``hw.initialise()`` * - Function names - ``BI_`` prefix removed - Unchanged from ``pyBen``: ``BI_`` prefix removed * - Return value - A dict: ``{"Error": 0, "reading": 1.23}`` - The value itself (``1.23``), a result object for several outputs, or ``None`` * - Errors - Check ``result["Error"] != 0`` after every call - An exception derived from ``SdkException`` is raised * - Tokens - Raw integers, e.g. ``11`` - Named constants, e.g. ``tokens.MonochromatorCurrentWL`` * - DLL loading - On ``import``; DLL must be found by the module - On ``BenHW()``; uses the bundled DLL, or ``BenHW(dll_path=...)`` Before and after ^^^^^^^^^^^^^^^^ Legacy ``pyBen`` code: .. code-block:: python import pyBen r = pyBen.build_system_model("system.cfg") if r["Error"] != 0: raise RuntimeError(r["description"]) pyBen.load_setup("system.atr") pyBen.initialise() pyBen.park() pyBen.zero_calibration(300.0, 800.0) pyBen.select_wavelength(555.0, 0) result = pyBen.automeasure() if result["Error"] == 0: print(result["reading"]) wl = pyBen.get("mono", 11, 0)["value"] # 11 = MonochromatorCurrentWL pyBen.close() The same code using ``benhw``: .. code-block:: python import time from benhw import BenHW, tokens, SdkException hw = BenHW() try: hw.build_system_model("system.cfg") hw.load_setup("system.atr") hw.initialise() hw.park() hw.zero_calibration(300.0, 800.0) settle_ms = hw.select_wavelength(555.0) time.sleep(settle_ms / 1000) reading = hw.automeasure() print(reading) wl = hw.get("mono", tokens.MonochromatorCurrentWL, 0) except SdkException as e: print(f"BenHW error {e.error_code}: {e.message}") finally: hw.close() Error handling ^^^^^^^^^^^^^^ Remove the ``["Error"]`` checks. Every method either succeeds or raises: * ``SdkException`` is the base class; it has ``error_code`` (the ``BI_*`` value) and ``message``. * Each error code has its own subclass, e.g. ``AdcOverloadException`` for ``BI_ADC_Overload`` or ``InvalidComponentException`` for ``BI_invalid_component``. These are importable from ``benhw`` or ``benhw.exceptions``. See :doc:`errors` for the full mapping. * When the DLL returns the generic ``BI_error`` (-1), the wrapper calls ``BI_report_error()`` for you and raises the more specific exception if one is available. The legacy pattern of calling ``report_error()`` after a failure is no longer needed. * ``build_system_model`` no longer returns the description string; if the configuration cannot be built, the DLL's message is the ``message`` of the raised ``SdkException``. .. code-block:: python from benhw import exceptions try: reading = hw.automeasure() except exceptions.AdcOverloadException: hw.autorange() reading = hw.automeasure() Functions whose signature or result changed ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Most functions only need the ``pyBen.`` prefix replaced and the ``["key"]`` lookup removed. The following need more attention: .. list-table:: :header-rows: 1 :widths: 40 60 * - ``pyBen`` - ``benhw`` * - ``select_wavelength(wl, delay)`` - ``select_wavelength(wl)``. The ``delay`` argument is gone. The settle delay in milliseconds is now *returned* (``pyBen`` discarded it); wait for it before measuring. * - ``multi_select_wavelength(wl, delay)`` - ``multi_select_wavelength(wl)``, returning the settle delay as above. * - ``component_select_wl(id, wl, delay)`` - ``component_select_wl(id, wl)``. * - ``get_zero_calibration_info()`` returns ``{"calibrationInfo": {"wavelength": (...), "darkCurrent": (...), "ADCOffset": (...)}}`` - Returns a result object with list attributes ``wavelength``, ``DarkCurrent`` and ``ADCOffset``. Note the capital ``D`` in ``DarkCurrent``. ``multi_get_zero_calibration_info(group)`` is the same. * - ``multi_measurement()`` returns a tuple under ``"reading"`` - Returns a ``list[float]``, one reading per group. * - ``read(size, id)`` returns ``"message"`` - ``read(buffer_size, id)`` returns a result object with ``buffer`` (``bytes``) and ``chars_read`` (``int``). * - ``trace(on)`` - ``trace(i, LoggingDir)``: also takes the directory the trace log is written to. * - ``version()`` returns ``{"description": ...}`` - Returns a ``str``. * - ``report_error()`` - Returns the detailed error code as an ``int``. Usually unnecessary (see above). * - ``get``/``set`` with integer tokens - Integers still work, but use the names in ``benhw.tokens`` for readability. ``benhw`` also exposes functions that ``pyBen`` never wrapped, including ``get_str``/``set_str``, ``multi_automeasure``, ``multi_park``, ``get_min_step``, ``get_max_bw``, logging (``start_log``, ``stop_log``, ``get_log``) and ``SCPI_query``/``SCPI_write``. See :doc:`python_api` for the complete list. ---- .. _migration_c: C: ``bendll.h`` to ``benhw.h`` ------------------------------ The function names and arguments are the ``BI_*`` functions you already call, so most C code compiles after changing the includes and the loader calls. Install the headers and DLLs as described in :doc:`c_api`. Overview of the differences ^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. list-table:: :header-rows: 1 :widths: 30 35 35 * - Topic - Legacy headers - ``benhw.h`` * - Includes - ``bendll.h``, ``dllerror.h``, ``dlltoken.h`` - ``benhw.h`` (includes ``errors.h`` and ``tokens.h``) * - Loading the DLL - Call ``init()`` and check for ``LOADED_DLL`` - Automatic on the first ``BI_*`` call, or ``benhw_load(NULL)`` to load up front * - Unloading the DLL - ``close()`` - ``benhw_unload()`` * - DLL used - ``benhw32_stdcall.dll`` (``WINAPI``) - ``benhw64.dll`` or ``benhw32_cdecl.dll``, chosen by process bitness * - Settle delay type - ``long*`` - ``int*`` * - ``BI_read`` sizes - ``short BufferSize``, ``short* CharsRead`` - ``uint16_t buffer_size``, ``uint16_t* chars_read`` * - Function not found in DLL - ``init()`` fails with ``UNABLE_TO_LOAD_FUNCTIONS`` - That call returns ``BENHW_ERR_DLL_LOAD_FAILED`` (-9000) Before and after ^^^^^^^^^^^^^^^^ Legacy code: .. code-block:: c #include #include "dllerror.h" #include "dlltoken.h" #include "bendll.h" int main(void) { char error[256]; long settle_delay = 0; double reading; if (init() != LOADED_DLL) return 1; if (BI_build_system_model("system.cfg", error) != BI_OK) { /* ... */ } BI_load_setup("system.atr"); BI_initialise(); BI_park(); BI_select_wavelength(555.0, &settle_delay); Sleep(settle_delay); BI_automeasure(&reading); close(); /* legacy close() only unloads the DLL */ return 0; } The same code using ``benhw.h``: .. code-block:: c #include #include "benhw.h" int main(void) { char error[256]; int settle_delay = 0; double reading; if (!benhw_load(NULL)) /* optional: fail early if the DLL is missing */ return 1; if (BI_build_system_model("system.cfg", error) != BI_OK) { printf("%s\n", error); return 1; } BI_load_setup("system.atr"); BI_initialise(); BI_park(); BI_select_wavelength(555.0, &settle_delay); Sleep(settle_delay); BI_automeasure(&reading); BI_close(); /* release the system model */ benhw_unload(); return 0; } Notes ^^^^^ * **Remove the legacy loader helpers.** Delete calls to ``init()`` and ``close()``: they were helper functions defined in ``bendll.h``, not DLL exports. The legacy ``close()`` only called ``FreeLibrary``; it never called ``BI_close()``. Call ``BI_close()`` yourself before unloading. * **Change the settle-delay variable type.** Use ``int`` instead of ``long`` for ``BI_select_wavelength``, ``BI_multi_select_wavelength`` and ``BI_component_select_wl``. * **Ship the cdecl or 64-bit DLL**, not ``benhw32_stdcall.dll``. ``benhw.h`` looks for the DLL next to your executable, then in a ``dlls`` subfolder, then on the normal DLL search path. To use a specific file, call ``benhw_load("C:\\path\\to\\benhw64.dll")`` before any other call. Your program can now be built as 64-bit. * **Error and token constants** (``BI_OK``, ``BI_error``, ``MonochromatorCurrentWL``, ...) keep their names and values. Error checks such as ``if (result != BI_OK)`` are unchanged. * If another part of your process has already loaded the DLL, use ``benhw_load_from_module(hmodule)`` instead of ``benhw_load()``. ---- .. _migration_cpp: C++: ``bendll.h`` to ``benhw.hpp`` ---------------------------------- C++ code that used the legacy C headers can follow the :ref:`C migration ` above and keep calling ``BI_*`` functions. Alternatively, switch to the ``benhw::BenHW`` class in ``benhw.hpp`` (in the same package), which replaces error-code checks and output buffers with return values and exceptions: .. code-block:: cpp #include #include #include #include "benhw.hpp" int main() { benhw::BenHW hw; // loads the DLL; unloads it when hw goes out of scope try { hw.build_system_model("system.cfg"); hw.load_setup("system.atr"); hw.initialise(); hw.park(); hw.zero_calibration(300.0, 800.0); int settle_ms = hw.select_wavelength(555.0); std::this_thread::sleep_for(std::chrono::milliseconds(settle_ms)); double reading = hw.automeasure(); std::cout << reading << "\n"; double wl = hw.get("mono", MonochromatorCurrentWL, 0); // tokens.h constant hw.close(); } catch (const benhw::SdkException& e) { std::cerr << "BenHW error " << e.error_code() << ": " << e.what() << "\n"; return 1; } return 0; } The method names are the C function names without the ``BI_`` prefix. The :doc:`exception classes ` and result types (e.g. ``get_zero_calibration_info_result``) match those of the Python SDK. See :doc:`cpp_api`. ---- .. _migration_labview: LabVIEW: ``BI_*.vi`` wrappers to the .NET assembly -------------------------------------------------- The legacy LabVIEW examples were VIs (``BI_SystemSetup.vi``, ``BI_MoveToWavelength.vi``, ``BI_TakeReading.vi``, ``BI_Get.vi``, ``BI_Set.vi``, ...) that called the DLL through Call Library Function Nodes and returned integer error codes. This SDK replaces them with the .NET assembly ``BenHW.dll``, which LabVIEW calls through .NET Constructor and Invoke Nodes. Install it and create the constructor as described in :doc:`labview`. Overview of the differences ^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. list-table:: :header-rows: 1 :widths: 30 35 35 * - Topic - Legacy VIs - .NET assembly * - Calling a function - Call Library Function Node on the BenHW DLL - Invoke Node on the reference from the ``BenHW`` Constructor Node * - Function names - ``BI_select_wavelength`` - PascalCase, without ``BI_``: ``SelectWavelength`` * - Outputs - Pointer parameters wired to indicators - Return value of the Invoke Node * - Errors - Integer return value compared with ``BI_OK`` - ``SdkException`` reported in the node's **error out** cluster * - DLL selection - Path configured in each Call Library Function Node - Single ``dllPath`` input on the Constructor Node Common replacements ^^^^^^^^^^^^^^^^^^^ .. list-table:: :header-rows: 1 :widths: 40 60 * - Legacy VI / DLL call - .NET method (Invoke Node) * - ``BI_build_system_model``, ``BI_load_setup``, ``BI_initialise`` (``BI_SystemSetup.vi``) - ``BuildSystemModel``, ``LoadSetup``, ``Initialise`` * - ``BI_park`` (``BI_Park.vi``) - ``Park`` * - ``BI_select_wavelength`` (``BI_MoveToWavelength.vi``) - ``SelectWavelength``: returns the settle delay in milliseconds * - ``BI_automeasure`` (``BI_TakeReading.vi``) - ``Automeasure``: returns the reading * - ``BI_get`` / ``BI_set`` (``BI_Get.vi`` / ``BI_Set.vi``) - ``Get`` / ``Set``, with the same numeric token values * - ``BI_close_shutter`` (``CloseShutter.vi``) - ``CloseShutter`` * - ``BI_report_error`` (``BI_Return_Error.vi``) - Not needed: the error is in **error out**. ``ReportError`` is still available. * - ``BI_version`` (``BI_GetVersion.vi``) - ``Version``: returns a string * - ``BI_close`` (``BI_Close.vi``) - ``Close``, then close the .NET reference A scan (``BI_Scan.vi``) becomes a loop of ``SelectWavelength``, a wait for the returned settle delay, and ``Automeasure``. The full method list is in :doc:`dotnet_api`. Notes ^^^^^ * **Errors arrive in the error cluster.** When a method throws, LabVIEW reports a .NET exception in the Invoke Node's **error out**; the exception message identifies the BenHW error. Wire **error in**/**error out** through your sequence, so a failure stops the following calls, in place of the legacy checks on each return code. * **Match the DLL to LabVIEW's bitness.** Wire the path of ``benhw64.dll`` to ``dllPath`` for 64-bit LabVIEW, or ``benhw32_cdecl.dll`` for 32-bit LabVIEW. Both are in the downloaded zip. * **Requires the .NET Framework 4.8 runtime.** * **Tokens are entered as numbers**, as before. Values are unchanged; see :doc:`tokens`.