send method

Future<void> send(
  1. List<int> data, {
  2. Completer<List<int>>? responseCompleter,
  3. Duration? responseTimeout,
})

Send the specified message and return a Future that completes when the message is acknowledged or completes with an error if the message is canceled or corrupted.

Implementation

Future<void> send(List<int> data,
    {Completer<List<int>>? responseCompleter, Duration? responseTimeout}) {
  if (data == null || data.isEmpty) _error('invalid data');
  if (responseCompleter != null && responseTimeout == null)
    _error('must specify responseTimeout with responseCompleter');
  if (_sendCompleter != null) _error('only one send at a time');
  if (_responseCompleter != null) _error('only one send/response at a time');

  _logFiner('==>', data, 'REQ');
  _sendData(data);
  _sendCompleter = Completer<void>();
  _responseCompleter = responseCompleter;

  // From section 6.2.2 of the Serial API Host Appl. Prg. Guide
  // Data frame sender timeout is 1600 ms
  return _sendCompleter!.future.timeout(sendTimeout, onTimeout: () {
    _logger.warning('send timeout $data');
    _sendCompleter = null;
    _responseCompleter = null;
    throw ZwException.sendTimeout;
  }).then((_) {
    _sendCompleter = null;
    if (_responseCompleter != null && responseTimeout != null) {
      _responseTimer = Timer(responseTimeout, () {
        _logger.warning('response timeout $data');
        _responseCompleter!.completeError(ZwException.responseTimeout);
        _responseCompleter = null;
        _responseTimer = null;
      });
    }
  });
}