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.digitalOutputCreate(pHandle), "Create");
    _handle = pHandle.value;

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

    if (deviceSerialNumber != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetDeviceSerialNumber(
              _handle!, deviceSerialNumber!),
          "SetSerial");
    }

    if (hubPort != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetChannel(_handle!, hubPort!), "SetHubPort");
    }
    if (_channel != null) {
      bindings.checkPhidgetError(
          bindings.phidgetSetChannel(_handle!, _channel!), "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');

    super.startListeningToShimEvents(_handle!);

    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(
              "Polling timed out waiting for Encoder attachment.");
        }
      });
    }
    _isAttached = true;
  } catch (e) {
    logger.e("Error during DigitalOutput.open: $e");
    Phidget.unregisterInstance(identityHashCode(this));
    if (_handle != null) {
      final pDelete = calloc<bindings.DigitalOutputHandle>();
      pDelete.value = _handle!;
      try {
        bindings.encoderDelete(pDelete);
      } catch (_) {}
      calloc.free(pDelete);
      _handle = null;
    }
  } finally {
    calloc.free(pHandle);
  }
}