open method

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

Implementation

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

  final pHandle = calloc<bindings.PhidgetHandle>();
  try {
    bindings.checkPhidgetError(
        bindings.digitalInputCreate(pHandle), 'DigitalInput_create');
    _handle = pHandle.value;
    // The super._internalHandle is set via super._startListeningToShimEvents(_handle!)
    Phidget.registerInstance(identityHashCode(this), this);

    if (deviceSerialNumber != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetDeviceSerialNumber(
              _handle!, deviceSerialNumber!),
          'Phidget_setDeviceSerialNumber');
    }
    if (hubPort != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetHubPort(_handle!, hubPort!),
          'Phidget_setHubPort');
    }
    if (_channel != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetChannel(_handle!, _channel!),
          'Phidget_setChannel');
    }

    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');
    bindings.checkPhidgetError(bindings.setDiStateChangeHandlerShim(_handle!),
        'set_di_state_change_handler_shim');

    super.startListeningToShimEvents(_handle!);
    _listenForDigitalInputShimEvents();

    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 DigitalInput attachment');
        }
      });
    }
  } catch (e) {
    Phidget.unregisterInstance(identityHashCode(this));
    if (_handle != null) {
      final pDelete = calloc<bindings.DigitalInputHandle>();
      pDelete.value = _handle!;
      try {
        bindings.digitalInputDelete(pDelete);
      } catch (_) {
      } finally {
        calloc.free(pDelete);
      }
      _handle = null;
      // No need to access super._internalHandle here
    }
    rethrow;
  } finally {
    calloc.free(pHandle);
  }
}