### Setup Python Environment Source: https://github.com/dino-lite/dnx64-python-api/blob/main/README.md Commands to create a virtual environment and install required dependencies. ```sh python3 -m venv .venv pip3 install -r requirements.txt ``` -------------------------------- ### Initialize DNX64 and Configure Device Source: https://github.com/dino-lite/dnx64-python-api/blob/main/README.md Example showing how to import the DNX64 module, initialize the class, and set basic camera parameters. ```py try: DNX64 = getattr(importlib.import_module("DNX64"), "DNX64") except ImportError as err: print("Error: ", err) # Initialize the DNX64 class dll_path = "/path/to/DNX64.dll" micro_scope = DNX64(dll_path) # Set Device Index first micro_scope.SetVideoDeviceIndex(0) # Get total number of video devices being detected device_count = micro_scope.GetVideoDeviceCount() print(f"Number of video devices: {device_count}") # NOTE: Buffer time for devices to set up properly time.sleep(0.1) # Set the auto-exposure target value for device 0 micro_scope.SetAETarget(0, 100) # NOTE: Buffer time for devices to set up properly time.sleep(0.1) # Set the exposure value for device 0 micro_scope.SetExposureValue(0, 1000) ``` -------------------------------- ### Initialize and Configure Microscope Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Basic setup sequence for loading the DLL, setting the device index, and querying the number of connected devices. ```python from DNX64 import DNX64 import time dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" microscope = DNX64(dll_path) microscope.SetVideoDeviceIndex(0) time.sleep(0.1) device_count = microscope.GetVideoDeviceCount() print(f"Devices detected: {device_count}") ``` -------------------------------- ### Initialize and Configure Dino-Lite Microscope Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Demonstrates the basic workflow of initializing the DNX64 library, selecting a device, and configuring exposure and LED settings. Requires the DNX64 SDK to be installed at the specified path. ```python from DNX64 import DNX64 import time # Initialize dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" microscope = DNX64(dll_path) # Set device and initialize microscope.SetVideoDeviceIndex(0) time.sleep(0.1) if not microscope.Init(): print("Failed to initialize") exit(1) time.sleep(0.1) # Use the device device_count = microscope.GetVideoDeviceCount() print(f"Devices found: {device_count}") # Configure exposure microscope.SetAutoExposure(0, 1) time.sleep(0.1) microscope.SetAETarget(0, 100) time.sleep(0.1) # Turn on LED microscope.SetLEDState(0, 1) time.sleep(0.1) ``` -------------------------------- ### Define standard installation path Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Sets the absolute path variable for the DNX64.dll library. ```python dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" ``` -------------------------------- ### Get WiFi Image Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Defines the method signature for capturing a single frame to a file. ```python def GetWiFiImage(self, filename: str) -> bool ``` -------------------------------- ### Get video device name Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the friendly name of the device at the specified index. ```python name = microscope.GetVideoDeviceName(0) print(f"Device: {name}") ``` -------------------------------- ### Define Method Signature Entry Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/types.md Example entry for the METHOD_SIGNATURES dictionary mapping method names to argument and return types. ```python "GetAETarget": ([ctypes.c_int], ctypes.c_long), ``` -------------------------------- ### Get Video Property Range and Validate Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Retrieves property constraints and validates values before applying them to prevent out-of-range errors. ```python index, min_val, max_val, step, default = microscope.GetVideoProcAmpValueRange(0) print(f"Property {index}:") print(f" Range: {min_val} to {max_val}") print(f" Step: {step}") print(f" Default: {default}") ``` ```python index, min_val, max_val, step, default = microscope.GetVideoProcAmpValueRange(0) desired_value = 100 if min_val <= desired_value <= max_val: microscope.SetVideoProcAmp(0, desired_value) else: print(f"Value {desired_value} is outside valid range [{min_val}, {max_val}]") # Use default or clamp value microscope.SetVideoProcAmp(0, default) ``` -------------------------------- ### Set eFLC Quadrant Values Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Examples for managing enhanced FLC, including turning off all quadrants, setting gradient brightness, and flashing a specific quadrant. ```python for quadrant in range(1, 5): microscope.SetEFLC(0, quadrant, 32) # 32 = off import time time.sleep(0.1) ``` ```python # Create a gradient effect across quadrants brightness_levels = [31, 24, 16, 8] for quadrant, brightness in enumerate(brightness_levels, 1): microscope.SetEFLC(0, quadrant, brightness) time.sleep(0.1) ``` ```python def flash_quadrant(microscope, device_index, quadrant): microscope.SetEFLC(device_index, quadrant, 32) # Off time.sleep(0.1) microscope.SetEFLC(device_index, quadrant, 31) # Full brightness time.sleep(0.2) microscope.SetEFLC(device_index, quadrant, 32) # Off flash_quadrant(microscope, 0, 1) ``` -------------------------------- ### Get total video device count Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the total number of connected video devices, including non-Dino-Lite webcams. ```python count = microscope.GetVideoDeviceCount() print(f"Devices found: {count}") ``` -------------------------------- ### Get Auto-Exposure Target Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the current auto-exposure brightness target value. ```python target = microscope.GetAETarget(0) print(f"AE target: {target}") ``` -------------------------------- ### Initialize Device and Configure Settings with Timing Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Demonstrates proper initialization and configuration of device settings using recommended sleep intervals to prevent command queue overflow. ```python import time from DNX64 import DNX64 dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" microscope = DNX64(dll_path) # Initialize with timing microscope.SetVideoDeviceIndex(0) time.sleep(0.1) if not microscope.Init(): exit(1) time.sleep(0.1) # Configure exposure with timing microscope.SetAutoExposure(0, 1) time.sleep(0.15) microscope.SetAETarget(0, 100) time.sleep(0.15) # Configure LED with timing microscope.SetLEDState(0, 1) time.sleep(0.15) microscope.SetLEDState(0, 0) time.sleep(0.15) print("All configurations complete") ``` -------------------------------- ### Get Auto-Exposure State Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the current auto-exposure status (0 for OFF, 1 for ON). ```python state = microscope.GetAutoExposure(0) print(f"Auto-exposure: {'ON' if state else 'OFF'}") ``` -------------------------------- ### Configure and Initialize Device Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Sets the device index and initializes the microscope. Requires a 0.1-second buffer after each configuration call. ```python from DNX64 import DNX64 import time microscope = DNX64("C:\\Program Files\\DNX64\\DNX64.dll") # Set device index FIRST microscope.SetVideoDeviceIndex(0) time.sleep(0.1) # Then initialize microscope.Init() time.sleep(0.1) # Then perform operations device_count = microscope.GetVideoDeviceCount() ``` -------------------------------- ### Get alternate device identifier Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the alternate ASCII device identifier for the specified index. ```python alt_id = microscope.GetDeviceIDA(0) ``` -------------------------------- ### Perform Robust Device Initialization Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Handles DLL loading, device verification, and error checking during the startup sequence. ```python import os import time from DNX64 import DNX64 def initialize_microscope(dll_path, device_idx=0): """Initialize with comprehensive error checking.""" # Step 1: Verify DLL exists if not os.path.exists(dll_path): raise FileNotFoundError(f"DLL not found: {dll_path}") # Step 2: Load DLL try: microscope = DNX64(dll_path) except OSError as e: raise RuntimeError(f"Failed to load DLL: {e}") # Step 3: Verify device exists count = microscope.GetVideoDeviceCount() if device_idx >= count: raise ValueError(f"Device {device_idx} not found (only {count} devices)") # Step 4: Set device index microscope.SetVideoDeviceIndex(device_idx) time.sleep(0.1) # Step 5: Initialize device try: if not microscope.Init(): raise RuntimeError("Device initialization returned False") except OSError as e: if e.winerror == -529697949: raise RuntimeError("Microscope not connected") raise RuntimeError(f"Device initialization failed: {e}") time.sleep(0.1) return microscope # Usage try: microscope = initialize_microscope("C:\\Program Files\\DNX64\\DNX64.dll", 0) except (FileNotFoundError, RuntimeError, ValueError) as e: print(f"Error: {e}") exit(1) ``` -------------------------------- ### Get unique device identifier Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the unique Unicode device identifier for the specified index. ```python device_id = microscope.GetDeviceId(0) print(f"ID: {device_id}") ``` -------------------------------- ### Init() Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Initializes the selected device for operation. This must be called after setting the device index and before any further Get/Set operations. ```APIDOC ## Init() ### Description Initializes the selected device for operation. This method is required before any Get or Set operations are performed. ### Returns - **bool** - True if initialization was successful, False if the device is not ready. ``` -------------------------------- ### Get current video device index Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the index of the currently selected video device. ```python current = microscope.GetVideoDeviceIndex() print(f"Active device: {current}") ``` -------------------------------- ### Initialize Device with Error Handling Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Initializes the device and checks the boolean return value to ensure the device is ready for operation. ```python from DNX64 import DNX64 import time microscope = DNX64("C:\\Program Files\\DNX64\\DNX64.dll") microscope.SetVideoDeviceIndex(0) time.sleep(0.1) if not microscope.Init(): print("Error: Failed to initialize device") exit(1) time.sleep(0.1) print("Device ready") ``` -------------------------------- ### DNX64.__init__ Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Initializes the DNX64 class instance by loading the required DNX64.dll library from the specified file path. ```APIDOC ## DNX64.__init__(dll_path: str) ### Description Initializes the DNX64 class by loading the DNX64.dll library using ctypes. This method must be called to establish a connection to the microscope hardware. ### Parameters - **dll_path** (str) - Required - Absolute path to the DNX64.dll library file. ### Returns - **None** - Initializes the instance. ### Throws - **OSError** - Raised if the DLL file cannot be found or loaded. ### Example ```python from DNX64 import DNX64 dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" microscope = DNX64(dll_path) ``` ``` -------------------------------- ### Get AE Target Value Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Retrieves the current AE target value used when auto-exposure is enabled. ```python ae_target = microscope.GetAETarget(0) print(f"AE target: {ae_target}") ``` -------------------------------- ### Get Manual Exposure Value Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the current manual exposure setting. Only valid when auto-exposure is disabled. ```python exposure = microscope.GetExposureValue(0) print(f"Exposure: {exposure}") ``` -------------------------------- ### Handle DNX64 initialization and errors Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates proper initialization of the DNX64 microscope with required buffer times and specific exception handling for common hardware and file system errors. ```python try: microscope = DNX64("C:\\Program Files\\DNX64\\DNX64.dll") microscope.SetVideoDeviceIndex(0) time.sleep(0.1) if not microscope.Init(): print("Device init failed") except FileNotFoundError: print("DLL not found") except OSError as e: if e.winerror == -529697949: print("Microscope not connected") else: print(f"OS error: {e}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Get Video Processing Property Value Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the current value for a specific video processing property index. ```python brightness = microscope.GetVideoProcAmp(0) ``` -------------------------------- ### Initialize DNX64 Control Object Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Perform basic initialization and verify device connection status. ```python from DNX64 import DNX64 microscope = DNX64("C:\\Program Files\\DNX64\\DNX64.dll") if microscope.Init(): print("Initialization successful") else: print("Initialization failed - check device connection") ``` ```python if not microscope.Init(): print("Error: Microscope is not connected") exit(1) ``` -------------------------------- ### Get FOV for Standard Magnification Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Calculates the field of view for a specific magnification level and converts the result from micrometers to millimeters. ```python fov_um = microscope.FOVx(0, 50.0) fov_mm = fov_um / 1000 # Convert to millimeters print(f"FOV at 50x: {fov_mm} mm") ``` -------------------------------- ### Discover and Configure Devices Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Retrieves device counts, lists available devices, and fetches configuration settings. ```python # Get device count count = microscope.GetVideoDeviceCount() # List all devices for i in range(count): name = microscope.GetVideoDeviceName(i) device_id = microscope.GetDeviceId(i) print(f"{i}: {name} (ID: {device_id})") # Get current device index current = microscope.GetVideoDeviceIndex() # Get device configuration (feature availability) config = microscope.GetConfig(0) ``` -------------------------------- ### DNX64.Init Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Initializes the control object. This method must be called before performing any device operations. ```APIDOC ## DNX64.Init ### Description Initializes the control object. Must be called before performing any device operations. ### Signature `def Init(self) -> bool` ### Returns - **bool** - True if initialization successful, False otherwise. ### Exceptions - **OSError** - Thrown with winerror code -529697949 if no microscope is connected. ``` -------------------------------- ### Get device configuration bitmask Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves a hexadecimal bitmask representing the device's available features, such as EDOF or AMR. ```python config = microscope.GetConfig(0) has_edof = (config & 0x80) == 0x80 print(f"EDOF available: {has_edof}") ``` -------------------------------- ### Initialize Device Control Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Call Init to prepare the device for operations; a 0.1s buffer is required after this call. ```python if microscope.Init(): print("Device ready") else: print("Initialization failed") ``` -------------------------------- ### Initialize Microscope Safely Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Perform robust initialization by validating the DLL path, checking device availability, and handling potential runtime errors. ```python import os import time from DNX64 import DNX64 def init_microscope(dll_path, device_idx=0): """Initialize microscope safely.""" if not os.path.exists(dll_path): raise FileNotFoundError(f"DLL not found: {dll_path}") try: microscope = DNX64(dll_path) except OSError as e: raise RuntimeError(f"Failed to load DLL: {e}") # Verify device exists count = microscope.GetVideoDeviceCount() if device_idx >= count: raise ValueError(f"Device {device_idx} not found (only {count} devices)") # Set and initialize microscope.SetVideoDeviceIndex(device_idx) time.sleep(0.1) if not microscope.Init(): raise RuntimeError("Device initialization failed") time.sleep(0.1) return microscope # Usage try: microscope = init_microscope("C:\\Program Files\\DNX64\\DNX64.dll", 0) except (FileNotFoundError, RuntimeError, ValueError) as e: print(f"Error: {e}") exit(1) ``` -------------------------------- ### Apply Configuration Profiles Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Encapsulate device settings into a class to simplify applying multiple parameters at once. ```python class Config: def __init__(self): self.auto_exposure = True self.ae_target = 100 self.led_state = 1 self.flc_level = 3 def apply(self, microscope, device_idx=0): import time if self.auto_exposure: microscope.SetAutoExposure(device_idx, 1) time.sleep(0.1) microscope.SetAETarget(device_idx, self.ae_target) else: microscope.SetAutoExposure(device_idx, 0) time.sleep(0.1) time.sleep(0.1) microscope.SetLEDState(device_idx, self.led_state) time.sleep(0.1) config = Config() config.apply(microscope) ``` -------------------------------- ### Get Video Processing Property Range Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Retrieves the valid range, step size, and default value for a video processing property. ```python index, min_val, max_val, step, default = microscope.GetVideoProcAmpValueRange(0) print(f"Range: {min_val}-{max_val}, step: {step}") ``` -------------------------------- ### Initialize DNX64 Device Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Standard workflow for initializing the microscope, setting the device index, and verifying device connectivity and features. ```python from DNX64 import DNX64 import time # Initialize dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" microscope = DNX64(dll_path) # Set device index early microscope.SetVideoDeviceIndex(0) time.sleep(0.1) # Initialize control object if not microscope.Init(): print("Failed to initialize") exit(1) # Check device count device_count = microscope.GetVideoDeviceCount() print(f"Devices found: {device_count}") # Get device information device_name = microscope.GetVideoDeviceName(0) device_id = microscope.GetDeviceId(0) print(f"Device: {device_name} (ID: {device_id})") # Check available features config = microscope.GetConfig(0) has_amr = (config & 0x40) == 0x40 has_edof = (config & 0x80) == 0x80 print(f"Features - AMR: {has_amr}, EDOF: {has_edof}") ``` -------------------------------- ### Initialize DNX64 Instance Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Instantiate the DNX64 class by providing the absolute path to the DNX64.dll library. ```python from DNX64 import DNX64 microscope = DNX64("C:\\Program Files\\DNX64\\DNX64.dll") ``` -------------------------------- ### Implement Robust Error Handling for DNX64 Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/errors.md Demonstrates a comprehensive approach to initializing the microscope, including file verification, device index validation, and specific exception handling for hardware connectivity. ```python import os import time from DNX64 import DNX64 def initialize_microscope(dll_path, device_index=0): """Initialize microscope with comprehensive error handling.""" # Step 1: Verify DLL exists if not os.path.exists(dll_path): raise FileNotFoundError(f"DNX64.dll not found at {dll_path}") # Step 2: Load DLL try: microscope = DNX64(dll_path) except OSError as e: raise RuntimeError(f"Failed to load DNX64.dll: {e}") # Step 3: Set device index device_count = microscope.GetVideoDeviceCount() if device_index >= device_count: raise ValueError(f"Device index {device_index} out of range (0-{device_count-1})") microscope.SetVideoDeviceIndex(device_index) time.sleep(0.1) # Step 4: Initialize device try: if not microscope.Init(): raise RuntimeError("Device initialization returned False") except OSError as e: if e.winerror == -529697949: raise RuntimeError("Microscope device not connected") else: raise RuntimeError(f"Device initialization failed: {e}") # Step 5: Verify device is responsive device_name = microscope.GetVideoDeviceName(device_index) if not device_name: raise RuntimeError("Device not responding to queries") print(f"Successfully initialized {device_name}") return microscope def safe_get_resolution_for_wifi(microscope): """Safely retrieve WiFi video capabilities.""" try: count, resolutions = microscope.GetWiFiVideoCaps() return count, resolutions except Exception as e: print(f"Failed to retrieve WiFi capabilities: {e}") return 0, [] def safe_set_exposure(microscope, device_index, exposure_value): """Set exposure with validation.""" try: # Disable auto-exposure first microscope.SetAutoExposure(device_index, 0) time.sleep(0.1) # Set manual exposure microscope.SetExposureValue(device_index, exposure_value) time.sleep(0.1) # Read back to verify actual = microscope.GetExposureValue(device_index) if actual == exposure_value: print(f"Exposure set successfully to {exposure_value}") else: print(f"Warning: Requested {exposure_value}, got {actual}") except Exception as e: print(f"Failed to set exposure: {e}") # Usage try: microscope = initialize_microscope("C:\\Program Files\\DNX64\\DNX64.dll", 0) safe_set_exposure(microscope, 0, 1000) except (FileNotFoundError, RuntimeError, ValueError) as e: print(f"Error: {e}") exit(1) ``` -------------------------------- ### Initialize DNX64 Microscope Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Initializes the microscope instance using the DLL path and sets the video device index. ```python from DNX64 import DNX64 import time # Create instance microscope = DNX64("C:\\Program Files\\DNX64\\DNX64.dll") # Set device index first microscope.SetVideoDeviceIndex(0) time.sleep(0.1) # Initialize if not microscope.Init(): exit(1) time.sleep(0.1) ``` -------------------------------- ### DNX64(dll_path: str) Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Initializes the DNX64 microscope interface by loading the required DLL library. ```APIDOC ## DNX64(dll_path: str) ### Description Initializes the DNX64 class. This constructor requires the absolute path to the DNX64.dll library file to establish communication with the hardware. ### Parameters - **dll_path** (str) - Required - The absolute file path to the DNX64.dll library file. ### Example Initialization ```python from DNX64 import DNX64 dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" microscope = DNX64(dll_path) ``` ``` -------------------------------- ### Init() Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Initializes the control object and the connected microscope device. This must be called before most other operations. ```APIDOC ## Init() ### Description Initializes the control object and device. A 0.1s buffer is required after calling this method. ### Returns - **bool** - True if initialization was successful, False otherwise. ### Throws - **OSError** - Thrown if initialization fails. ``` -------------------------------- ### Create and Apply Configuration Profiles Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Encapsulates microscope settings into a class to simplify applying multiple parameters at once. Includes necessary time delays between API calls to ensure stability. ```python class MicroscopeConfig: def __init__(self): self.auto_exposure = True self.ae_target = 100 self.exposure_value = 1000 self.led_state = 1 self.flc_level = 3 self.apl_level = 2 self.axi_level = 4 def apply(self, microscope, device_index=0): import time if self.auto_exposure: microscope.SetAutoExposure(device_index, 1) time.sleep(0.1) microscope.SetAETarget(device_index, self.ae_target) else: microscope.SetAutoExposure(device_index, 0) time.sleep(0.1) microscope.SetExposureValue(device_index, self.exposure_value) time.sleep(0.1) microscope.SetLEDState(device_index, self.led_state) time.sleep(0.1) # Usage config = MicroscopeConfig() config.apply(microscope) ``` -------------------------------- ### DNX64 Constructor Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/API_INDEX.md Initializes the main wrapper class for interacting with the DNX64.dll library. ```APIDOC ## DNX64(dll_path: str) ### Description Creates a new instance of the DNX64 wrapper class to interact with the microscope device. ### Parameters - **dll_path** (str) - Required - The absolute path to the DNX64.dll file. ### Returns - **DNX64 instance** (object) - An instance of the DNX64 class. ``` -------------------------------- ### Initialize DNX64 Constructor Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Constructor signature for initializing the DNX64 class with the required DLL path. ```python def __init__(self, dll_path: str) -> None ``` -------------------------------- ### Verify Exposure Settings Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Set a parameter and immediately read it back to confirm the hardware accepted the change. ```python import time def set_exposure_verified(microscope, device_idx, value): """Set exposure and verify.""" microscope.SetAutoExposure(device_idx, 0) time.sleep(0.1) microscope.SetExposureValue(device_idx, value) time.sleep(0.1) actual = microscope.GetExposureValue(device_idx) if actual == value: print(f"✓ Exposure set to {value}") else: print(f"✗ Requested {value}, got {actual}") ``` -------------------------------- ### Configure Device Settings Programmatically Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Encapsulates device settings into a class to manage state and apply updates to the microscope. ```python class DeviceConfig: def __init__(self): self.auto_exposure = True self.ae_target = 100 self.led_on = True self.flc_level = 3 def apply(self, microscope, device_idx=0): import time if self.auto_exposure: microscope.SetAutoExposure(device_idx, 1) time.sleep(0.1) microscope.SetAETarget(device_idx, self.ae_target) else: microscope.SetAutoExposure(device_idx, 0) time.sleep(0.1) time.sleep(0.1) microscope.SetLEDState(device_idx, 1 if self.led_on else 0) time.sleep(0.1) config = DeviceConfig() config.apply(microscope) ``` -------------------------------- ### Get/SetVideoProcAmp() Source: https://github.com/dino-lite/dnx64-python-api/wiki/Appendix:-Parameter-Table Provides the index mapping for video processing amplifier properties. ```APIDOC ## Get/SetVideoProcAmp() ### Description Maps integer values to specific video processing properties for adjustment. ### Parameters - **0** - Brightness - **1** - Contrast - **2** - Hue - **3** - Saturation - **4** - Sharpness - **5** - Gamma - **6** - ColorEnable - **7** - WhiteBalance - **8** - BacklightCompensation - **9** - Gain ``` -------------------------------- ### Handle Microscope Initialization Errors Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/types.md Demonstrates catching OSError with specific winerror codes to identify connection issues during Init(). ```python try: result = microscope.Init() if not result: print("Init returned False - device may not be ready") except OSError as e: if e.winerror == -529697949: print("Error: No microscope connected") else: print(f"Unexpected OS error: {e}") ``` -------------------------------- ### Toggle LED State Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Demonstrates turning the LED off and on with a short delay between states. Requires an active camera preview. ```python # Assuming camera preview is running microscope.SetLEDState(0, 0) # LED off import time time.sleep(0.1) microscope.SetLEDState(0, 1) # LED on time.sleep(0.1) ``` -------------------------------- ### Handle Initialization Errors Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Wraps the DNX64 class instantiation in a try-except block to catch DLL loading and initialization failures. ```python try: microscope = DNX64(dll_path) except FileNotFoundError: print("DLL not found") exit(1) except OSError as e: print(f"Failed to load DLL: {e}") exit(1) ``` -------------------------------- ### Configure WiFi Streaming Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Select the WiFi device, query supported resolutions, and capture images from the stream. ```python import time # Select WiFi Streamer microscope.SetVideoDeviceIndex(90) time.sleep(0.1) # Get supported resolutions try: count, resolutions = microscope.GetWiFiVideoCaps() print(f"Resolutions: {resolutions}") # Set resolution w, h = resolutions[0] microscope.SetWiFiVideoRes(w, h) time.sleep(0.1) # Capture image if microscope.GetWiFiImage("capture.jpg"): print("Image saved") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Configure device settings with integers Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/types.md Integers represent device indices, configuration levels, and state flags. ```python microscope.SetAETarget(0, 18) # int device_index, int ae_target microscope.SetFLCLevel(0, 3) # int device_index, int flc_level count = microscope.GetVideoDeviceCount() # returns int ``` -------------------------------- ### Check DNX64 API Version Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Execute this command to verify the version of the DNX64 library currently in use. ```bash python3 version.py ``` -------------------------------- ### DNX64.SetLEDState Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Sets the LED state for a specified device. Requires an active camera preview. ```APIDOC ## DNX64.SetLEDState ### Description Sets the LED state for the specified device. The camera preview must be established for this to work on most devices. ### Parameters - **device_index** (int) - Required - Zero-based index of the device. - **led_state** (int) - Required - LED state value to set. ### Returns - None ### Limitations Not applicable to AM211, AM2011, and Dino-Eye series. Requires active camera preview. ``` -------------------------------- ### Implement Timing and Buffering Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Ensures device stability by adding mandatory delays after initialization, device selection, and configuration commands. ```python import time # Always add buffer after setting device index microscope.SetVideoDeviceIndex(0) time.sleep(0.1) # Always add buffer after Init() if microscope.Init(): time.sleep(0.1) # Always add buffer after Set* methods microscope.SetExposureValue(0, 1000) time.sleep(0.1) # When issuing multiple commands in sequence microscope.SetAutoExposure(0, 1) time.sleep(0.15) microscope.SetAETarget(0, 100) time.sleep(0.15) ``` -------------------------------- ### Initialize DNX64 microscope object Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Instantiates the DNX64 class using the provided DLL path. ```python from DNX64 import DNX64 dll_path = "C:\\Program Files\\DNX64\\DNX64.dll" microscope = DNX64(dll_path) print("Microscope object created successfully") ``` -------------------------------- ### Implement Persistent Configuration Logging Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Saves and loads device settings to a JSON file, allowing for state restoration across sessions. ```python import json import time def save_configuration(microscope, filename, device_index=0): """Save current device configuration to file.""" config = { 'timestamp': time.strftime("%Y-%m-%d %H:%M:%S"), 'auto_exposure': microscope.GetAutoExposure(device_index), 'ae_target': microscope.GetAETarget(device_index), 'exposure': microscope.GetExposureValue(device_index), 'device_id': microscope.GetDeviceId(device_index), } with open(filename, 'w') as f: json.dump(config, f, indent=2) def load_configuration(microscope, filename, device_index=0): """Load and apply configuration from file.""" import time with open(filename, 'r') as f: config = json.load(f) microscope.SetAutoExposure(device_index, config['auto_exposure']) time.sleep(0.1) microscope.SetAETarget(device_index, config['ae_target']) time.sleep(0.1) microscope.SetExposureValue(device_index, config['exposure']) time.sleep(0.1) # Usage save_configuration(microscope, "device_config.json") load_configuration(microscope, "device_config.json") ``` -------------------------------- ### Handle Initialization OSError Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/errors.md Use this pattern to catch specific WinError codes during the Init() method call, particularly for device connection issues. ```python try: result = microscope.Init() if not result: print("Init returned False - check device connection") except OSError as e: if e.winerror == -529697949: print("Error: Microscope is not connected or not recognized") print("Possible solutions:") print(" 1. Check USB cable connection") print(" 2. Verify device drivers are installed") print(" 3. Check Device Manager for unknown devices") else: print(f"Unexpected OS error: {e}") ``` -------------------------------- ### List WiFi Resolutions Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Iterates through and prints all supported video resolutions returned by the device. ```python try: count, resolutions = microscope.GetWiFiVideoCaps() print(f"Supported resolutions ({count} total):") for width, height in resolutions: print(f" {width}x{height}") except Exception as e: print(f"Failed to retrieve WiFi capabilities: {e}") ``` -------------------------------- ### Acquire video frames with OpenCV Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Initializes the DNX64 microscope and streams video frames using OpenCV. Requires the DNX64 DLL path and a valid device index. ```python from DNX64 import DNX64 import cv2 import time microscope = DNX64("C:\\Program Files\\DNX64\\DNX64.dll") microscope.SetVideoDeviceIndex(0) time.sleep(0.1) if not microscope.Init(): exit(1) time.sleep(0.1) # Acquire video frames cap = cv2.VideoCapture(0) while cap.isOpened(): ret, frame = cap.read() if ret: cv2.imshow("Microscope", frame) if cv2.waitKey(1) & 0xFF == 27: # ESC to exit break cap.release() cv2.destroyAllWindows() ``` -------------------------------- ### Adjust Focus (EDOF) Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Initializes the lens and sets coarse and fine focus positions within hardware limits if EDOF is supported. ```python import time if (config & 0x80) == 0x80: # Initialize lens microscope.SetLensInitPos(0) time.sleep(0.1) # Get position limits upper, lower = microscope.GetLensPosLimits(0) # Set coarse position middle = (upper + lower) // 2 microscope.SetLensPos(0, middle) time.sleep(0.1) # Get fine position limits upper_f, lower_f = microscope.GetLensFinePosLimits(0) # Set fine position middle_f = (upper_f + lower_f) // 2 microscope.SetLensFinePos(0, middle_f) time.sleep(0.1) ``` -------------------------------- ### Handle Generic Windows OS Errors Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/errors.md Catch and inspect generic Windows OS errors encountered during DLL initialization. ```python try: result = microscope.Init() except OSError as e: print(f"OS Error Code: {e.winerror}") print(f"Description: {e}") # Consult Windows error code documentation for specific codes ``` -------------------------------- ### LED Configuration Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Method to control the LED state of the device. ```APIDOC ## SetLEDState(device_id, state) ### Description Sets the LED state for the device. Requires active camera preview. ### Parameters - **device_id** (int) - Required - Device identifier - **state** (int) - Required - LED state (0 for OFF) ``` -------------------------------- ### Retrieve Video Device Name Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/api-reference/dnx64_class.md Iterate through available devices to print their friendly names. ```python for i in range(microscope.GetVideoDeviceCount()): name = microscope.GetVideoDeviceName(i) print(f"Device {i}: {name}") ``` -------------------------------- ### Display File Structure Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/INDEX.md Visual representation of the documentation directory structure. ```text output/ ├── README.md ← Start here ├── QUICK_REFERENCE.md ← Copy-paste examples ├── API_INDEX.md ← Method navigation ├── INDEX.md ← This file ├── api-reference/ │ └── dnx64_class.md ← Complete method docs (40KB) ├── types.md ← Type definitions ├── errors.md ← Error reference └── configuration.md ← Setup & config ``` -------------------------------- ### Handle WiFi Video Resolution Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/types.md Retrieves supported resolutions as tuples and sets the video resolution using width and height integers. ```python # Resolution from capabilities count, resolutions = microscope.GetWiFiVideoCaps() resolution = resolutions[0] # Tuple[int, int] width, height = resolution # Setting resolution microscope.SetWiFiVideoRes(1280, 1024) # width: int, height: int ``` -------------------------------- ### Enumerate and Select Multiple Devices Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Iterates through available devices to identify and select a specific camera index. ```python # Discover devices device_count = microscope.GetVideoDeviceCount() print(f"Found {device_count} devices:") for i in range(device_count): microscope.SetVideoDeviceIndex(i) time.sleep(0.1) name = microscope.GetVideoDeviceName(i) print(f" {i}: {name}") # Select desired device selected_index = 0 # User selects microscope.SetVideoDeviceIndex(selected_index) time.sleep(0.1) ``` -------------------------------- ### DNX64 Module Directory Structure Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Visual representation of the project file hierarchy and class organization. ```text DNX64/ ├── __init__.py # Main module with DNX64 class │ ├── METHOD_SIGNATURES dict # ctypes function signatures │ ├── VID_POINTERS constant # Array size for video ops │ ├── VID_PARAMS constant # Parameter count │ └── DNX64 class │ ├── __init__() # Constructor │ ├── setup() # Initialize function signatures │ ├── Device Discovery methods │ ├── Exposure Control methods │ ├── Video Processing methods │ ├── Optical Properties methods │ ├── Lighting Control methods │ ├── Focus Control methods │ ├── Feature-Specific methods │ ├── Event Handling methods │ └── WiFi Streaming methods ├── version.py # DLL version checker utility └── examples/ ├── simple_usb_preview_window.py ├── usb_streamer.py ├── wifi_streamer.py └── simple_wifi_preview_window.html ``` -------------------------------- ### Verify device features before method calls Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/errors.md Check device configuration bits using GetConfig() to ensure specific features like AMR, EDOF, or FLC are supported before execution. ```python config = microscope.GetConfig(0) # Before GetAMR() if not (config & 0x40): print("Device does not support AMR") return # Before EDOF methods if not (config & 0x80): print("Device does not support EDOF") return # Before FLC methods if not (config & 0x02): print("Device does not support FLC") return ``` -------------------------------- ### Configure Focus Control (EDOF) Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/configuration.md Initializes the lens and adjusts coarse and fine focus positions if the EDOF feature (config bit 0x80) is available. ```python import time config = microscope.GetConfig(0) if not (config & 0x80): print("Device does not support EDOF") else: # Initialize lens microscope.SetLensInitPos(0) time.sleep(0.1) # Get position limits upper, lower = microscope.GetLensPosLimits(0) print(f"Lens position range: {lower} to {upper}") # Set lens to middle position middle_pos = (upper + lower) // 2 microscope.SetLensPos(0, middle_pos) time.sleep(0.1) # Fine-tune around that position upper_fine, lower_fine = microscope.GetLensFinePosLimits(0) middle_fine = (upper_fine + lower_fine) // 2 microscope.SetLensFinePos(0, middle_fine) time.sleep(0.1) ``` -------------------------------- ### Manage Video Properties Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/QUICK_REFERENCE.md Retrieve property ranges, current values, and update settings for video processing amplifiers. ```python import time # Get property range index, min_val, max_val, step, default = microscope.GetVideoProcAmpValueRange(0) print(f"Range: {min_val}-{max_val}, step: {step}, default: {default}") # Get current value value = microscope.GetVideoProcAmp(0) # Set new value microscope.SetVideoProcAmp(0, 128) time.sleep(0.1) ``` -------------------------------- ### Validate device index and check return values Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/errors.md Validates the device index and checks for zero-value returns which may indicate a device readiness issue. ```python # Validate device index first device_count = microscope.GetVideoDeviceCount() if device_index >= device_count: print(f"Device index {device_index} out of range") return # Call methods value = microscope.GetExposureValue(device_index) if value == 0: print("Warning: Received zero value - device may not be ready") ``` -------------------------------- ### Configure exposure settings Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Toggles between auto-exposure and manual exposure modes. Ensure sufficient sleep time between configuration calls to allow hardware updates. ```python # Enable auto-exposure with moderate target microscope.SetAutoExposure(0, 1) time.sleep(0.1) microscope.SetAETarget(0, 100) time.sleep(0.1) # Later: switch to manual for fixed exposure microscope.SetAutoExposure(0, 0) time.sleep(0.1) microscope.SetExposureValue(0, 2000) time.sleep(0.1) # Verify the setting ae_enabled = microscope.GetAutoExposure(0) exposure = microscope.GetExposureValue(0) print(f"Auto: {ae_enabled}, Exposure: {exposure}") ``` -------------------------------- ### Select Video Device Index Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/README.md Sets the active video device index. Use index 0 for standard USB cameras and 90 for WiFi Streamer devices. ```python microscope.SetVideoDeviceIndex(0) # First device time.sleep(0.1) ``` ```python microscope.SetVideoDeviceIndex(90) # WiFi Streamer time.sleep(0.1) ``` -------------------------------- ### Dino-Lite API Methods Source: https://github.com/dino-lite/dnx64-python-api/blob/main/_autodocs/types.md A collection of methods available in the dnx64-python-api for device control and status retrieval. ```APIDOC ## Dino-Lite API Methods ### Methods - **Init()** (bool) - Initializes the device. Returns False if device not found. - **EnableMicroTouch()** (bool) - Enables the MicroTouch feature. - **GetVideoDeviceCount()** (int) - Returns the total number of detected devices. - **GetVideoDeviceIndex()** (int) - Returns the index of the currently active device. - **GetVideoDeviceName()** (str) - Returns the friendly name of the device. - **GetDeviceId()** (str) - Returns the unique device identifier. - **GetDeviceIDA()** (str) - Returns the alternate device identifier. - **GetConfig()** (int) - Returns a bitmask of device features. - **GetAutoExposure()** (int) - Returns the auto exposure state (0=OFF, 1=ON). - **GetAETarget()** (int) - Returns the brightness target for auto exposure. - **GetExposureValue()** (int) - Returns the current exposure value. - **FOVx()** (float) - Returns the field of view in micrometers. - **GetAMR()** (float) - Returns the automatic magnification reading. - **GetVideoProcAmp()** (int) - Returns the video property value. - **GetVideoProcAmpValueRange()** (Tuple[int,int,int,int,int]) - Returns (index, min, max, step, default) for video properties. - **GetLensPosLimits()** (Tuple[int,int]) - Returns (upper, lower) lens position limits. - **GetLensFinePosLimits()** (Tuple[int,int]) - Returns (upper, lower) fine lens position limits. - **GetWiFiVideoCaps()** (Tuple[int, List[Tuple[int,int]]]) - Returns (count, resolutions) for WiFi video capabilities. - **GetWiFiImage()** (bool) - Captures and saves a WiFi image. Returns True if successful. - **SetWiFiVideoRes()** (bool) - Sets the WiFi video resolution. Returns True if successful. ```