Refactor ConnectionManager and DeviceInfoManager

This commit is contained in:
estevez-dev 2019-08-31 22:10:07 +03:00
parent 3e12f4f8a4
commit f9c37f5084
10 changed files with 64 additions and 64 deletions

View File

@ -47,7 +47,7 @@ class _CameraStreamViewState extends State<CameraStreamView> {
.entity; .entity;
started = true; started = true;
} }
streamUrl = '${Connection().httpWebHost}/api/camera_proxy_stream/${_entity streamUrl = '${ConnectionManager().httpWebHost}/api/camera_proxy_stream/${_entity
.entityId}?token=${_entity.attributes['access_token']}'; .entityId}?token=${_entity.attributes['access_token']}';
return Column( return Column(
children: <Widget>[ children: <Widget>[

View File

@ -47,7 +47,7 @@ class _EntityHistoryWidgetState extends State<EntityHistoryWidget> {
} }
if (_historyLastUpdated == null || now.difference(_historyLastUpdated).inSeconds > 30) { if (_historyLastUpdated == null || now.difference(_historyLastUpdated).inSeconds > 30) {
_historyLastUpdated = now; _historyLastUpdated = now;
Connection().getHistory(entityId).then((history){ ConnectionManager().getHistory(entityId).then((history){
if (!_disposed) { if (!_disposed) {
setState(() { setState(() {
_history = history.isNotEmpty ? history[0] : []; _history = history.isNotEmpty ? history[0] : [];

View File

@ -23,7 +23,7 @@ class HomeAssistant {
Duration fetchTimeout = Duration(seconds: 30); Duration fetchTimeout = Duration(seconds: 30);
String get locationName { String get locationName {
if (Connection().useLovelace) { if (ConnectionManager().useLovelace) {
return ui?.title ?? ""; return ui?.title ?? "";
} else { } else {
return _instanceConfig["location_name"] ?? ""; return _instanceConfig["location_name"] ?? "";
@ -36,8 +36,8 @@ class HomeAssistant {
bool get isMobileAppEnabled => _instanceConfig["components"] != null && (_instanceConfig["components"] as List).contains("mobile_app"); bool get isMobileAppEnabled => _instanceConfig["components"] != null && (_instanceConfig["components"] as List).contains("mobile_app");
HomeAssistant._internal() { HomeAssistant._internal() {
Connection().onStateChangeCallback = _handleEntityStateChange; ConnectionManager().onStateChangeCallback = _handleEntityStateChange;
Device().loadDeviceInfo(); DeviceInfoManager().loadDeviceInfo();
} }
Completer _fetchCompleter; Completer _fetchCompleter;
@ -47,18 +47,18 @@ class HomeAssistant {
Logger.w("Previous data fetch is not completed yet"); Logger.w("Previous data fetch is not completed yet");
return _fetchCompleter.future; return _fetchCompleter.future;
} }
if (entities == null) entities = EntityCollection(Connection().httpWebHost); if (entities == null) entities = EntityCollection(ConnectionManager().httpWebHost);
_fetchCompleter = Completer(); _fetchCompleter = Completer();
List<Future> futures = []; List<Future> futures = [];
futures.add(_getStates()); futures.add(_getStates());
if (Connection().useLovelace) { if (ConnectionManager().useLovelace) {
futures.add(_getLovelace()); futures.add(_getLovelace());
} }
futures.add(_getConfig()); futures.add(_getConfig());
futures.add(_getServices()); futures.add(_getServices());
futures.add(_getUserInfo()); futures.add(_getUserInfo());
futures.add(_getPanels()); futures.add(_getPanels());
futures.add(Connection().sendSocketMessage( futures.add(ConnectionManager().sendSocketMessage(
type: "subscribe_events", type: "subscribe_events",
additionalData: {"event_type": "state_changed"}, additionalData: {"event_type": "state_changed"},
)); ));
@ -78,7 +78,7 @@ class HomeAssistant {
Future logout() async { Future logout() async {
Logger.d("Logging out..."); Logger.d("Logging out...");
await Connection().logout().then((_) { await ConnectionManager().logout().then((_) {
ui?.clear(); ui?.clear();
entities?.clear(); entities?.clear();
panels?.clear(); panels?.clear();
@ -86,7 +86,7 @@ class HomeAssistant {
} }
Future _getConfig() async { Future _getConfig() async {
await Connection().sendSocketMessage(type: "get_config").then((data) { await ConnectionManager().sendSocketMessage(type: "get_config").then((data) {
_instanceConfig = Map.from(data); _instanceConfig = Map.from(data);
}).catchError((e) { }).catchError((e) {
throw HAError("Error getting config: ${e}"); throw HAError("Error getting config: ${e}");
@ -94,7 +94,7 @@ class HomeAssistant {
} }
Future _getStates() async { Future _getStates() async {
await Connection().sendSocketMessage(type: "get_states").then( await ConnectionManager().sendSocketMessage(type: "get_states").then(
(data) => entities.parse(data) (data) => entities.parse(data)
).catchError((e) { ).catchError((e) {
throw HAError("Error getting states: $e"); throw HAError("Error getting states: $e");
@ -102,27 +102,27 @@ class HomeAssistant {
} }
Future _getLovelace() async { Future _getLovelace() async {
await Connection().sendSocketMessage(type: "lovelace/config").then((data) => _rawLovelaceData = data).catchError((e) { await ConnectionManager().sendSocketMessage(type: "lovelace/config").then((data) => _rawLovelaceData = data).catchError((e) {
throw HAError("Error getting lovelace config: $e"); throw HAError("Error getting lovelace config: $e");
}); });
} }
Future _getUserInfo() async { Future _getUserInfo() async {
_userName = null; _userName = null;
await Connection().sendSocketMessage(type: "auth/current_user").then((data) => _userName = data["name"]).catchError((e) { await ConnectionManager().sendSocketMessage(type: "auth/current_user").then((data) => _userName = data["name"]).catchError((e) {
Logger.w("Can't get user info: ${e}"); Logger.w("Can't get user info: ${e}");
}); });
} }
Future _getServices() async { Future _getServices() async {
await Connection().sendSocketMessage(type: "get_services").then((data) => Logger.d("Services received")).catchError((e) { await ConnectionManager().sendSocketMessage(type: "get_services").then((data) => Logger.d("Services received")).catchError((e) {
Logger.w("Can't get services: ${e}"); Logger.w("Can't get services: ${e}");
}); });
} }
Future _getPanels() async { Future _getPanels() async {
panels.clear(); panels.clear();
await Connection().sendSocketMessage(type: "get_panels").then((data) { await ConnectionManager().sendSocketMessage(type: "get_panels").then((data) {
data.forEach((k,v) { data.forEach((k,v) {
String title = v['title'] == null ? "${k[0].toUpperCase()}${k.substring(1)}" : "${v['title'][0].toUpperCase()}${v['title'].substring(1)}"; String title = v['title'] == null ? "${k[0].toUpperCase()}${k.substring(1)}" : "${v['title'][0].toUpperCase()}${v['title'].substring(1)}";
panels.add(Panel( panels.add(Panel(
@ -305,7 +305,7 @@ class HomeAssistant {
void _createUI() { void _createUI() {
ui = HomeAssistantUI(); ui = HomeAssistantUI();
if ((Connection().useLovelace) && (_rawLovelaceData != null)) { if ((ConnectionManager().useLovelace) && (_rawLovelaceData != null)) {
Logger.d("Creating Lovelace UI"); Logger.d("Creating Lovelace UI");
_parseLovelace(); _parseLovelace();
} else { } else {

View File

@ -104,8 +104,8 @@ part 'entity_collection.class.dart';
part 'managers/auth_manager.class.dart'; part 'managers/auth_manager.class.dart';
part 'managers/location_manager.class.dart'; part 'managers/location_manager.class.dart';
part 'managers/mobile_app_integration_manager.class.dart'; part 'managers/mobile_app_integration_manager.class.dart';
part 'connection.class.dart'; part 'managers/connection_manager.class.dart';
part 'device.class.dart'; part 'managers/device_info_manager.class.dart';
part 'ui_class/ui.dart'; part 'ui_class/ui.dart';
part 'ui_class/view.class.dart'; part 'ui_class/view.class.dart';
part 'ui_class/card.class.dart'; part 'ui_class/card.class.dart';
@ -166,7 +166,7 @@ class HAClientApp extends StatelessWidget {
"/putchase": (context) => PurchasePage(title: "Support app development"), "/putchase": (context) => PurchasePage(title: "Support app development"),
"/log-view": (context) => LogViewPage(title: "Log"), "/log-view": (context) => LogViewPage(title: "Log"),
"/login": (context) => WebviewScaffold( "/login": (context) => WebviewScaffold(
url: "${Connection().oauthUrl}", url: "${ConnectionManager().oauthUrl}",
appBar: new AppBar( appBar: new AppBar(
leading: IconButton( leading: IconButton(
icon: Icon(Icons.help), icon: Icon(Icons.help),
@ -287,7 +287,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
void _fullLoad() async { void _fullLoad() async {
_showInfoBottomBar(progress: true,); _showInfoBottomBar(progress: true,);
_subscribe().then((_) { _subscribe().then((_) {
Connection().init(loadSettings: true, forceReconnect: true).then((__){ ConnectionManager().init(loadSettings: true, forceReconnect: true).then((__){
LocationManager(); LocationManager();
_fetchData(); _fetchData();
}, onError: (e) { }, onError: (e) {
@ -299,7 +299,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
void _quickLoad() { void _quickLoad() {
_hideBottomBar(); _hideBottomBar();
_showInfoBottomBar(progress: true,); _showInfoBottomBar(progress: true,);
Connection().init(loadSettings: false, forceReconnect: false).then((_){ ConnectionManager().init(loadSettings: false, forceReconnect: false).then((_){
_fetchData(); _fetchData();
}, onError: (e) { }, onError: (e) {
_setErrorState(e); _setErrorState(e);
@ -328,7 +328,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
@override @override
void didChangeAppLifecycleState(AppLifecycleState state) { void didChangeAppLifecycleState(AppLifecycleState state) {
Logger.d("$state"); Logger.d("$state");
if (state == AppLifecycleState.resumed && Connection().settingsLoaded) { if (state == AppLifecycleState.resumed && ConnectionManager().settingsLoaded) {
_quickLoad(); _quickLoad();
} }
} }
@ -486,7 +486,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
message: "Calling $domain.$service", message: "Calling $domain.$service",
duration: Duration(seconds: 3) duration: Duration(seconds: 3)
); );
Connection().callService(domain: domain, service: service, entityId: entityId, additionalServiceData: additionalParams).catchError((e) => _setErrorState(e)); ConnectionManager().callService(domain: domain, service: service, entityId: entityId, additionalServiceData: additionalParams).catchError((e) => _setErrorState(e));
} }
void _showEntityPage(String entityId) { void _showEntityPage(String entityId) {
@ -515,7 +515,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
menuItems.add( menuItems.add(
UserAccountsDrawerHeader( UserAccountsDrawerHeader(
accountName: Text(widget.homeAssistant.userName), accountName: Text(widget.homeAssistant.userName),
accountEmail: Text(Connection().displayHostname ?? "Not configured"), accountEmail: Text(ConnectionManager().displayHostname ?? "Not configured"),
/*onDetailsPressed: () { /*onDetailsPressed: () {
setState(() { setState(() {
_accountMenuExpanded = !_accountMenuExpanded; _accountMenuExpanded = !_accountMenuExpanded;
@ -552,7 +552,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
new ListTile( new ListTile(
leading: Icon(MaterialDesignIcons.getIconDataFromIconName("mdi:home-assistant")), leading: Icon(MaterialDesignIcons.getIconDataFromIconName("mdi:home-assistant")),
title: Text("Open Web UI"), title: Text("Open Web UI"),
onTap: () => HAUtils.launchURL(Connection().httpWebHost), onTap: () => HAUtils.launchURL(ConnectionManager().httpWebHost),
) )
); );
menuItems.addAll([ menuItems.addAll([
@ -777,7 +777,7 @@ class _MainPageState extends State<MainPage> with WidgetsBindingObserver, Ticker
List<Widget> emptyBody = [ List<Widget> emptyBody = [
Text("."), Text("."),
]; ];
if (Connection().isAuthenticated) { if (ConnectionManager().isAuthenticated) {
_showLoginButton = false; _showLoginButton = false;
popupMenuItems.add( popupMenuItems.add(
PopupMenuItem<String>( PopupMenuItem<String>(

View File

@ -17,7 +17,7 @@ class AuthManager {
if (url.startsWith("http://ha-client.homemade.systems/service/auth_callback.html")) { if (url.startsWith("http://ha-client.homemade.systems/service/auth_callback.html")) {
String authCode = url.split("=")[1]; String authCode = url.split("=")[1];
Logger.d("We have auth code. Getting temporary access token..."); Logger.d("We have auth code. Getting temporary access token...");
Connection().sendHTTPPost( ConnectionManager().sendHTTPPost(
endPoint: "/auth/token", endPoint: "/auth/token",
contentType: "application/x-www-form-urlencoded", contentType: "application/x-www-form-urlencoded",
includeAuthHeader: false, includeAuthHeader: false,

View File

@ -1,14 +1,14 @@
part of 'main.dart'; part of '../main.dart';
class Connection { class ConnectionManager {
static final Connection _instance = Connection._internal(); static final ConnectionManager _instance = ConnectionManager._internal();
factory Connection() { factory ConnectionManager() {
return _instance; return _instance;
} }
Connection._internal(); ConnectionManager._internal();
String _domain; String _domain;
String _port; String _port;

View File

@ -1,10 +1,10 @@
part of 'main.dart'; part of '../main.dart';
class Device { class DeviceInfoManager {
static final Device _instance = Device._internal(); static final DeviceInfoManager _instance = DeviceInfoManager._internal();
factory Device() { factory DeviceInfoManager() {
return _instance; return _instance;
} }
@ -14,7 +14,7 @@ class Device {
String osName; String osName;
String osVersion; String osVersion;
Device._internal(); DeviceInfoManager._internal();
loadDeviceInfo() { loadDeviceInfo() {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

View File

@ -4,10 +4,10 @@ class MobileAppIntegrationManager {
static final _appRegistrationData = { static final _appRegistrationData = {
"app_version": "$appVersion", "app_version": "$appVersion",
"device_name": "${HomeAssistant().userName}'s ${Device().model}", "device_name": "${HomeAssistant().userName}'s ${DeviceInfoManager().model}",
"manufacturer": Device().manufacturer, "manufacturer": DeviceInfoManager().manufacturer,
"model": Device().model, "model": DeviceInfoManager().model,
"os_version": Device().osVersion, "os_version": DeviceInfoManager().osVersion,
"app_data": { "app_data": {
"push_token": "${HomeAssistant().fcmToken}", "push_token": "${HomeAssistant().fcmToken}",
"push_url": "https://us-central1-ha-client-c73c4.cloudfunctions.net/sendPushNotification" "push_url": "https://us-central1-ha-client-c73c4.cloudfunctions.net/sendPushNotification"
@ -16,16 +16,16 @@ class MobileAppIntegrationManager {
static Future checkAppRegistration({bool forceRegister: false, bool showOkDialog: false}) { static Future checkAppRegistration({bool forceRegister: false, bool showOkDialog: false}) {
Completer completer = Completer(); Completer completer = Completer();
if (Connection().webhookId == null || forceRegister) { if (ConnectionManager().webhookId == null || forceRegister) {
Logger.d("Mobile app was not registered yet or need to be reseted. Registering..."); Logger.d("Mobile app was not registered yet or need to be reseted. Registering...");
var registrationData = Map.from(_appRegistrationData); var registrationData = Map.from(_appRegistrationData);
registrationData.addAll({ registrationData.addAll({
"app_id": "ha_client", "app_id": "ha_client",
"app_name": "$appName", "app_name": "$appName",
"os_name": Device().osName, "os_name": DeviceInfoManager().osName,
"supports_encryption": false, "supports_encryption": false,
}); });
Connection().sendHTTPPost( ConnectionManager().sendHTTPPost(
endPoint: "/api/mobile_app/registrations", endPoint: "/api/mobile_app/registrations",
includeAuthHeader: true, includeAuthHeader: true,
data: json.encode(registrationData) data: json.encode(registrationData)
@ -34,7 +34,7 @@ class MobileAppIntegrationManager {
var responseObject = json.decode(response); var responseObject = json.decode(response);
SharedPreferences.getInstance().then((prefs) { SharedPreferences.getInstance().then((prefs) {
prefs.setString("app-webhook-id", responseObject["webhook_id"]); prefs.setString("app-webhook-id", responseObject["webhook_id"]);
Connection().webhookId = responseObject["webhook_id"]; ConnectionManager().webhookId = responseObject["webhook_id"];
completer.complete(); completer.complete();
eventBus.fire(ShowPopupDialogEvent( eventBus.fire(ShowPopupDialogEvent(
title: "Mobile app Integration was created", title: "Mobile app Integration was created",
@ -42,7 +42,7 @@ class MobileAppIntegrationManager {
positiveText: "Restart now", positiveText: "Restart now",
negativeText: "Later", negativeText: "Later",
onPositive: () { onPositive: () {
Connection().callService(domain: "homeassistant", service: "restart", entityId: null); ConnectionManager().callService(domain: "homeassistant", service: "restart", entityId: null);
}, },
)); ));
}); });
@ -57,8 +57,8 @@ class MobileAppIntegrationManager {
"type": "update_registration", "type": "update_registration",
"data": _appRegistrationData "data": _appRegistrationData
}; };
Connection().sendHTTPPost( ConnectionManager().sendHTTPPost(
endPoint: "/api/webhook/${Connection().webhookId}", endPoint: "/api/webhook/${ConnectionManager().webhookId}",
includeAuthHeader: false, includeAuthHeader: false,
data: json.encode(updateData) data: json.encode(updateData)
).then((response) { ).then((response) {
@ -111,7 +111,7 @@ class MobileAppIntegrationManager {
onPositive: () { onPositive: () {
SharedPreferences.getInstance().then((prefs) { SharedPreferences.getInstance().then((prefs) {
prefs.remove("app-webhook-id"); prefs.remove("app-webhook-id");
Connection().webhookId = null; ConnectionManager().webhookId = null;
checkAppRegistration(); checkAppRegistration();
}); });
}, },

View File

@ -57,7 +57,7 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
positiveText: "Sure. Make it so", positiveText: "Sure. Make it so",
negativeText: "What?? No!", negativeText: "What?? No!",
onPositive: () { onPositive: () {
Connection().callService(domain: "homeassistant", service: "restart", entityId: null); ConnectionManager().callService(domain: "homeassistant", service: "restart", entityId: null);
}, },
)); ));
} }
@ -69,7 +69,7 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
positiveText: "Sure. Make it so", positiveText: "Sure. Make it so",
negativeText: "What?? No!", negativeText: "What?? No!",
onPositive: () { onPositive: () {
Connection().callService(domain: "homeassistant", service: "stop", entityId: null); ConnectionManager().callService(domain: "homeassistant", service: "stop", entityId: null);
}, },
)); ));
} }
@ -108,7 +108,7 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
), ),
Text("Registration", style: TextStyle(fontSize: Sizes.largeFontSize-2)), Text("Registration", style: TextStyle(fontSize: Sizes.largeFontSize-2)),
Container(height: Sizes.rowPadding,), Container(height: Sizes.rowPadding,),
Text("${HomeAssistant().userName}'s ${Device().model}, ${Device().osName} ${Device().osVersion}"), Text("${HomeAssistant().userName}'s ${DeviceInfoManager().model}, ${DeviceInfoManager().osName} ${DeviceInfoManager().osVersion}"),
Container(height: 6.0,), Container(height: 6.0,),
Text("Here you can manually check if HA Client integration with your Home Assistant works fine. As mobileApp integration in Home Assistant is still in development, this is not 100% correct check."), Text("Here you can manually check if HA Client integration with your Home Assistant works fine. As mobileApp integration in Home Assistant is still in development, this is not 100% correct check."),
//Divider(), //Divider(),
@ -154,19 +154,19 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
), ),
), ),
), ),
LinkToWebConfig(name: "Home Assistant Cloud", url: Connection().httpWebHost+"/config/cloud/account"), LinkToWebConfig(name: "Home Assistant Cloud", url: ConnectionManager().httpWebHost+"/config/cloud/account"),
Container(height: 8.0,), Container(height: 8.0,),
LinkToWebConfig(name: "Integrations", url: Connection().httpWebHost+"/config/integrations/dashboard"), LinkToWebConfig(name: "Integrations", url: ConnectionManager().httpWebHost+"/config/integrations/dashboard"),
LinkToWebConfig(name: "Users", url: Connection().httpWebHost+"/config/users/picker"), LinkToWebConfig(name: "Users", url: ConnectionManager().httpWebHost+"/config/users/picker"),
Container(height: 8.0,), Container(height: 8.0,),
LinkToWebConfig(name: "General", url: Connection().httpWebHost+"/config/core"), LinkToWebConfig(name: "General", url: ConnectionManager().httpWebHost+"/config/core"),
LinkToWebConfig(name: "Server Control", url: Connection().httpWebHost+"/config/server_control"), LinkToWebConfig(name: "Server Control", url: ConnectionManager().httpWebHost+"/config/server_control"),
LinkToWebConfig(name: "Persons", url: Connection().httpWebHost+"/config/person"), LinkToWebConfig(name: "Persons", url: ConnectionManager().httpWebHost+"/config/person"),
LinkToWebConfig(name: "Entity Registry", url: Connection().httpWebHost+"/config/entity_registry"), LinkToWebConfig(name: "Entity Registry", url: ConnectionManager().httpWebHost+"/config/entity_registry"),
LinkToWebConfig(name: "Area Registry", url: Connection().httpWebHost+"/config/area_registry"), LinkToWebConfig(name: "Area Registry", url: ConnectionManager().httpWebHost+"/config/area_registry"),
LinkToWebConfig(name: "Automation", url: Connection().httpWebHost+"/config/automation"), LinkToWebConfig(name: "Automation", url: ConnectionManager().httpWebHost+"/config/automation"),
LinkToWebConfig(name: "Script", url: Connection().httpWebHost+"/config/script"), LinkToWebConfig(name: "Script", url: ConnectionManager().httpWebHost+"/config/script"),
LinkToWebConfig(name: "Customization", url: Connection().httpWebHost+"/config/customize"), LinkToWebConfig(name: "Customization", url: ConnectionManager().httpWebHost+"/config/customize"),
], ],
); );
} }

View File

@ -36,7 +36,7 @@ class Panel {
) )
); );
} else { } else {
String url = "${Connection().httpWebHost}/$urlPath"; String url = "${ConnectionManager().httpWebHost}/$urlPath";
Logger.d("Launching custom tab with $url"); Logger.d("Launching custom tab with $url");
HAUtils.launchURLInCustomTab(context: context, url: url); HAUtils.launchURLInCustomTab(context: context, url: url);
} }