open method

  1. @override
Future<void> open()
override

Implementation

@override
Future<void> open() async {
  if (_handle != null) return;

  final pHandle = calloc<bindings.VoltageInputHandle>();
  try {
    bindings.checkPhidgetError(
        bindings.voltageInputCreate(pHandle), 'VoltageInput.create');
    _handle = pHandle.value;

    final int instanceId = identityHashCode(this);
    Phidget.registerInstance(instanceId, this);

    if (deviceSerialNumber != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetDeviceSerialNumber(
              _handle!, deviceSerialNumber!),
          'setDeviceSerialNumber');
    }
    if (hubPort != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetHubPort(_handle!, hubPort!), 'setHubPort');
    }

    bindings.checkPhidgetError(
        bindings.setAttachHandlerShim(_handle!), 'set_attach_handler_shim');
    bindings.checkPhidgetError(
        bindings.setDetachHandlerShim(_handle!), 'set_detach_handler_shim');
    bindings.checkPhidgetError(
        bindings.setErrorHandlerShim(_handle!), 'set_error_handler_shim');

    int openResult =
        bindings.phidgetOpenWaitForAttachment(_handle!, openTimeoutMs);
    bindings.checkPhidgetError(openResult, 'Phidget_openWaitForAttachment');

    final pIsAttached = calloc<Int32>();
    try {
      bindings.phidgetGetAttached(_handle!, pIsAttached);
      if (pIsAttached.value == 1) {
        super.internalProcessAttach();
      }
    } finally {
      calloc.free(pIsAttached);
    }

    if (isAttached) {
      if (!attachCompleter.isCompleted) {
        attachCompleter.complete();
      }
    } else {
      await attachCompleter.future.timeout(
          Duration(milliseconds: openTimeoutMs + 500), onTimeout: () {
        if (!isAttached) {
          throw TimeoutException(
              'Timed out waiting for device attachment after Phidget_openWaitForAttachment returned.');
        }
        return;
      });
    }
  } catch (e) {
    logger.e('Error during VoltageInput.open: $e');
    Phidget.unregisterInstance(identityHashCode(this));
    if (_handle != null) {
      _handle = null;
    }
    rethrow;
  } finally {
    calloc.free(pHandle);
  }
}