This commit is contained in:
Yegor Vialov 2018-10-07 23:06:06 +03:00
parent 2fa35d771a
commit 84d283de2b
4 changed files with 63 additions and 26 deletions

View File

@ -1,9 +1,10 @@
part of 'main.dart'; part of 'main.dart';
class EntityViewPage extends StatefulWidget { 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 Entity entity;
final HomeAssistant homeAssistant;
@override @override
_EntityViewPageState createState() => new _EntityViewPageState(); _EntityViewPageState createState() => new _EntityViewPageState();
@ -11,26 +12,34 @@ class EntityViewPage extends StatefulWidget {
class _EntityViewPageState extends State<EntityViewPage> { class _EntityViewPageState extends State<EntityViewPage> {
String _title; String _title;
Entity _entity;
StreamSubscription _stateSubscription; StreamSubscription _stateSubscription;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_entity = widget.entity;
if (_stateSubscription != null) _stateSubscription.cancel(); if (_stateSubscription != null) _stateSubscription.cancel();
_stateSubscription = eventBus.on<StateChangedEvent>().listen((event) { _stateSubscription = eventBus.on<StateChangedEvent>().listen((event) {
if (event.entityId == _entity.entityId) { if (event.entityId == widget.entity.entityId) {
setState(() {}); setState(() {});
} }
}); });
_prepareData(); _prepareData();
_getHistory();
} }
_prepareData() async { void _prepareData() async {
_title = _entity.displayName; _title = widget.entity.displayName;
} }
void _getHistory() {
widget.homeAssistant.getHistory(widget.entity.entityId).then((List history) {
if (history != null) {
}
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return new Scaffold( return new Scaffold(
@ -44,7 +53,7 @@ class _EntityViewPageState extends State<EntityViewPage> {
), ),
body: Padding( body: Padding(
padding: EdgeInsets.all(10.0), padding: EdgeInsets.all(10.0),
child: _entity.buildWidget(context, EntityWidgetType.extended) child: widget.entity.buildWidget(context, EntityWidgetType.extended)
), ),
); );
} }

View File

@ -1,9 +1,9 @@
part of 'main.dart'; part of 'main.dart';
class HomeAssistant { class HomeAssistant {
String _hassioAPIEndpoint; String _webSocketAPIEndpoint;
String _hassioPassword; String _password;
String _hassioAuthType; String _authType;
IOWebSocketChannel _hassioChannel; IOWebSocketChannel _hassioChannel;
SendMessageQueue _messageQueue; SendMessageQueue _messageQueue;
@ -47,9 +47,9 @@ class HomeAssistant {
} }
void updateConnectionSettings(String url, String password, String authType) { void updateConnectionSettings(String url, String password, String authType) {
_hassioAPIEndpoint = url; _webSocketAPIEndpoint = url;
_hassioPassword = password; _password = password;
_hassioAuthType = authType; _authType = authType;
} }
Future fetch() { Future fetch() {
@ -98,7 +98,7 @@ class HomeAssistant {
_socketSubscription.cancel(); _socketSubscription.cancel();
} }
_hassioChannel = IOWebSocketChannel.connect( _hassioChannel = IOWebSocketChannel.connect(
_hassioAPIEndpoint, pingInterval: Duration(seconds: 30)); _webSocketAPIEndpoint, pingInterval: Duration(seconds: 30));
_socketSubscription = _hassioChannel.stream.listen( _socketSubscription = _hassioChannel.stream.listen(
(message) => _handleMessage(message), (message) => _handleMessage(message),
cancelOnError: true, cancelOnError: true,
@ -170,7 +170,7 @@ class HomeAssistant {
var data = json.decode(message); var data = json.decode(message);
//TheLogger.log("Debug","[Received] => Message type: ${data['type']}"); //TheLogger.log("Debug","[Received] => Message type: ${data['type']}");
if (data["type"] == "auth_required") { if (data["type"] == "auth_required") {
_sendAuthMessageRaw('{"type": "auth","$_hassioAuthType": "$_hassioPassword"}'); _sendAuthMessageRaw('{"type": "auth","$_authType": "$_password"}');
} else if (data["type"] == "auth_ok") { } else if (data["type"] == "auth_ok") {
_completeConnecting(null); _completeConnecting(null);
_sendSubscribe(); _sendSubscribe();
@ -299,7 +299,6 @@ class HomeAssistant {
} }
void _parseUserInfo(Map data) { void _parseUserInfo(Map data) {
TheLogger.log("Debug", "$data");
if (data["success"] == true) { if (data["success"] == true) {
_userName = data["result"]["name"]; _userName = data["result"]["name"];
} else { } else {
@ -347,6 +346,34 @@ class HomeAssistant {
Widget buildViews(BuildContext context) { Widget buildViews(BuildContext context) {
return _viewBuilder.buildWidget(context); return _viewBuilder.buildWidget(context);
} }
Future<List> 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 { class SendMessageQueue {

View File

@ -11,6 +11,7 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:date_format/date_format.dart'; import 'package:date_format/date_format.dart';
import 'package:http/http.dart' as http;
part 'entity_class/entity.class.dart'; part 'entity_class/entity.class.dart';
part 'entity_class/button_entity.class.dart'; part 'entity_class/button_entity.class.dart';
@ -34,7 +35,7 @@ part 'card_class.dart';
EventBus eventBus = new EventBus(); EventBus eventBus = new EventBus();
const String appName = "HA Client"; const String appName = "HA Client";
const appVersion = "0.2.5"; const appVersion = "0.2.5 .31";
String homeAssistantWebHost; String homeAssistantWebHost;
@ -88,8 +89,8 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
HomeAssistant _homeAssistant; HomeAssistant _homeAssistant;
EntityCollection _entities; EntityCollection _entities;
//Map _instanceConfig; //Map _instanceConfig;
String _apiEndpoint; String _webSocketApiEndpoint;
String _apiPassword; String _password;
String _authType; String _authType;
int _uiViewsCount = 0; int _uiViewsCount = 0;
String _instanceHost; String _instanceHost;
@ -147,12 +148,12 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
String domain = prefs.getString('hassio-domain'); String domain = prefs.getString('hassio-domain');
String port = prefs.getString('hassio-port'); String port = prefs.getString('hassio-port');
_instanceHost = "$domain:$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"; homeAssistantWebHost = "${prefs.getString('hassio-res-protocol')}://$domain:$port";
_apiPassword = prefs.getString('hassio-password'); _password = prefs.getString('hassio-password');
_authType = prefs.getString('hassio-auth-type'); _authType = prefs.getString('hassio-auth-type');
if ((domain == null) || (port == null) || (_apiPassword == null) || if ((domain == null) || (port == null) || (_password == null) ||
(domain.length == 0) || (port.length == 0) || (_apiPassword.length == 0)) { (domain.length == 0) || (port.length == 0) || (_password.length == 0)) {
throw("Check connection settings"); throw("Check connection settings");
} else { } else {
_settingsLoaded = true; _settingsLoaded = true;
@ -200,7 +201,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
} }
_refreshData() async { _refreshData() async {
_homeAssistant.updateConnectionSettings(_apiEndpoint, _apiPassword, _authType); _homeAssistant.updateConnectionSettings(_webSocketApiEndpoint, _password, _authType);
setState(() { setState(() {
_hideErrorSnackBar(); _hideErrorSnackBar();
_isLoading = 1; _isLoading = 1;
@ -236,7 +237,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => EntityViewPage(entity: entity), builder: (context) => EntityViewPage(entity: entity, homeAssistant: _homeAssistant),
) )
); );
} }

View File

@ -1,7 +1,7 @@
name: hass_client name: hass_client
description: Home Assistant Android Client description: Home Assistant Android Client
version: 0.2.5+29 version: 0.2.5+31
environment: environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0" sdk: ">=2.0.0-dev.68.0 <3.0.0"