connect method

Future<bool> connect(
  1. ArtemisAcpsDeviceConfig config
)

Implementation

Future<bool> connect(ArtemisAcpsDeviceConfig config) async {
  log("connect as reader");
  bool response = true;
  _config = config;

  if (_connectAddress == config.getUrl) {
    response = true;
  }

  try {
    final defaultHeaders = MessageHeaders();
    await disconnect();

    String url = config.getUrl;
    log("URL $url");

    _hubConnection =
        HubConnectionBuilder()
            .withUrl(url, options: HttpConnectionOptions(skipNegotiation: true, transport: HttpTransportType.WebSockets, headers: defaultHeaders, accessTokenFactory: () async => jsonEncode(defaultHeaders.asMap)))
            .build();

    refreshSocketStatus(HubConnectionState.Connecting);

    await _hubConnection
        .start()!
        .catchError((e) {
          log("Error: $e");
          refreshSocketStatus(_hubConnection.state);
          _connectAddress = null;
          response = false;
        })
        .then((value) {
          log("Connection Started");
          refreshSocketStatus(_hubConnection.state);
          _connectAddress = config.getUrl;

          log(_hubConnection.state.toString());
          _hubConnection.on("VirtualDeviceRequest", onVirtualDeviceRequest);
          handShake();

          response = true;
        })
        .onError((error, stackTrace) {
          _connectAddress = null;
          refreshSocketStatus(_hubConnection.state);
          response = false;
        });
  } catch (e) {
    log("Error: ${e.toString()}");
    removeAcps();
    response = false;
  }

  _hubConnection.onclose(({error}) {
    _connectAddress = null;
    response = false;
    refreshSocketStatus(_hubConnection.state);
  });

  _hubConnection.onreconnecting(_onReconnecting);
  _hubConnection.onreconnected(_onReconnected);

  return response;
}