This repository has been archived on 2023-11-18. You can view files and clone it, but cannot push or open issues or pull requests.
ha_client/lib/home_assistant.class.dart

392 lines
11 KiB
Dart
Raw Normal View History

2018-09-25 22:47:06 +03:00
part of 'main.dart';
class HomeAssistant {
2019-03-26 00:18:30 +02:00
static const DEFAULT_DASHBOARD = 'lovelace';
static final HomeAssistant _instance = HomeAssistant._internal();
factory HomeAssistant() {
return _instance;
}
2018-10-25 00:05:29 +03:00
EntityCollection entities;
2018-10-27 00:54:05 +03:00
HomeAssistantUI ui;
2018-09-25 22:47:06 +03:00
Map _instanceConfig = {};
String _userName;
String _lovelaceDashbordUrl;
HSVColor savedColor;
2019-09-15 17:29:49 +03:00
int savedPlayerPosition;
2019-09-15 18:38:02 +03:00
String sendToPlayerId;
String sendFromPlayerId;
2020-03-15 15:47:51 +02:00
Map services;
bool autoUi = false;
String fcmToken;
2018-10-27 00:54:05 +03:00
Map _rawLovelaceData;
2020-03-15 15:47:51 +02:00
var _rawStates;
var _rawUserInfo;
var _rawPanels;
2018-10-27 00:54:05 +03:00
set lovelaceDashboardUrl(String val) => _lovelaceDashbordUrl = val;
2019-03-13 16:39:23 +02:00
List<Panel> panels = [];
2018-10-08 23:11:56 +03:00
Duration fetchTimeout = Duration(seconds: 30);
2018-10-02 18:05:50 +03:00
2018-11-04 21:02:12 +02:00
String get locationName {
if (!autoUi) {
return ui?.title ?? "Home";
2018-11-04 21:02:12 +02:00
} else {
return _instanceConfig["location_name"] ?? "Home";
2018-11-04 21:02:12 +02:00
}
}
String get userName => _userName ?? locationName;
2018-10-08 23:11:56 +03:00
String get userAvatarText => userName.length > 0 ? userName[0] : "";
2019-03-21 14:08:07 +02:00
bool get isNoEntities => entities == null || entities.isEmpty;
bool get isNoViews => ui == null || ui.isEmpty;
HomeAssistant._internal() {
ConnectionManager().onStateChangeCallback = _handleEntityStateChange;
ConnectionManager().onLovelaceUpdatedCallback = _handleLovelaceUpdate;
DeviceInfoManager().loadDeviceInfo();
2018-09-25 22:47:06 +03:00
}
2019-03-26 00:18:30 +02:00
Completer _fetchCompleter;
2018-10-08 23:11:56 +03:00
2020-03-22 01:11:00 +02:00
Future fetchData(bool uiOnly) {
2019-03-26 00:18:30 +02:00
if (_fetchCompleter != null && !_fetchCompleter.isCompleted) {
Logger.w("Previous data fetch is not completed yet");
return _fetchCompleter.future;
2018-10-08 23:11:56 +03:00
}
2019-03-26 00:18:30 +02:00
_fetchCompleter = Completer();
2018-10-07 18:27:10 +03:00
List<Future> futures = [];
2020-03-22 01:11:00 +02:00
if (!uiOnly) {
if (entities == null) entities = EntityCollection(ConnectionManager().httpWebHost);
futures.add(_getStates(null));
futures.add(_getConfig(null));
futures.add(_getUserInfo(null));
futures.add(_getPanels(null));
futures.add(_getServices(null));
}
if (!autoUi) {
2020-03-15 15:47:51 +02:00
futures.add(_getLovelace(null));
2018-10-27 00:54:05 +03:00
}
2019-03-26 00:18:30 +02:00
Future.wait(futures).then((_) {
2020-04-15 17:03:31 +03:00
if (isComponentEnabled('mobile_app')) {
2020-03-15 17:26:03 +02:00
_createUI();
2019-04-19 21:43:52 +03:00
_fetchCompleter.complete();
2020-03-22 01:11:00 +02:00
if (!uiOnly) MobileAppIntegrationManager.checkAppRegistration();
2019-04-19 21:43:52 +03:00
} else {
2020-02-12 15:22:26 +02:00
_fetchCompleter.completeError(HAError("Mobile app component not found", actions: [HAErrorAction.tryAgain(), HAErrorAction(type: HAErrorActionType.URL ,title: "Help",url: "http://ha-client.app/docs#mobile-app-integration")]));
2019-04-19 21:43:52 +03:00
}
}).catchError((e) {
2019-03-26 00:18:30 +02:00
_fetchCompleter.completeError(e);
});
2019-03-26 00:18:30 +02:00
return _fetchCompleter.future;
2018-09-25 22:47:06 +03:00
}
2020-03-15 17:26:03 +02:00
Future<void> fetchDataFromCache() async {
Logger.d('Loading cached data');
2020-03-15 15:47:51 +02:00
SharedPreferences prefs = await SharedPreferences.getInstance();
2020-03-15 17:26:03 +02:00
bool cached = prefs.getBool('cached');
if (cached != null && cached) {
2020-03-15 15:47:51 +02:00
if (entities == null) entities = EntityCollection(ConnectionManager().httpWebHost);
try {
_getStates(prefs);
if (!autoUi) {
2020-03-15 15:47:51 +02:00
_getLovelace(prefs);
}
_getConfig(prefs);
_getUserInfo(prefs);
_getPanels(prefs);
_getServices(prefs);
2020-04-15 17:03:31 +03:00
if (isComponentEnabled('mobile_app')) {
2020-03-15 17:26:03 +02:00
_createUI();
}
2020-03-15 15:47:51 +02:00
} catch (e) {
Logger.d('Didnt get cached data: $e');
}
}
}
void saveCache() async {
Logger.d('Saving data to cache...');
SharedPreferences prefs = await SharedPreferences.getInstance();
try {
await prefs.setString('cached_states', json.encode(_rawStates));
await prefs.setString('cached_lovelace', json.encode(_rawLovelaceData));
await prefs.setString('cached_user', json.encode(_rawUserInfo));
await prefs.setString('cached_config', json.encode(_instanceConfig));
await prefs.setString('cached_panels', json.encode(_rawPanels));
await prefs.setString('cached_services', json.encode(services));
await prefs.setBool('cached', true);
} catch (e) {
await prefs.setBool('cached', false);
Logger.e('Error saving cache: $e');
}
Logger.d('Done saving cache');
}
2019-03-20 23:38:57 +02:00
Future logout() async {
2019-03-21 14:08:07 +02:00
Logger.d("Logging out...");
await ConnectionManager().logout().then((_) {
2019-03-26 00:18:30 +02:00
ui?.clear();
entities?.clear();
panels?.clear();
2019-03-26 00:18:30 +02:00
});
}
2020-03-15 15:47:51 +02:00
Future _getConfig(SharedPreferences sharedPrefs) async {
if (sharedPrefs != null) {
try {
var data = json.decode(sharedPrefs.getString('cached_config'));
_parseConfig(data);
} catch (e) {
throw HAError("Error getting config: $e");
}
} else {
await ConnectionManager().sendSocketMessage(type: "get_config").then((data) => _parseConfig(data)).catchError((e) {
throw HAError("Error getting config: $e");
});
}
2018-09-25 22:47:06 +03:00
}
2020-03-15 15:47:51 +02:00
void _parseConfig(data) {
_instanceConfig = Map.from(data);
2020-04-15 17:03:31 +03:00
Logger.d('stream: ${_instanceConfig['components'].contains('stream')}');
2019-03-20 19:01:30 +02:00
}
2020-03-15 15:47:51 +02:00
Future _getStates(SharedPreferences sharedPrefs) async {
if (sharedPrefs != null) {
try {
var data = json.decode(sharedPrefs.getString('cached_states'));
_parseStates(data);
} catch (e) {
throw HAError("Error getting states: $e");
}
} else {
await ConnectionManager().sendSocketMessage(type: "get_states").then(
(data) => _parseStates(data)
).catchError((e) {
throw HAError("Error getting states: $e");
});
}
}
2020-03-15 15:47:51 +02:00
void _parseStates(data) {
_rawStates = data;
entities.parse(data);
}
Future _getLovelace(SharedPreferences sharedPrefs) {
if (sharedPrefs != null) {
try {
var data = json.decode(sharedPrefs.getString('cached_lovelace'));
_rawLovelaceData = data;
} catch (e) {
autoUi = true;
}
2020-03-15 15:47:51 +02:00
return Future.value();
} else {
Completer completer = Completer();
2020-04-04 16:17:01 +03:00
var additionalData;
if (_lovelaceDashbordUrl != HomeAssistant.DEFAULT_DASHBOARD) {
additionalData = {
'url_path': _lovelaceDashbordUrl
};
}
ConnectionManager().sendSocketMessage(
type: 'lovelace/config',
2020-04-04 16:17:01 +03:00
additionalData: additionalData
).then((data) {
2020-03-15 15:47:51 +02:00
_rawLovelaceData = data;
completer.complete();
}).catchError((e) {
if ("$e" == "config_not_found") {
autoUi = true;
_rawLovelaceData = null;
2020-03-15 15:47:51 +02:00
completer.complete();
} else {
completer.completeError(HAError("Error getting lovelace config: $e"));
}
});
return completer.future;
}
2018-10-27 00:54:05 +03:00
}
2020-03-15 15:47:51 +02:00
Future _getServices(SharedPreferences prefs) async {
if (prefs != null) {
try {
var data = json.decode(prefs.getString('cached_services'));
_parseServices(data);
} catch (e) {
Logger.w("Can't get services: $e");
}
}
await ConnectionManager().sendSocketMessage(type: "get_services").then((data) => _parseServices(data)).catchError((e) {
Logger.w("Can't get services: $e");
});
}
2020-02-20 16:33:03 +02:00
2020-03-15 15:47:51 +02:00
void _parseServices(data) {
services = data;
2020-02-20 16:33:03 +02:00
}
2020-03-15 15:47:51 +02:00
Future _getUserInfo(SharedPreferences sharedPrefs) async {
2019-03-02 18:00:25 +02:00
_userName = null;
2020-03-15 15:47:51 +02:00
await ConnectionManager().sendSocketMessage(type: "auth/current_user").then((data) => _parseUserInfo(data)).catchError((e) {
2019-10-28 12:43:10 +02:00
Logger.w("Can't get user info: $e");
});
}
2020-03-15 15:47:51 +02:00
void _parseUserInfo(data) {
_rawUserInfo = data;
_userName = data["name"];
}
Future _getPanels(SharedPreferences sharedPrefs) async {
if (sharedPrefs != null) {
try {
var data = json.decode(sharedPrefs.getString('cached_panels'));
_parsePanels(data);
} catch (e) {
throw HAError("Error getting panels list: $e");
}
} else {
await ConnectionManager().sendSocketMessage(type: "get_panels").then((data) => _parsePanels(data)).catchError((e) {
throw HAError("Error getting panels list: $e");
});
}
}
void _parsePanels(data) {
_rawPanels = data;
panels.clear();
List<Panel> dashboards = [];
2020-03-15 15:47:51 +02:00
data.forEach((k,v) {
String title = v['title'] == null ? "${k[0].toUpperCase()}${k.substring(1)}" : "${v['title'][0].toUpperCase()}${v['title'].substring(1)}";
if (v['component_name'] != null && v['component_name'] == 'lovelace') {
dashboards.add(
Panel(
id: k,
componentName: v['component_name'],
title: title,
urlPath: v['url_path'],
config: v['config'],
icon: (v['icon'] == null || v['icon'] == 'hass:view-dashboard') ? 'mdi:view-dashboard' : v['icon']
)
);
} else {
panels.add(
Panel(
id: k,
componentName: v['component_name'],
title: title,
urlPath: v['url_path'],
config: v['config'],
icon: v['icon']
)
);
}
});
panels.insertAll(0, dashboards);
2020-03-15 15:47:51 +02:00
}
Future getCameraStream(String entityId) {
Completer completer = Completer();
ConnectionManager().sendSocketMessage(type: "camera/stream", additionalData: {"entity_id": entityId}).then((data) {
completer.complete(data);
}).catchError((e) {
2020-03-15 15:47:51 +02:00
completer.completeError(e);
});
2020-03-15 15:47:51 +02:00
return completer.future;
2018-09-25 22:47:06 +03:00
}
2020-04-15 17:03:31 +03:00
bool isComponentEnabled(String name) {
return _instanceConfig["components"] != null && (_instanceConfig["components"] as List).contains("$name");
}
void _handleLovelaceUpdate() {
if (_fetchCompleter != null && _fetchCompleter.isCompleted) {
2020-03-22 01:11:00 +02:00
eventBus.fire(new LovelaceChangedEvent());
}
}
2018-09-25 22:47:06 +03:00
void _handleEntityStateChange(Map eventData) {
2018-10-27 01:24:23 +03:00
//TheLogger.debug( "New state for ${eventData['entity_id']}");
if (_fetchCompleter != null && _fetchCompleter.isCompleted) {
Map data = Map.from(eventData);
eventBus.fire(new StateChangedEvent(
entityId: data["entity_id"],
needToRebuildUI: entities.updateState(data)
));
}
2018-09-25 22:47:06 +03:00
}
2020-04-01 20:04:32 +03:00
bool isServiceExist(String service) {
return services != null &&
services.isNotEmpty &&
services.containsKey(service);
}
2018-10-27 00:54:05 +03:00
void _createUI() {
Logger.d("Creating Lovelace UI");
ui = HomeAssistantUI(rawLovelaceConfig: _rawLovelaceData);
2020-04-09 19:25:35 +03:00
/*if (isServiceExist('zha_map')) {
panels.add(
Panel(
id: 'haclient_zha',
componentName: 'haclient_zha',
title: 'ZHA',
urlPath: '/haclient_zha',
icon: 'mdi:zigbee'
)
);
2020-04-09 19:25:35 +03:00
}*/
2018-10-25 00:54:20 +03:00
}
2018-10-02 17:23:19 +03:00
}
2019-03-26 00:18:30 +02:00
/*
2018-10-02 17:23:19 +03:00
class SendMessageQueue {
int _messageTimeout;
List<HAMessage> _queue = [];
SendMessageQueue(this._messageTimeout);
void add(String message) {
_queue.add(HAMessage(_messageTimeout, message));
}
2019-10-28 12:43:10 +02:00
2018-10-02 17:23:19 +03:00
List<String> getActualMessages() {
_queue.removeWhere((item) => item.isExpired());
List<String> result = [];
_queue.forEach((haMessage){
result.add(haMessage.message);
});
this.clear();
return result;
}
2019-10-28 12:43:10 +02:00
2018-10-02 17:23:19 +03:00
void clear() {
_queue.clear();
}
2019-10-28 12:43:10 +02:00
2018-10-02 17:23:19 +03:00
}
class HAMessage {
DateTime _timeStamp;
int _messageTimeout;
String message;
2019-10-28 12:43:10 +02:00
2018-10-02 17:23:19 +03:00
HAMessage(this._messageTimeout, this.message) {
_timeStamp = DateTime.now();
}
2019-10-28 12:43:10 +02:00
2018-10-02 17:23:19 +03:00
bool isExpired() {
2018-10-07 12:14:48 +03:00
return DateTime.now().difference(_timeStamp).inSeconds > _messageTimeout;
2018-10-02 17:23:19 +03:00
}
2019-03-26 00:18:30 +02:00
}*/