Skip to content

Commit

Permalink
fix(iot): 物联网界面加载失败后添加错误提示 (#422)
Browse files Browse the repository at this point in the history
通过监听 connectionState 和 onConnectionLost 来实现

fixed #289
  • Loading branch information
he0119 authored Sep 9, 2024
1 parent 65a8b1c commit 56603b9
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/lang/zh-CN/
- 捕获解码异常并修复在网页无法打开物品管理主页的问题
- 修复多次请求图片的问题
- 修复升级服务器 Filter 用法导致的问题
- 物联网界面加载失败后添加错误提示

## [0.9.7] - 2024-02-05

Expand Down
54 changes: 48 additions & 6 deletions lib/core/repository/graphql_api_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,20 @@ DocumentNode opi(DocumentNode document) => transform(
);

class SocketCustomLink extends Link {
SocketCustomLink(this.url, this.settingsController, this.defaultHeaders);
SocketCustomLink(
this.url,
this.defaultHeaders,
this.settingsController,
this.onConnectionLost,
this.connectionStateController,
);
final String url;
final Map<String, String> defaultHeaders;
_Connection? _connection;
final SettingsController settingsController;
final Future<Duration?> Function(int? code, String? reason) onConnectionLost;
final StreamController<bool> connectionStateController;

_Connection? _connection;

/// this will be called every time you make a subscription
@override
Expand All @@ -138,10 +147,18 @@ class SocketCustomLink extends Link {
headers: kIsWeb || cookies == null
? null
: {'cookie': cookies, ...defaultHeaders},
onConnectionLost: onConnectionLost,
),
),
cookies: cookies,
);

// 监听连接状态
_connection?.client.connectionState.listen((event) {
if (event == SocketConnectionState.connected) {
connectionStateController.add(true);
}
});
}

@override
Expand All @@ -168,9 +185,10 @@ class GraphQLApiClient {
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SettingsController settingsController;

GraphQLApiClient(
this.settingsController,
);
final StreamController<bool> _websocketConnectionStateController =
StreamController<bool>.broadcast();

GraphQLApiClient(this.settingsController);

GraphQLClient? get client => _client;

Expand All @@ -179,6 +197,9 @@ class GraphQLApiClient {
return prefs.getString('token');
}

Stream<bool> get websocketConnectionState =>
_websocketConnectionStateController.stream;

/// 登录
Future<User?> login(String username, String password) async {
final loginOptions = MutationOptions(
Expand Down Expand Up @@ -237,7 +258,12 @@ class GraphQLApiClient {
);
}
final websocketLink = SocketCustomLink(
url.replaceFirst('http', 'ws'), settingsController, headers);
url.replaceFirst('http', 'ws'),
headers,
settingsController,
onWebsocketConnectionLost,
_websocketConnectionStateController,
);

link = Link.split((request) => request.isSubscription, websocketLink, link);

Expand All @@ -246,6 +272,13 @@ class GraphQLApiClient {
link: link,
);
_log.fine('GraphQLClient initailized with url $url');
websocketConnectionState.listen((event) {
if (event) {
_log.info('Websocket connected');
} else {
_log.warning('Websocket disconnected');
}
});
}

/// 加载配置,比如用户代理
Expand Down Expand Up @@ -315,6 +348,7 @@ class GraphQLApiClient {
return results;
}

/// 订阅
Stream<QueryResult> subscribe(SubscriptionOptions options) {
return _client!.subscribe(options).map((event) {
if (event.hasException) {
Expand All @@ -324,6 +358,7 @@ class GraphQLApiClient {
});
}

/// 处理异常
void _handleException(OperationException exception) {
for (var error in exception.graphqlErrors) {
if (error.message == 'User is not authenticated') {
Expand All @@ -338,4 +373,11 @@ class GraphQLApiClient {
throw const NetworkException('网络异常,请稍后再试');
}
}

Future<Duration?> onWebsocketConnectionLost(int? code, String? reason) async {
_log.warning(
'Websocket Connection lost with code $code and reason $reason');
_websocketConnectionStateController.add(false);
return null;
}
}
10 changes: 10 additions & 0 deletions lib/iot/bloc/device_data/device_data_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:smarthome/core/core.dart';
import 'package:smarthome/iot/model/iot.dart';
import 'package:smarthome/iot/repository/iot_repository.dart';
import 'package:smarthome/utils/exceptions.dart';
Expand All @@ -11,13 +12,16 @@ part 'device_data_state.dart';

class DeviceDataBloc extends Bloc<DeviceDataEvent, DeviceDataState> {
final IotRepository iotRepository;
final GraphQLApiClient client;
final String deviceId;

StreamSubscription<AutowateringData>? _dataSubscription;
StreamSubscription<bool>? _connectionSubscription;

DeviceDataBloc({
required this.iotRepository,
required this.deviceId,
required this.client,
}) : super(DeviceDataInitial()) {
on<DeviceDataStarted>(_onDeviceDataStarted);
on<DeviceDataupdated>(_onDeviceDataupdated);
Expand All @@ -27,6 +31,7 @@ class DeviceDataBloc extends Bloc<DeviceDataEvent, DeviceDataState> {
@override
Future<void> close() {
_dataSubscription?.cancel();
_connectionSubscription?.cancel();
return super.close();
}

Expand All @@ -49,6 +54,11 @@ class DeviceDataBloc extends Bloc<DeviceDataEvent, DeviceDataState> {
}
},
);
_connectionSubscription = client.websocketConnectionState.listen((state) {
if (!state) {
add(const DeviceDataStoped('服务器断开连接'));
}
});
}

FutureOr<void> _onDeviceDataupdated(
Expand Down
1 change: 1 addition & 0 deletions lib/iot/view/home_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class IotHomePage extends Page {
create: (context) => DeviceDataBloc(
iotRepository: RepositoryProvider.of<IotRepository>(context),
deviceId: 'RGV2aWNlOjE=',
client: RepositoryProvider.of<GraphQLApiClient>(context),
)..add(const DeviceDataStarted()),
),
BlocProvider<DeviceEditBloc>(
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ dependencies:

# Dart
logging: ^1.2.0
graphql: ^5.1.3
graphql: ^5.2.0-beta.8
http: ^1.2.2
bloc: ^8.1.4
equatable: ^2.0.5
Expand Down

0 comments on commit 56603b9

Please sign in to comment.