From a7cda2a35ebb5bd262d6e9ec25b88466c03ef404 Mon Sep 17 00:00:00 2001 From: estevez-dev Date: Sat, 30 Mar 2019 00:29:52 +0200 Subject: [PATCH] WIP #48 Notifications --- android/app/src/main/AndroidManifest.xml | 4 ++-- lib/connection.class.dart | 24 ++++++++++++--------- lib/home_assistant.class.dart | 4 ++++ lib/main.dart | 27 +++++++++++++++--------- pubspec.lock | 15 +++++++++---- pubspec.yaml | 1 + 6 files changed, 49 insertions(+), 26 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 46304b4..c2df7c8 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -27,10 +27,10 @@ + defined in @style/LaunchTheme). + android:value="true" />--> diff --git a/lib/connection.class.dart b/lib/connection.class.dart index 5b05c48..1f9b366 100644 --- a/lib/connection.class.dart +++ b/lib/connection.class.dart @@ -16,6 +16,7 @@ class Connection { String _token; String _tempToken; String oauthUrl; + String deviceName; bool get isAuthenticated => _token != null; StreamSubscription _socketSubscription; Duration connectTimeout = Duration(seconds: 15); @@ -51,6 +52,9 @@ class Connection { (domain.length == 0) || (port.length == 0)) { completer.completeError({"errorCode": 5, "errorMessage": "Check connection settings"}); } else { + DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); + AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; + deviceName = androidInfo.model; oauthUrl = "$httpWebHost/auth/authorize?client_id=${Uri.encodeComponent('http://ha-client.homemade.systems/')}&redirect_uri=${Uri.encodeComponent('http://ha-client.homemade.systems/service/auth_callback.html')}"; if (_token == null) { await AuthManager().getTempToken( @@ -97,10 +101,7 @@ class Connection { Logger.d("[Received] <== ${data.toString()}"); _messageResolver["auth"]?.complete(); _messageResolver.remove("auth"); - if (!connecting.isCompleted) connecting.complete(sendSocketMessage( - type: "subscribe_events", - additionalData: {"event_type": "state_changed"}, - )); + if (!connecting.isCompleted) connecting.complete(); } else if (data["type"] == "auth_invalid") { Logger.d("[Received] <== ${data.toString()}"); _messageResolver["auth"]?.completeError({"errorCode": 62, "errorMessage": "${data["message"]}"}); @@ -119,12 +120,16 @@ class Connection { return connecting.future; } - Future _disconnect() async { + _disconnect() async { Logger.d( "Socket disconnecting..."); - await _socketSubscription?.cancel(); - await _socket?.sink?.close()?.timeout(Duration(seconds: 4), - onTimeout: () => Logger.d( "Socket sink close timeout") - ); + if (_socketSubscription != null) { + await _socketSubscription?.cancel(); + } + if (_socket != null && _socket.sink != null) { + await _socket.sink.close().timeout(Duration(seconds: 5), + onTimeout: () => Logger.d("Socket sink close timeout") + ); + } Logger.d( "..Disconnected"); } @@ -335,7 +340,6 @@ class Connection { }).catchError((e) { completer.completeError(e); }); - return completer.future; } diff --git a/lib/home_assistant.class.dart b/lib/home_assistant.class.dart index 4c47e86..e7e2de9 100644 --- a/lib/home_assistant.class.dart +++ b/lib/home_assistant.class.dart @@ -76,6 +76,10 @@ class HomeAssistant { futures.add(_getPanels()); Future.wait(futures).then((_) { _createUI(); + Connection().sendSocketMessage( + type: "subscribe_events", + additionalData: {"event_type": "state_changed"}, + ); _fetchCompleter.complete(); }).catchError((e) { _fetchCompleter.completeError(e); diff --git a/lib/main.dart b/lib/main.dart index a282952..eec4d26 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -20,6 +20,7 @@ import 'package:flutter_custom_tabs/flutter_custom_tabs.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:device_info/device_info.dart'; part 'entity_class/const.dart'; part 'entity_class/entity.class.dart'; @@ -104,6 +105,7 @@ part 'ui_widgets/config_panel_widget.dart'; EventBus eventBus = new EventBus(); +final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); const String appName = "HA Client"; const appVersion = "0.6.0-alpha1"; @@ -168,7 +170,6 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker StreamSubscription _startAuthSubscription; StreamSubscription _reloadUISubscription; int _previousViewCount; - final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); @override void initState() { @@ -199,8 +200,8 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker void _initialLoad() async { _showInfoBottomBar(progress: true,); - await _subscribe(); widget.homeAssistant.init().then((_){ + _subscribe(); _fetchData(); }, onError: (e) { _setErrorState(e); @@ -285,13 +286,16 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker } _firebaseMessaging.getToken().then((String token) { - //Logger.d("FCM token: $token"); + Logger.d("Device name: ${json.encode(Connection().deviceName)}"); widget.homeAssistant.connection.sendHTTPPost( - endPoint: '/api/notify.fcm-android', - data: '{"token": "$token"}' + endPoint: '/api/notify.ha-client', + data: '{"token": "$token", "device": ${json.encode(Connection().deviceName)}}' ).then((_) { Logger.d("Notificatin listener registered."); completer.complete(); + }).catchError((e) { + Logger.e("Error registering notification listener: ${e.toString()}"); + completer.complete(); }); }).catchError((e) { Logger.e("Error registering notification listener: ${e.toString()}"); @@ -319,9 +323,7 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker } _setErrorState(e) { - if (e is Error) { - Logger.e(e.toString()); - Logger.e("${e.stackTrace}"); + if (e["errorCode"] == null) { _showErrorBottomBar( message: "Unknown error", errorCode: 13 @@ -566,7 +568,7 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker case 10: { _bottomBarAction = FlatButton( - child: Text("Refresh", style: textStyle), + child: Text("Reload", style: textStyle), onPressed: () { //_scaffoldKey?.currentState?.hideCurrentSnackBar(); _reLoad(); @@ -588,7 +590,12 @@ class _MainPageState extends State with WidgetsBindingObserver, Ticker } default: { - _bottomBarAction = Container(width: 0.0, height: 0.0,); + _bottomBarAction = FlatButton( + child: Text("Try again", style: textStyle), + onPressed: () { + _reLoad(); + }, + ); break; } } diff --git a/pubspec.lock b/pubspec.lock index 9319ca9..cd760de 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -94,13 +94,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.0.6" + device_info: + dependency: "direct main" + description: + name: device_info + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.0+1" event_bus: dependency: "direct main" description: name: event_bus url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "1.1.0" firebase_messaging: dependency: "direct main" description: @@ -166,7 +173,7 @@ packages: name: flutter_webview_plugin url: "https://pub.dartlang.org" source: hosted - version: "0.3.1" + version: "0.3.3" http: dependency: transitive description: @@ -194,7 +201,7 @@ packages: name: intl url: "https://pub.dartlang.org" source: hosted - version: "0.15.7" + version: "0.15.8" logging: dependency: transitive description: @@ -388,7 +395,7 @@ packages: name: web_socket_channel url: "https://pub.dartlang.org" source: hosted - version: "1.0.9" + version: "1.0.12" xml: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index cdd07b8..617995c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -23,6 +23,7 @@ dependencies: firebase_messaging: ^4.0.0+1 flutter_webview_plugin: ^0.3.1 flutter_secure_storage: ^3.2.0 + device_info: ^0.4.0+1 dev_dependencies: flutter_test: