openWebSocket method

void openWebSocket(
  1. void callback(
    1. dynamic event
    )
)

Function used to implement instance of WebSocketChannel to create a stream for capture library to use and stay connected to. Helps to maintain network for capture notifications. Since this is over HTTP we use websocket. For iOS there is no need to establish websockets since we connect to the iOS service.

Implementation

void openWebSocket(void Function(dynamic event) callback) {
  websocket = WebSocketChannel.connect(Uri.parse(hostWebsocket));
  logger?.log('websocket =>', 'open attempt');
  callback(websocket);
  websocket!.stream.listen(
    (dynamic message) {
      logger?.log('receiving something through the websocket:', message);
      final Map<String, dynamic> jsonRes =
          json.decode(message as String) as Map<String, dynamic>;
      final JRpcResponse response = JRpcResponse.fromJson(jsonRes);
      final CaptureResult? result = response.captureResult;
      final CaptureEvent? event = result?.event;
      if (event != null) {
        notification(event, result?.handle);
      } else if (jsonRes['error'] != null) {
        logger!.log('Error in listener',
            '${jsonRes['error']['code']}: ${jsonRes['error']['message']}');
        final CaptureException err = CaptureException(
            jsonRes['error']['code'] as int,
            jsonRes['error']['message'] as String);
        // need to provide some sort of handle
        notification(err, 00000);
      } else {
        logger?.log('websocket =>', 'No result returned');
      }
    },
    onDone: () {
      logger?.log('websocket =>', 'websocket closed!');
    },
    onError: (dynamic error) {
      if (error.hashCode == 1006) {
        final CaptureException err =
            CaptureException(error.hashCode, 'Websocket cannot communicate');
        notification(err);
      } else {
        final CaptureException err = CaptureException(
            SktErrors.ESKT_SERVICENOTCOMMUNICATING,
            'Service is unable to communicate');
        notification(err);
      }
    },
  );
}