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

603 lines
18 KiB
Dart
Raw Normal View History

2018-09-25 22:47:06 +03:00
part of 'main.dart';
class HomeAssistant {
2018-10-07 23:06:06 +03:00
String _webSocketAPIEndpoint;
String _password;
bool _useLovelace = false;
2018-09-25 22:47:06 +03:00
IOWebSocketChannel _hassioChannel;
2018-10-02 17:23:19 +03:00
SendMessageQueue _messageQueue;
2018-09-25 22:47:06 +03:00
int _currentMessageId = 0;
int _statesMessageId = 0;
int _servicesMessageId = 0;
int _subscriptionMessageId = 0;
int _configMessageId = 0;
int _userInfoMessageId = 0;
2018-10-27 00:54:05 +03:00
int _lovelaceMessageId = 0;
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;
2018-10-27 00:54:05 +03:00
Map _rawLovelaceData;
2018-09-25 22:47:06 +03:00
Completer _fetchCompleter;
Completer _statesCompleter;
Completer _servicesCompleter;
2018-10-27 00:54:05 +03:00
Completer _lovelaceCompleter;
2018-09-25 22:47:06 +03:00
Completer _configCompleter;
Completer _connectionCompleter;
Completer _userInfoCompleter;
Timer _connectionTimer;
Timer _fetchTimer;
bool autoReconnect = false;
2018-09-25 22:47:06 +03:00
2018-10-03 10:35:40 +03:00
StreamSubscription _socketSubscription;
2018-10-08 23:11:56 +03:00
int messageExpirationTime = 30; //seconds
Duration fetchTimeout = Duration(seconds: 30);
2018-10-07 12:14:48 +03:00
Duration connectTimeout = Duration(seconds: 15);
2018-10-02 18:05:50 +03:00
2018-11-04 21:02:12 +02:00
String get locationName {
if (_useLovelace) {
return ui?.title ?? "";
} else {
return _instanceConfig["location_name"] ?? "";
}
}
String get userName => _userName ?? locationName;
2018-10-08 23:11:56 +03:00
String get userAvatarText => userName.length > 0 ? userName[0] : "";
2018-10-25 00:54:20 +03:00
//int get viewsCount => entities.views.length ?? 0;
HomeAssistant() {
2018-10-25 00:05:29 +03:00
entities = EntityCollection();
2018-10-02 18:05:50 +03:00
_messageQueue = SendMessageQueue(messageExpirationTime);
2018-09-25 22:47:06 +03:00
}
void updateSettings(String url, String password, bool useLovelace) {
2018-10-07 23:06:06 +03:00
_webSocketAPIEndpoint = url;
_password = password;
2018-10-27 00:54:05 +03:00
_useLovelace = useLovelace;
Logger.d( "Use lovelace is $_useLovelace");
}
2018-09-25 22:47:06 +03:00
Future fetch() {
if ((_fetchCompleter != null) && (!_fetchCompleter.isCompleted)) {
Logger.w("Previous fetch is not complited");
2018-09-25 22:47:06 +03:00
} else {
_fetchCompleter = new Completer();
2018-10-02 18:05:50 +03:00
_fetchTimer = Timer(fetchTimeout, () {
Logger.e( "Data fetching timeout");
2018-10-08 23:11:56 +03:00
disconnect().then((_) {
_completeFetching({
"errorCode": 9,
"errorMessage": "Couldn't get data from server"
});
});
});
_connection().then((r) {
2018-09-25 22:47:06 +03:00
_getData();
}).catchError((e) {
_completeFetching(e);
2018-09-25 22:47:06 +03:00
});
}
return _fetchCompleter.future;
}
disconnect() async {
if ((_hassioChannel != null) && (_hassioChannel.closeCode == null) && (_hassioChannel.sink != null)) {
await _hassioChannel.sink.close().timeout(Duration(seconds: 3),
onTimeout: () => Logger.d( "Socket sink closed")
);
await _socketSubscription.cancel();
2018-10-03 10:35:40 +03:00
_hassioChannel = null;
2018-09-25 22:47:06 +03:00
}
2018-09-25 22:47:06 +03:00
}
Future _connection() {
if ((_connectionCompleter != null) && (!_connectionCompleter.isCompleted)) {
Logger.d("Previous connection is not complited");
2018-09-25 22:47:06 +03:00
} else {
if ((_hassioChannel == null) || (_hassioChannel.closeCode != null)) {
2018-10-08 23:11:56 +03:00
_connectionCompleter = new Completer();
autoReconnect = false;
disconnect().then((_){
Logger.d( "Socket connecting...");
_connectionTimer = Timer(connectTimeout, () {
Logger.e( "Socket connection timeout");
2018-10-08 23:11:56 +03:00
_handleSocketError(null);
});
if (_socketSubscription != null) {
_socketSubscription.cancel();
}
_hassioChannel = IOWebSocketChannel.connect(
2018-10-07 23:06:06 +03:00
_webSocketAPIEndpoint, pingInterval: Duration(seconds: 30));
_socketSubscription = _hassioChannel.stream.listen(
(message) => _handleMessage(message),
cancelOnError: true,
2018-10-08 23:11:56 +03:00
onDone: () => _handleSocketClose(),
onError: (e) => _handleSocketError(e)
);
});
} else {
_completeConnecting(null);
}
2018-09-25 22:47:06 +03:00
}
return _connectionCompleter.future;
}
2018-10-08 23:11:56 +03:00
void _handleSocketClose() {
Logger.d("Socket disconnected. Automatic reconnect is $autoReconnect");
2018-10-08 23:11:56 +03:00
if (autoReconnect) {
_reconnect();
}
}
void _handleSocketError(e) {
Logger.e("Socket stream Error: $e");
Logger.d("Automatic reconnect is $autoReconnect");
2018-10-08 23:11:56 +03:00
if (autoReconnect) {
_reconnect();
} else {
disconnect().then((_) {
_completeConnecting({
"errorCode": 1,
"errorMessage": "Couldn't connect to Home Assistant. Check network connection or connection settings."
});
});
}
}
void _reconnect() {
disconnect().then((_) {
_connection().catchError((e){
_completeConnecting(e);
});
});
}
2018-10-07 18:27:10 +03:00
_getData() async {
List<Future> futures = [];
futures.add(_getStates());
2018-10-27 00:54:05 +03:00
if (_useLovelace) {
futures.add(_getLovelace());
}
2018-10-07 18:27:10 +03:00
futures.add(_getConfig());
futures.add(_getServices());
futures.add(_getUserInfo());
2018-10-07 18:27:10 +03:00
try {
await Future.wait(futures);
2018-10-27 00:54:05 +03:00
_createUI();
2018-10-07 18:27:10 +03:00
_completeFetching(null);
} catch (error) {
_completeFetching(error);
}
2018-09-25 22:47:06 +03:00
}
void _completeFetching(error) {
_fetchTimer.cancel();
_completeConnecting(error);
if (!_fetchCompleter.isCompleted) {
if (error != null) {
_fetchCompleter.completeError(error);
} else {
autoReconnect = true;
Logger.d( "Fetch complete successful");
2018-10-08 23:11:56 +03:00
_fetchCompleter.complete();
}
2018-09-25 22:47:06 +03:00
}
}
void _completeConnecting(error) {
_connectionTimer.cancel();
if (!_connectionCompleter.isCompleted) {
if (error != null) {
_connectionCompleter.completeError(error);
} else {
_connectionCompleter.complete();
}
} else if (error != null) {
2018-11-04 18:20:06 +02:00
if (error is Error) {
eventBus.fire(ShowErrorEvent(error.toString(), 12));
} else {
eventBus.fire(ShowErrorEvent(error["errorMessage"], error["errorCode"]));
}
}
}
_handleMessage(String message) {
2018-09-25 22:47:06 +03:00
var data = json.decode(message);
if (data["type"] == "auth_required") {
_sendAuthMessageRaw('{"type": "auth","access_token": "$_password"}');
2018-09-25 22:47:06 +03:00
} else if (data["type"] == "auth_ok") {
_completeConnecting(null);
2018-09-25 22:47:06 +03:00
_sendSubscribe();
} else if (data["type"] == "auth_invalid") {
_completeConnecting({"errorCode": 6, "errorMessage": "${data["message"]}"});
2018-09-25 22:47:06 +03:00
} else if (data["type"] == "result") {
Logger.d("[Received] <== id:${data["id"]}, ${data['success'] ? 'success' : 'error'}");
2018-09-25 22:47:06 +03:00
if (data["id"] == _configMessageId) {
_parseConfig(data);
} else if (data["id"] == _statesMessageId) {
_parseEntities(data);
2018-10-27 00:54:05 +03:00
} else if (data["id"] == _lovelaceMessageId) {
_handleLovelace(data);
2018-09-25 22:47:06 +03:00
} else if (data["id"] == _servicesMessageId) {
_parseServices(data);
} else if (data["id"] == _userInfoMessageId) {
_parseUserInfo(data);
2018-09-25 22:47:06 +03:00
}
} else if (data["type"] == "event") {
if ((data["event"] != null) && (data["event"]["event_type"] == "state_changed")) {
Logger.d("[Received] <== ${data['type']}.${data["event"]["event_type"]}: ${data["event"]["data"]["entity_id"]}");
2018-09-25 22:47:06 +03:00
_handleEntityStateChange(data["event"]["data"]);
} else if (data["event"] != null) {
Logger.w("Unhandled event type: ${data["event"]["event_type"]}");
2018-09-25 22:47:06 +03:00
} else {
Logger.e("Event is null: $message");
2018-09-25 22:47:06 +03:00
}
} else {
Logger.w("Unknown message type: $message");
2018-09-25 22:47:06 +03:00
}
}
void _sendSubscribe() {
_incrementMessageId();
_subscriptionMessageId = _currentMessageId;
2018-10-02 17:23:19 +03:00
_sendMessageRaw('{"id": $_subscriptionMessageId, "type": "subscribe_events", "event_type": "state_changed"}', false);
2018-09-25 22:47:06 +03:00
}
Future _getConfig() {
_configCompleter = new Completer();
_incrementMessageId();
_configMessageId = _currentMessageId;
2018-10-02 17:23:19 +03:00
_sendMessageRaw('{"id": $_configMessageId, "type": "get_config"}', false);
2018-09-25 22:47:06 +03:00
return _configCompleter.future;
}
Future _getStates() {
_statesCompleter = new Completer();
_incrementMessageId();
_statesMessageId = _currentMessageId;
2018-10-02 17:23:19 +03:00
_sendMessageRaw('{"id": $_statesMessageId, "type": "get_states"}', false);
2018-09-25 22:47:06 +03:00
return _statesCompleter.future;
}
2018-10-27 00:54:05 +03:00
Future _getLovelace() {
_lovelaceCompleter = new Completer();
_incrementMessageId();
_lovelaceMessageId = _currentMessageId;
_sendMessageRaw('{"id": $_lovelaceMessageId, "type": "lovelace/config"}', false);
return _lovelaceCompleter.future;
}
Future _getUserInfo() {
_userInfoCompleter = new Completer();
_incrementMessageId();
_userInfoMessageId = _currentMessageId;
_sendMessageRaw('{"id": $_userInfoMessageId, "type": "auth/current_user"}', false);
return _userInfoCompleter.future;
}
2018-09-25 22:47:06 +03:00
Future _getServices() {
_servicesCompleter = new Completer();
_incrementMessageId();
_servicesMessageId = _currentMessageId;
2018-10-02 17:23:19 +03:00
_sendMessageRaw('{"id": $_servicesMessageId, "type": "get_services"}', false);
2018-09-25 22:47:06 +03:00
return _servicesCompleter.future;
}
_incrementMessageId() {
_currentMessageId += 1;
}
2018-10-02 17:23:19 +03:00
void _sendAuthMessageRaw(String message) {
Logger.d( "[Sending] ==> auth request");
2018-10-02 17:23:19 +03:00
_hassioChannel.sink.add(message);
}
_sendMessageRaw(String message, bool queued) {
var sendCompleter = Completer();
2018-10-02 17:23:19 +03:00
if (queued) _messageQueue.add(message);
_connection().then((r) {
2018-10-02 17:23:19 +03:00
_messageQueue.getActualMessages().forEach((message){
Logger.d( "[Sending queued] ==> $message");
2018-10-02 17:23:19 +03:00
_hassioChannel.sink.add(message);
});
if (!queued) {
Logger.d( "[Sending] ==> $message");
2018-10-02 17:23:19 +03:00
_hassioChannel.sink.add(message);
}
sendCompleter.complete();
}).catchError((e){
sendCompleter.completeError(e);
});
return sendCompleter.future;
}
2018-10-16 17:35:13 +03:00
Future callService(String domain, String service, String entityId, Map<String, dynamic> additionalParams) {
_incrementMessageId();
String message = "";
if (entityId != null) {
message = '{"id": $_currentMessageId, "type": "call_service", "domain": "$domain", "service": "$service", "service_data": {"entity_id": "$entityId"';
if (additionalParams != null) {
additionalParams.forEach((name, value) {
if ((value is double) || (value is int) || (value is List)) {
message += ', "$name" : $value';
} else {
message += ', "$name" : "$value"';
}
});
}
message += '}}';
} else {
message = '{"id": $_currentMessageId, "type": "call_service", "domain": "$domain", "service": "$service"';
if (additionalParams != null && additionalParams.isNotEmpty) {
message += ', "service_data": {';
bool first = true;
additionalParams.forEach((name, value) {
if (!first) {
message += ', ';
}
if ((value is double) || (value is int) || (value is List)) {
message += '"$name" : $value';
} else {
message += '"$name" : "$value"';
}
first = false;
});
message += '}';
}
message += '}';
2018-09-25 22:47:06 +03:00
}
2018-10-02 17:23:19 +03:00
return _sendMessageRaw(message, true);
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']}");
2018-10-12 18:03:27 +03:00
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
}
void _parseConfig(Map data) {
if (data["success"] == true) {
_instanceConfig = Map.from(data["result"]);
_configCompleter.complete();
} else {
_configCompleter.completeError({"errorCode": 2, "errorMessage": data["error"]["message"]});
}
}
void _parseUserInfo(Map data) {
if (data["success"] == true) {
_userName = data["result"]["name"];
} else {
_userName = null;
Logger.w("There was an error getting current user: $data");
}
_userInfoCompleter.complete();
}
2018-09-25 22:47:06 +03:00
void _parseServices(response) {
_servicesCompleter.complete();
2018-10-27 00:54:05 +03:00
}
void _handleLovelace(response) {
if (response["success"] == true) {
_rawLovelaceData = response["result"];
} else {
Logger.e("There was an error getting Lovelace config: $response");
2018-10-27 00:54:05 +03:00
_rawLovelaceData = null;
2018-09-25 22:47:06 +03:00
}
2018-10-27 00:54:05 +03:00
_lovelaceCompleter.complete();
}
void _parseLovelace() {
Logger.d("--Title: ${_rawLovelaceData["title"]}");
2018-11-04 21:02:12 +02:00
ui.title = _rawLovelaceData["title"];
2018-10-27 00:54:05 +03:00
int viewCounter = 0;
Logger.d("--Views count: ${_rawLovelaceData['views'].length}");
2018-10-27 00:54:05 +03:00
_rawLovelaceData["views"].forEach((rawView){
Logger.d("----view id: ${rawView['id']}");
2018-10-27 00:54:05 +03:00
HAView view = HAView(
count: viewCounter,
2018-11-04 18:26:31 +02:00
id: "${rawView['id']}",
2018-10-27 00:54:05 +03:00
name: rawView['title'],
iconName: rawView['icon']
);
view.cards.addAll(_createLovelaceCards(rawView["cards"] ?? []));
ui.views.add(
view
);
viewCounter += 1;
});
}
List<HACard> _createLovelaceCards(List rawCards) {
List<HACard> result = [];
rawCards.forEach((rawCard){
bool isThereCardOptionsInside = rawCard["card"] != null;
2018-11-25 20:44:19 +02:00
HACard card = HACard(
id: "card",
name: isThereCardOptionsInside ? rawCard["card"]["title"] ?? rawCard["card"]["name"] : rawCard["title"] ?? rawCard["name"],
type: isThereCardOptionsInside ? rawCard["card"]['type'] : rawCard['type'],
columnsCount: isThereCardOptionsInside ? rawCard["card"]['columns'] ?? 4 : rawCard['columns'] ?? 4,
showName: isThereCardOptionsInside ? rawCard["card"]['show_name'] ?? true : rawCard['show_name'] ?? true,
showState: isThereCardOptionsInside ? rawCard["card"]['show_state'] ?? true : rawCard['show_state'] ?? true,
showEmpty: rawCard['show_empty'] ?? true,
2019-01-23 23:34:45 +02:00
stateFilter: rawCard['state_filter'] ?? [],
content: rawCard['content']
2018-11-25 20:44:19 +02:00
);
2018-10-27 00:54:05 +03:00
if (rawCard["cards"] != null) {
2018-11-25 20:44:19 +02:00
card.childCards = _createLovelaceCards(rawCard["cards"]);
}
rawCard["entities"]?.forEach((rawEntity) {
if (rawEntity is String) {
if (entities.isExist(rawEntity)) {
card.entities.add(EntityWrapper(entity: entities.get(rawEntity)));
}
} else {
if (entities.isExist(rawEntity["entity"])) {
Entity e = entities.get(rawEntity["entity"]);
card.entities.add(
EntityWrapper(
2018-11-25 20:44:19 +02:00
entity: e,
displayName: rawEntity["name"],
icon: rawEntity["icon"],
2018-12-14 14:28:23 +02:00
uiAction: EntityUIAction(rawEntityData: rawEntity)
)
2018-11-25 20:44:19 +02:00
);
2018-09-25 22:47:06 +03:00
}
2018-11-25 20:44:19 +02:00
}
});
if (rawCard["entity"] != null) {
var en = rawCard["entity"];
if (en is String) {
if (entities.isExist(en)) {
Entity e = entities.get(en);
card.linkedEntityWrapper = EntityWrapper(
entity: e,
2018-12-25 11:48:37 +02:00
icon: rawCard["icon"],
displayName: rawCard["name"],
2018-12-14 14:28:23 +02:00
uiAction: EntityUIAction(rawEntityData: rawCard)
2018-11-25 20:44:19 +02:00
);
}
} else {
if (entities.isExist(en["entity"])) {
Entity e = entities.get(en["entity"]);
card.linkedEntityWrapper = EntityWrapper(
entity: e,
2018-11-15 19:08:47 +02:00
icon: en["icon"],
displayName: en["name"],
2018-12-14 14:28:23 +02:00
uiAction: EntityUIAction(rawEntityData: rawCard)
2018-11-25 20:44:19 +02:00
);
2018-11-15 19:08:47 +02:00
}
2018-10-27 17:28:47 +03:00
}
2018-11-25 20:44:19 +02:00
2018-10-27 00:54:05 +03:00
}
2018-11-25 20:44:19 +02:00
result.add(card);
2018-10-27 00:54:05 +03:00
});
return result;
2018-09-25 22:47:06 +03:00
}
void _parseEntities(response) async {
if (response["success"] == false) {
_statesCompleter.completeError({"errorCode": 3, "errorMessage": response["error"]["message"]});
return;
}
2018-10-25 00:05:29 +03:00
entities.parse(response["result"]);
2018-09-25 22:47:06 +03:00
_statesCompleter.complete();
}
2018-10-07 02:17:14 +03:00
2018-10-27 00:54:05 +03:00
void _createUI() {
2018-11-04 21:02:12 +02:00
ui = HomeAssistantUI();
2018-10-27 00:54:05 +03:00
if ((_useLovelace) && (_rawLovelaceData != null)) {
Logger.d("Creating Lovelace UI");
2018-10-27 00:54:05 +03:00
_parseLovelace();
} else {
Logger.d("Creating group-based UI");
2018-10-27 00:54:05 +03:00
int viewCounter = 0;
if (!entities.hasDefaultView) {
HAView view = HAView(
count: viewCounter,
id: "group.default_view",
name: "Home",
childEntities: entities.filterEntitiesForDefaultView()
);
ui.views.add(
view
);
viewCounter += 1;
2018-10-25 00:54:20 +03:00
}
2018-10-27 00:54:05 +03:00
entities.viewEntities.forEach((viewEntity) {
HAView view = HAView(
count: viewCounter,
id: viewEntity.entityId,
name: viewEntity.displayName,
childEntities: viewEntity.childEntities
);
view.linkedEntity = viewEntity;
ui.views.add(
view
);
viewCounter += 1;
});
}
2018-10-25 00:54:20 +03:00
}
2018-10-27 00:54:05 +03:00
Widget buildViews(BuildContext context, bool lovelace) {
2018-10-25 00:05:29 +03:00
return ui.build(context);
2018-10-07 02:17:14 +03:00
}
2018-10-07 23:06:06 +03:00
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]);
String url = "$homeAssistantWebHost/api/history/period/$startTime?&filter_entity_id=$entityId";
Logger.d("[Sending] ==> $url");
2018-10-07 23:06:06 +03:00
http.Response historyResponse;
historyResponse = await http.get(url, headers: {
2018-10-07 23:06:06 +03:00
"authorization": "Bearer $_password",
"Content-Type": "application/json"
});
var history = json.decode(historyResponse.body);
if (history is List) {
Logger.d( "[Received] <== ${history.first.length} history recors");
return history;
} else {
return [];
2018-10-07 23:06:06 +03: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));
}
List<String> getActualMessages() {
_queue.removeWhere((item) => item.isExpired());
List<String> result = [];
_queue.forEach((haMessage){
result.add(haMessage.message);
});
this.clear();
return result;
}
void clear() {
_queue.clear();
}
}
class HAMessage {
DateTime _timeStamp;
int _messageTimeout;
String message;
HAMessage(this._messageTimeout, this.message) {
_timeStamp = DateTime.now();
}
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
}
2018-09-25 22:47:06 +03:00
}