Skip to content

LED does not turn off at the end of recording #77

@raqueladaia

Description

@raqueladaia

Hi,

I'm writing a script to control the miniscope v4 with Python.

I can do a video recording, turn on the LED and modify its brightness but at the end of the video recording I cannot switch off the LED.

This is the snippet to do the video recording and to switch off the LED. Maybe you see something I'm missing and you can enlighten me?

`

FUNCTIONS WITHIN SNIPPET

def apply_control(self, device_cfg: dict, name: str, prefer_display=None):
    controls = device_cfg.get("controlSettings", {})
    if name not in controls:
        return 0
    cfg = controls[name]
    i2cValue, i2cValue2, chosen = self._resolve_control_value(cfg, prefer_display)
    cmds = cfg.get("sendCommand", [])
    sent = 0
    for cmd in cmds:
        if str(cmd.get("protocol", "")).upper() != "I2C":
            continue
        self._send_i2c_block(cmd, i2c_value=i2cValue, i2c_value2=i2cValue2)
        sent += 1
    self._send_commands()
    # Show both the raw and LSB so you can see the effective byte the DAQ would send
    print(f"Applied control '{name}' with {sent} packet(s) "
          f"(chosen={chosen}, raw={i2cValue}, raw&0xFF={i2cValue & 0xFF}, i2cValue2={i2cValue2}).")
    return sent


def force_led_off(self, device_cfg: dict):
    """Force LED off by sending I2C commands directly with minimal value."""
    if not self.cam or not self.cam.isOpened():
        return False
        
    controls = device_cfg.get("controlSettings", {})
    if "led0" not in controls:
        return False
        
    led_cfg = controls["led0"]
    cmds = led_cfg.get("sendCommand", [])
    
    print("Force LED off: sending direct I2C commands...")
    
    # Try multiple approaches to turn off LED
    test_values = [0, 1, 10, 50, 100]  # Test different values
    
    for test_val in test_values:
        print(f"  Trying I2C value: {test_val}")
        
        # Send commands with this value
        for cmd in cmds:
            if str(cmd.get("protocol", "")).upper() == "I2C":
                self._send_i2c_block(cmd, i2c_value=test_val)
        
        self._send_commands()
        time.sleep(0.1)
    
    # Final attempt: try to send the exact negative value that should turn it off
    # Based on the scaling: display=0 -> i2c=-255
    print("  Final attempt: sending calculated negative value (-255)")
    for cmd in cmds:
        if str(cmd.get("protocol", "")).upper() == "I2C":
            self._send_i2c_block(cmd, i2c_value=-255)
    
    self._send_commands()
    time.sleep(0.2)
    
    print("Force LED off commands sent")
    return True

SNIPPET OF VIDEO RECORDING AND ATTEMPTING TO SWITCH OFF LED

try:
    while time.time() - t0 < dur_s:
        ok, frame = vc._grab_one()
        if not ok:
            print("Frame drop; attempting reconnect…")
            if not vc.attempt_reconnect():
                break
            continue

        if not json_color and frame.ndim == 3:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        writer.write(frame)

        ts_ms = int(time.time() * 1000)
        daq_counter = int(vc.cam.get(cv2.CAP_PROP_CONTRAST))
        timestamps.append((daq_counter, ts_ms))

        if vc.head_orientation_stream_state:
            bno = vc.extract_bno()
            if bno:
                bno_log.append((daq_counter, bno["w"], bno["x"], bno["y"], bno["z"]))
finally:
    vc.stop_recording_flag()
    writer.release()
    
    # Turn off LED after recording
    if "led0" in dev_cfg["controlSettings"]:
        print("Turning off LED after recording...")
        
        # Try multiple times to ensure LED is turned off
        for attempt in range(3):
            if vc.cam and vc.cam.isOpened():
                print(f"LED off attempt {attempt + 1}/3...")
                
                # First try: Force LED to 0 (off) with explicit control
                led_off_result = vc.apply_control(dev_cfg, "led0", prefer_display=0)
                print(f"LED off command result: {led_off_result} packets sent")
                
                # Add delay to ensure LED command is processed
                time.sleep(0.5)
                
                # Try alternative approach: use a high display value that should result in low I2C value
                print("Trying alternative: high display value for low I2C...")
                alt_result = vc.apply_control(dev_cfg, "led0", prefer_display=100)
                print(f"Alternative LED control result: {alt_result} packets sent")
                time.sleep(0.5)
                
                # Verify LED was set to 0 by checking the control value
                if hasattr(vc, '_resolve_control_value'):
                    try:
                        led_cfg = dev_cfg["controlSettings"]["led0"]
                        i2c_value, _, chosen = vc._resolve_control_value(led_cfg, prefer_display=0)
                        print(f"LED control verification: chosen={chosen}, i2c_value={i2c_value}")
                        
                        # If the calculated I2C value is negative, try sending it directly
                        if i2c_value < 0:
                            print(f"Warning: LED I2C value is negative ({i2c_value}), this might cause issues")
                    except Exception as e:
                        print(f"LED verification failed: {e}")
                
                # Second try: Try with a very low positive value (1) instead of 0
                if attempt == 1:
                    print("Trying LED off with value 1 instead of 0...")
                    vc.apply_control(dev_cfg, "led0", prefer_display=1)
                    time.sleep(0.3)
                
                # Third try: Use force LED off method
                if attempt == 2:
                    print("Final attempt: using force LED off method...")
                    vc.force_led_off(dev_cfg)
                    time.sleep(0.5)
            else:
                print("Camera not available for LED control")
                break`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions