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;
started = true;
}
streamUrl = '${Connection().httpWebHost}/api/camera_proxy_stream/${_entity
streamUrl = '${ConnectionManager().httpWebHost}/api/camera_proxy_stream/${_entity
.entityId}?token=${_entity.attributes['access_token']}';
return Column(
children: <Widget>[

View File

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

View File

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

View File

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

View File

@ -17,7 +17,7 @@ class AuthManager {
if (url.startsWith("http://ha-client.homemade.systems/service/auth_callback.html")) {
String authCode = url.split("=")[1];
Logger.d("We have auth code. Getting temporary access token...");
Connection().sendHTTPPost(
ConnectionManager().sendHTTPPost(
endPoint: "/auth/token",
contentType: "application/x-www-form-urlencoded",
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;
}
Connection._internal();
ConnectionManager._internal();
String _domain;
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;
}
@ -14,7 +14,7 @@ class Device {
String osName;
String osVersion;
Device._internal();
DeviceInfoManager._internal();
loadDeviceInfo() {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

View File

@ -4,10 +4,10 @@ class MobileAppIntegrationManager {
static final _appRegistrationData = {
"app_version": "$appVersion",
"device_name": "${HomeAssistant().userName}'s ${Device().model}",
"manufacturer": Device().manufacturer,
"model": Device().model,
"os_version": Device().osVersion,
"device_name": "${HomeAssistant().userName}'s ${DeviceInfoManager().model}",
"manufacturer": DeviceInfoManager().manufacturer,
"model": DeviceInfoManager().model,
"os_version": DeviceInfoManager().osVersion,
"app_data": {
"push_token": "${HomeAssistant().fcmToken}",
"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}) {
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...");
var registrationData = Map.from(_appRegistrationData);
registrationData.addAll({
"app_id": "ha_client",
"app_name": "$appName",
"os_name": Device().osName,
"os_name": DeviceInfoManager().osName,
"supports_encryption": false,
});
Connection().sendHTTPPost(
ConnectionManager().sendHTTPPost(
endPoint: "/api/mobile_app/registrations",
includeAuthHeader: true,
data: json.encode(registrationData)
@ -34,7 +34,7 @@ class MobileAppIntegrationManager {
var responseObject = json.decode(response);
SharedPreferences.getInstance().then((prefs) {
prefs.setString("app-webhook-id", responseObject["webhook_id"]);
Connection().webhookId = responseObject["webhook_id"];
ConnectionManager().webhookId = responseObject["webhook_id"];
completer.complete();
eventBus.fire(ShowPopupDialogEvent(
title: "Mobile app Integration was created",
@ -42,7 +42,7 @@ class MobileAppIntegrationManager {
positiveText: "Restart now",
negativeText: "Later",
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",
"data": _appRegistrationData
};
Connection().sendHTTPPost(
endPoint: "/api/webhook/${Connection().webhookId}",
ConnectionManager().sendHTTPPost(
endPoint: "/api/webhook/${ConnectionManager().webhookId}",
includeAuthHeader: false,
data: json.encode(updateData)
).then((response) {
@ -111,7 +111,7 @@ class MobileAppIntegrationManager {
onPositive: () {
SharedPreferences.getInstance().then((prefs) {
prefs.remove("app-webhook-id");
Connection().webhookId = null;
ConnectionManager().webhookId = null;
checkAppRegistration();
});
},

View File

@ -57,7 +57,7 @@ class _ConfigPanelWidgetState extends State<ConfigPanelWidget> {
positiveText: "Sure. Make it so",
negativeText: "What?? No!",
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",
negativeText: "What?? No!",
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)),
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,),
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(),
@ -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,),
LinkToWebConfig(name: "Integrations", url: Connection().httpWebHost+"/config/integrations/dashboard"),
LinkToWebConfig(name: "Users", url: Connection().httpWebHost+"/config/users/picker"),
LinkToWebConfig(name: "Integrations", url: ConnectionManager().httpWebHost+"/config/integrations/dashboard"),
LinkToWebConfig(name: "Users", url: ConnectionManager().httpWebHost+"/config/users/picker"),
Container(height: 8.0,),
LinkToWebConfig(name: "General", url: Connection().httpWebHost+"/config/core"),
LinkToWebConfig(name: "Server Control", url: Connection().httpWebHost+"/config/server_control"),
LinkToWebConfig(name: "Persons", url: Connection().httpWebHost+"/config/person"),
LinkToWebConfig(name: "Entity Registry", url: Connection().httpWebHost+"/config/entity_registry"),
LinkToWebConfig(name: "Area Registry", url: Connection().httpWebHost+"/config/area_registry"),
LinkToWebConfig(name: "Automation", url: Connection().httpWebHost+"/config/automation"),
LinkToWebConfig(name: "Script", url: Connection().httpWebHost+"/config/script"),
LinkToWebConfig(name: "Customization", url: Connection().httpWebHost+"/config/customize"),
LinkToWebConfig(name: "General", url: ConnectionManager().httpWebHost+"/config/core"),
LinkToWebConfig(name: "Server Control", url: ConnectionManager().httpWebHost+"/config/server_control"),
LinkToWebConfig(name: "Persons", url: ConnectionManager().httpWebHost+"/config/person"),
LinkToWebConfig(name: "Entity Registry", url: ConnectionManager().httpWebHost+"/config/entity_registry"),
LinkToWebConfig(name: "Area Registry", url: ConnectionManager().httpWebHost+"/config/area_registry"),
LinkToWebConfig(name: "Automation", url: ConnectionManager().httpWebHost+"/config/automation"),
LinkToWebConfig(name: "Script", url: ConnectionManager().httpWebHost+"/config/script"),
LinkToWebConfig(name: "Customization", url: ConnectionManager().httpWebHost+"/config/customize"),
],
);
}

View File

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