openWebSocket method

dynamic 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

openWebSocket(void Function(dynamic event) callback) {
  this.websocket = WebSocketChannel.connect(Uri.parse(this.hostWebsocket));
  this.logger!.log('websocket =>', 'open attempt');
  callback(this.websocket);
  this.websocket!.stream.listen(
    (dynamic message) {
      this.logger!.log('receiving something through the websocket:', message);
      Map jsonRes = json.decode(message);
      if (jsonRes['result'] != null && jsonRes['result']['event'] != null) {
        int handle = jsonRes['result']['handle'];
        int type = jsonRes['result']['event']['type'];
        int id = jsonRes['result']['event']['id'];
        dynamic value =
            typifyValue(jsonRes['result']['event']['value'], type);
        CaptureEvent evt = CaptureEvent(id, type, value, handle);
        this.notification(evt);
      } else if (jsonRes['error'] != null) {
        this.logger!.log('Error in listener', jsonRes['error']);
      } else {
        this.logger!.log('Uh oh =>', 'No result returned');
      }
    },
    onDone: () {
      this.logger!.log('websocket =>', 'websocket closed!');
    },
    onError: (error) {
      if (error.hashCode == 1006) {
        CaptureException err = CaptureException(
            error.hashCode.toInt(), 'Websocket cannot communicate');
        this.notification(err);
      } else {
        CaptureException err = CaptureException(
            SktErrors.ESKT_SERVICENOTCOMMUNICATING,
            'Service is unable to communicate');
        this.notification(err);
      }
    },
  );
}