open method

void open()

open can be called when handler is null or handler is closed

Implementation

void open() {
  /// Do not open a port which has been opened
  if (_isOpened == false) {
    handler = CreateFile(_portNameUtf16, GENERIC_READ | GENERIC_WRITE, 0,
        nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

    if (handler == INVALID_HANDLE_VALUE) {
      final lastError = GetLastError();
      if (lastError == ERROR_FILE_NOT_FOUND) {
        throw Exception(_portNameUtf16.toDartString() + "is not available");
      } else {
        throw Exception('Open port failed, error is $lastError');
      }
    }

    _setCommState();

    _setCommTimeouts();

    _isOpened = true;

    if (SetCommMask(handler!, EV_RXCHAR) == 0) {
      throw Exception('SetCommMask error');
    }
    _createEvent();
  } else {
    throw Exception('Port has been opened');
  }
}