From 84d283de2bf6ef30cfc59f96279d25b468511c71 Mon Sep 17 00:00:00 2001 From: Yegor Vialov Date: Sun, 7 Oct 2018 23:06:06 +0300 Subject: [PATCH] VIP #120 --- lib/entity.page.dart | 23 ++++++++++++------ lib/home_assistant.class.dart | 45 ++++++++++++++++++++++++++++------- lib/main.dart | 19 ++++++++------- pubspec.yaml | 2 +- 4 files changed, 63 insertions(+), 26 deletions(-) diff --git a/lib/entity.page.dart b/lib/entity.page.dart index 5e56531..ab5e8fe 100644 --- a/lib/entity.page.dart +++ b/lib/entity.page.dart @@ -1,9 +1,10 @@ part of 'main.dart'; class EntityViewPage extends StatefulWidget { - EntityViewPage({Key key, this.entity}) : super(key: key); + EntityViewPage({Key key, @required this.entity, @required this.homeAssistant }) : super(key: key); final Entity entity; + final HomeAssistant homeAssistant; @override _EntityViewPageState createState() => new _EntityViewPageState(); @@ -11,26 +12,34 @@ class EntityViewPage extends StatefulWidget { class _EntityViewPageState extends State { String _title; - Entity _entity; StreamSubscription _stateSubscription; @override void initState() { super.initState(); - _entity = widget.entity; if (_stateSubscription != null) _stateSubscription.cancel(); _stateSubscription = eventBus.on().listen((event) { - if (event.entityId == _entity.entityId) { + if (event.entityId == widget.entity.entityId) { setState(() {}); } }); _prepareData(); + _getHistory(); } - _prepareData() async { - _title = _entity.displayName; + void _prepareData() async { + _title = widget.entity.displayName; } + void _getHistory() { + widget.homeAssistant.getHistory(widget.entity.entityId).then((List history) { + if (history != null) { + + } + }); + } + + @override Widget build(BuildContext context) { return new Scaffold( @@ -44,7 +53,7 @@ class _EntityViewPageState extends State { ), body: Padding( padding: EdgeInsets.all(10.0), - child: _entity.buildWidget(context, EntityWidgetType.extended) + child: widget.entity.buildWidget(context, EntityWidgetType.extended) ), ); } diff --git a/lib/home_assistant.class.dart b/lib/home_assistant.class.dart index 051cebe..c789084 100644 --- a/lib/home_assistant.class.dart +++ b/lib/home_assistant.class.dart @@ -1,9 +1,9 @@ part of 'main.dart'; class HomeAssistant { - String _hassioAPIEndpoint; - String _hassioPassword; - String _hassioAuthType; + String _webSocketAPIEndpoint; + String _password; + String _authType; IOWebSocketChannel _hassioChannel; SendMessageQueue _messageQueue; @@ -47,9 +47,9 @@ class HomeAssistant { } void updateConnectionSettings(String url, String password, String authType) { - _hassioAPIEndpoint = url; - _hassioPassword = password; - _hassioAuthType = authType; + _webSocketAPIEndpoint = url; + _password = password; + _authType = authType; } Future fetch() { @@ -98,7 +98,7 @@ class HomeAssistant { _socketSubscription.cancel(); } _hassioChannel = IOWebSocketChannel.connect( - _hassioAPIEndpoint, pingInterval: Duration(seconds: 30)); + _webSocketAPIEndpoint, pingInterval: Duration(seconds: 30)); _socketSubscription = _hassioChannel.stream.listen( (message) => _handleMessage(message), cancelOnError: true, @@ -170,7 +170,7 @@ class HomeAssistant { var data = json.decode(message); //TheLogger.log("Debug","[Received] => Message type: ${data['type']}"); if (data["type"] == "auth_required") { - _sendAuthMessageRaw('{"type": "auth","$_hassioAuthType": "$_hassioPassword"}'); + _sendAuthMessageRaw('{"type": "auth","$_authType": "$_password"}'); } else if (data["type"] == "auth_ok") { _completeConnecting(null); _sendSubscribe(); @@ -299,7 +299,6 @@ class HomeAssistant { } void _parseUserInfo(Map data) { - TheLogger.log("Debug", "$data"); if (data["success"] == true) { _userName = data["result"]["name"]; } else { @@ -347,6 +346,34 @@ class HomeAssistant { Widget buildViews(BuildContext context) { return _viewBuilder.buildWidget(context); } + + Future getHistory(String entityId) async { + DateTime now = DateTime.now(); + //String endTime = formatDate(now, [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]); + String startTime = formatDate(now.subtract(Duration(hours: 24)), [yyyy, '-', mm, '-', dd, 'T', HH, ':', nn, ':', ss, z]); + TheLogger.log("Debug", "$startTime"); + String url = "$homeAssistantWebHost/api/history/period/$startTime?&filter_entity_id=$entityId&skip_initial_state"; + TheLogger.log("Debug", "$url"); + http.Response historyResponse; + if (_authType == "access_token") { + historyResponse = await http.get(url, headers: { + "authorization": "Bearer $_password", + "Content-Type": "application/json" + }); + } else { + historyResponse = await http.get(url, headers: { + "X-HA-Access": "$_password", + "Content-Type": "application/json" + }); + } + var _history = json.decode(historyResponse.body); + if (_history is Map) { + return null; + } else if (_history is List) { + TheLogger.log("Debug", "${_history[0].toString()}"); + return _history; + } + } } class SendMessageQueue { diff --git a/lib/main.dart b/lib/main.dart index 942ba9e..0c1274b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -11,6 +11,7 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:flutter/services.dart'; import 'package:date_format/date_format.dart'; +import 'package:http/http.dart' as http; part 'entity_class/entity.class.dart'; part 'entity_class/button_entity.class.dart'; @@ -34,7 +35,7 @@ part 'card_class.dart'; EventBus eventBus = new EventBus(); const String appName = "HA Client"; -const appVersion = "0.2.5"; +const appVersion = "0.2.5 .31"; String homeAssistantWebHost; @@ -88,8 +89,8 @@ class _MainPageState extends State with WidgetsBindingObserver { HomeAssistant _homeAssistant; EntityCollection _entities; //Map _instanceConfig; - String _apiEndpoint; - String _apiPassword; + String _webSocketApiEndpoint; + String _password; String _authType; int _uiViewsCount = 0; String _instanceHost; @@ -147,12 +148,12 @@ class _MainPageState extends State with WidgetsBindingObserver { String domain = prefs.getString('hassio-domain'); String port = prefs.getString('hassio-port'); _instanceHost = "$domain:$port"; - _apiEndpoint = "${prefs.getString('hassio-protocol')}://$domain:$port/api/websocket"; + _webSocketApiEndpoint = "${prefs.getString('hassio-protocol')}://$domain:$port/api/websocket"; homeAssistantWebHost = "${prefs.getString('hassio-res-protocol')}://$domain:$port"; - _apiPassword = prefs.getString('hassio-password'); + _password = prefs.getString('hassio-password'); _authType = prefs.getString('hassio-auth-type'); - if ((domain == null) || (port == null) || (_apiPassword == null) || - (domain.length == 0) || (port.length == 0) || (_apiPassword.length == 0)) { + if ((domain == null) || (port == null) || (_password == null) || + (domain.length == 0) || (port.length == 0) || (_password.length == 0)) { throw("Check connection settings"); } else { _settingsLoaded = true; @@ -200,7 +201,7 @@ class _MainPageState extends State with WidgetsBindingObserver { } _refreshData() async { - _homeAssistant.updateConnectionSettings(_apiEndpoint, _apiPassword, _authType); + _homeAssistant.updateConnectionSettings(_webSocketApiEndpoint, _password, _authType); setState(() { _hideErrorSnackBar(); _isLoading = 1; @@ -236,7 +237,7 @@ class _MainPageState extends State with WidgetsBindingObserver { Navigator.push( context, MaterialPageRoute( - builder: (context) => EntityViewPage(entity: entity), + builder: (context) => EntityViewPage(entity: entity, homeAssistant: _homeAssistant), ) ); } diff --git a/pubspec.yaml b/pubspec.yaml index 7ad7204..c805c99 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: hass_client description: Home Assistant Android Client -version: 0.2.5+29 +version: 0.2.5+31 environment: sdk: ">=2.0.0-dev.68.0 <3.0.0"