Matthias Nott
2026-03-23 07ad99d7c4f8c52930442a34d316e634435bd75a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import 'dart:async';
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../models/server_config.dart';
import 'wol_service.dart';
enum ConnectionStatus {
  disconnected,
  connecting,
  connected,
  reconnecting,
}
/// WebSocket client with dual-URL fallback, heartbeat, and auto-reconnect.
class WebSocketService with WidgetsBindingObserver {
  WebSocketService({required this.config});
  ServerConfig config;
  WebSocketChannel? _channel;
  ConnectionStatus _status = ConnectionStatus.disconnected;
  Timer? _heartbeatTimer;
  Timer? _zombieTimer;
  Timer? _reconnectTimer;
  int _reconnectAttempt = 0;
  bool _intentionalClose = false;
  DateTime? _lastPong;
  StreamSubscription? _subscription;
  // Callbacks
  void Function()? onOpen;
  void Function()? onClose;
  void Function()? onReconnecting;
  void Function(Map<String, dynamic> message)? onMessage;
  void Function(String error)? onError;
  void Function(ConnectionStatus status)? onStatusChanged;
  ConnectionStatus get status => _status;
  bool get isConnected => _status == ConnectionStatus.connected;
  void _setStatus(ConnectionStatus newStatus) {
    if (_status == newStatus) return;
    _status = newStatus;
    onStatusChanged?.call(newStatus);
  }
  /// Connect to the WebSocket server.
  /// Tries local URL first (2.5s timeout), then remote URL.
  Future<void> connect() async {
    if (_status == ConnectionStatus.connected ||
        _status == ConnectionStatus.connecting) {
      return;
    }
    _intentionalClose = false;
    _setStatus(ConnectionStatus.connecting);
    // Send Wake-on-LAN if MAC configured
    if (config.macAddress != null && config.macAddress!.isNotEmpty) {
      try {
        await WolService.wake(config.macAddress!, localHost: config.localHost);
      } catch (_) {}
    }
    final urls = config.urls;
    for (final url in urls) {
      if (_intentionalClose) return;
      try {
        final connected = await _tryConnect(url,
            timeout: url == urls.first && urls.length > 1
                ? const Duration(milliseconds: 2500)
                : const Duration(seconds: 5));
        if (connected) return;
      } catch (_) {
        continue;
      }
    }
    // All URLs failed
    _setStatus(ConnectionStatus.disconnected);
    onError?.call('Failed to connect to server');
    _scheduleReconnect();
  }
  Future<bool> _tryConnect(String url, {Duration? timeout}) async {
    try {
      final uri = Uri.parse(url);
      final channel = WebSocketChannel.connect(uri);
      // Wait for connection with timeout
      await channel.ready.timeout(
        timeout ?? const Duration(seconds: 5),
        onTimeout: () {
          channel.sink.close();
          throw TimeoutException('Connection timeout');
        },
      );
      _channel = channel;
      _reconnectAttempt = 0;
      _setStatus(ConnectionStatus.connected);
      _startHeartbeat();
      _listenMessages();
      onOpen?.call();
      return true;
    } catch (e) {
      return false;
    }
  }
  void _listenMessages() {
    _subscription?.cancel();
    _subscription = _channel?.stream.listen(
      (data) {
        _lastPong = DateTime.now();
        if (data is String) {
          // Handle pong
          if (data == 'pong') return;
          try {
            final json = jsonDecode(data) as Map<String, dynamic>;
            onMessage?.call(json);
          } catch (_) {
            // Non-JSON message, ignore
          }
        }
      },
      onError: (error) {
        onError?.call(error.toString());
        _handleDisconnect();
      },
      onDone: () {
        _handleDisconnect();
      },
    );
  }
  void _startHeartbeat() {
    _heartbeatTimer?.cancel();
    _zombieTimer?.cancel();
    _lastPong = DateTime.now();
    // Send ping every 30 seconds
    _heartbeatTimer = Timer.periodic(const Duration(seconds: 30), (_) {
      if (_channel != null && _status == ConnectionStatus.connected) {
        try {
          _channel!.sink.add(jsonEncode({'type': 'ping'}));
        } catch (_) {
          _handleDisconnect();
        }
      }
    });
    // Check for zombie connection every 15 seconds
    _zombieTimer = Timer.periodic(const Duration(seconds: 15), (_) {
      if (_lastPong != null) {
        final elapsed = DateTime.now().difference(_lastPong!);
        if (elapsed.inSeconds > 60) {
          _handleDisconnect();
        }
      }
    });
  }
  void _handleDisconnect() {
    _stopHeartbeat();
    _subscription?.cancel();
    final wasConnected = _status == ConnectionStatus.connected;
    try {
      _channel?.sink.close();
    } catch (_) {}
    _channel = null;
    if (_intentionalClose) {
      _setStatus(ConnectionStatus.disconnected);
      onClose?.call();
    } else if (wasConnected) {
      _setStatus(ConnectionStatus.reconnecting);
      onReconnecting?.call();
      _scheduleReconnect();
    }
  }
  void _stopHeartbeat() {
    _heartbeatTimer?.cancel();
    _zombieTimer?.cancel();
    _heartbeatTimer = null;
    _zombieTimer = null;
  }
  void _scheduleReconnect() {
    if (_intentionalClose) return;
    _reconnectTimer?.cancel();
    // Exponential backoff: 1s, 2s, 4s, 8s, 16s, 30s max
    final delay = Duration(
      milliseconds: (1000 * (1 << _reconnectAttempt.clamp(0, 4)))
          .clamp(1000, 30000),
    );
    _reconnectAttempt++;
    _reconnectTimer = Timer(delay, () {
      if (!_intentionalClose) {
        _setStatus(ConnectionStatus.reconnecting);
        onReconnecting?.call();
        connect();
      }
    });
  }
  /// Send a JSON message.
  void send(Map<String, dynamic> message) {
    if (_channel == null || _status != ConnectionStatus.connected) {
      onError?.call('Not connected');
      return;
    }
    try {
      _channel!.sink.add(jsonEncode(message));
    } catch (e) {
      onError?.call('Send failed: $e');
    }
  }
  /// Send a raw string.
  void sendRaw(String data) {
    if (_channel == null || _status != ConnectionStatus.connected) return;
    try {
      _channel!.sink.add(data);
    } catch (_) {}
  }
  /// Disconnect intentionally.
  void disconnect() {
    _intentionalClose = true;
    _reconnectTimer?.cancel();
    _stopHeartbeat();
    _subscription?.cancel();
    try {
      _channel?.sink.close();
    } catch (_) {}
    _channel = null;
    _setStatus(ConnectionStatus.disconnected);
    onClose?.call();
  }
  /// Update config and reconnect.
  Future<void> updateConfig(ServerConfig newConfig) async {
    config = newConfig;
    disconnect();
    await Future.delayed(const Duration(milliseconds: 100));
    await connect();
  }
  /// Dispose all resources.
  void dispose() {
    disconnect();
    _reconnectTimer?.cancel();
  }
  // App lifecycle integration
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        if (_status != ConnectionStatus.connected && !_intentionalClose) {
          _reconnectAttempt = 0;
          connect();
        }
      case AppLifecycleState.paused:
        // Keep connection alive but don't reconnect aggressively
        break;
      default:
        break;
    }
  }
}