ensureConnected method

Future<PosPrintResult> ensureConnected({
  1. Duration timeout = const Duration(seconds: 5),
})

Implementation

Future<PosPrintResult> ensureConnected(
    {Duration timeout = const Duration(seconds: 5)}) async {
  if (_connected) {
    return PosPrintResult.success;
  }

  try {
    var host = _host;
    var port = _port;

    if (host == null || port == null) {
      throw StateError("Call `connect` first to define `host` and `port`!");
    }

    _socket = await Socket.connect(host, port, timeout: timeout);
    _connected = true;

    _socket.listen(_addInputBytes);
    _socket.add(_generator.reset());

    return Future<PosPrintResult>.value(PosPrintResult.success);
  } catch (e) {
    return Future<PosPrintResult>.value(PosPrintResult.timeout);
  }
}