connect function
Implementation
@pragma('vm:entry-point')
Future<void> connect(
String token, MethodChannel channel, Function? onMessage) async {
if (!connected) {
await channel.invokeMethod<dynamic>("unlock");
return;
}
if (active) return;
await addLog(channel, "Connecting");
active = true;
try {
await subs?.cancel();
webChannel?.sink.close();
webChannel = WebSocketChannel.connect(
Uri.parse('wss://sub.pushed.ru/v2/open-websocket/$token'),
);
await webChannel?.ready;
await setNewStatus(channel, ServiceStatus.active);
subs = webChannel?.stream.listen((event) async {
await channel.invokeMethod<dynamic>("lock");
var message = utf8.decode(event);
await addLog(channel, "Pushed message: $message");
if (message != "ONLINE") {
var payload = json.decode(message);
var messageId = payload["messageId"];
var traceId = payload["mfTraceId"];
var lastMessageId =
await channel.invokeMethod<String>("getLastMessageId");
if (lastMessageId != messageId) {
await addLog(channel, "Pushed processing message");
await channel.invokeMethod<dynamic>(
"setLastMessageId", {"lastMessageId": messageId});
var response = json.encode(<String, dynamic>{
"messageId": messageId,
if (traceId != null) "mfTraceId": traceId
});
webChannel?.sink.add(utf8.encode(response));
try {
var data = json.decode(payload["data"]);
payload["data"] = data;
} catch (_) {}
Map<String, dynamic> data = {"type": "message", "message": payload};
var res = await channel.invokeMethod<dynamic>("data", data) ?? false;
if (!res && onMessage != null) await onMessage(payload);
}
}
await Future.delayed(const Duration(seconds: 5));
await channel.invokeMethod<dynamic>("unlock");
}, onDone: () async {
await channel.invokeMethod<dynamic>("lock");
await addLog(channel, "Closed");
active = false;
await setNewStatus(channel, ServiceStatus.disconnected);
await Future.delayed(const Duration(seconds: 1));
connect(token, channel, onMessage);
});
} catch (e) {
await channel.invokeMethod<dynamic>("lock");
await addLog(channel, "Error: $e");
await setNewStatus(channel, ServiceStatus.disconnected);
await subs?.cancel();
active = false;
await Future.delayed(const Duration(seconds: 1));
connect(token, channel, onMessage);
}
}