Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Excluded generic app from installDist Implemented providers in Generic App

Michael Rademakera1f101917696
diff --git a/console/generic_app/.buildignore b/console/generic_app/.buildignore
deleted file mode 100644
index 5322bb279..000000000
--- a/console/generic_app/.buildignore
+++ /dev/null
@@ -1 +0,0 @@
-# Ignore this project in composite/superproject build
\ No newline at end of file
diff --git a/console/generic_app/android/app/src/main/AndroidManifest.xml b/console/generic_app/android/app/src/main/AndroidManifest.xml
index 04304ba4a..05f783ef7 100644
--- a/console/generic_app/android/app/src/main/AndroidManifest.xml
+++ b/console/generic_app/android/app/src/main/AndroidManifest.xml
@@ -26,6 +26,11 @@
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
+
+ <intent-filter>
+ <action android:name="FLUTTER_NOTIFICATION_CLICK" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
diff --git a/console/generic_app/ios/Runner/AppDelegate.swift b/console/generic_app/ios/Runner/AppDelegate.swift
index 70693e4a8..c295d8275 100644
--- a/console/generic_app/ios/Runner/AppDelegate.swift
+++ b/console/generic_app/ios/Runner/AppDelegate.swift
@@ -8,6 +8,9 @@ import Flutter
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
+
+ [UNUserNotificationCenter currentNotificationCenter].delegate = (id) self;
+
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
diff --git a/console/generic_app/lib/ConsoleProviders/GeofenceProvider.dart b/console/generic_app/lib/ConsoleProviders/GeofenceProvider.dart
index 0ca6722c7..ba669998a 100644
--- a/console/generic_app/lib/ConsoleProviders/GeofenceProvider.dart
+++ b/console/generic_app/lib/ConsoleProviders/GeofenceProvider.dart
@@ -1,6 +1,4 @@
-import 'dart:collection';
import 'dart:convert';
-import 'dart:html';
import 'package:flutter/material.dart';
import 'package:flutter_geofence/Geolocation.dart';
@@ -11,7 +9,7 @@ import 'package:generic_app/network/ApiManager.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
-typedef GeofenceCallback = Function(Map<String, dynamic>);
+import 'ProviderConstants.dart';
class GeofenceProvider {
static const String baseUrlKey = "baseUrl";
@@ -24,8 +22,8 @@ class GeofenceProvider {
final SharedPreferences _sharedPreferences;
final ApiManager _apiManager;
- GeofenceCallback _enableCallback;
- GeofenceCallback _getLocationCallback;
+ ProviderCallback _enableCallback;
+ ProviderCallback _getLocationCallback;
String _baseURL;
String _consoleId;
@@ -72,7 +70,7 @@ class GeofenceProvider {
};
}
- enable(String baseUrl, String consoleId, GeofenceCallback callback) async {
+ enable(String baseUrl, String consoleId, ProviderCallback callback) async {
this._baseURL = baseUrl;
this._consoleId = consoleId;
this._apiManager.baseUrl = baseUrl;
@@ -83,31 +81,28 @@ class GeofenceProvider {
this._enableCallback = callback;
if (await Permission.locationAlways.isGranted) {
- Geofence.initialize();
- Geofence.startListening(GeolocationEvent.entry, (geolocation) {
- _queueSendLocation(geofences.firstWhere((element) => element.id == geolocation.id), {"type": "Point", "coordinates": [geolocation.longitude, geolocation.latitude]});
- });
- Geofence.startListening(GeolocationEvent.exit, (geolocation) {
- _queueSendLocation(geofences.firstWhere((element) => element.id == geolocation.id), null);
- });
+ _startGeofenceProvider();
_enableCallback?.call({
"action": "PROVIDER_ENABLE",
"provider": "geofence",
"hasPermission": await Permission.locationAlways.isGranted,
"success": true
});
+ Future.delayed(Duration(seconds: 5)).then((value) => refreshGeofences());
} else {
if (await Permission.locationAlways.isUndetermined) {
Permission.locationAlways.request().then((value) {
+ if (value.isGranted) {
+ _startGeofenceProvider();
+ Future.delayed(Duration(seconds: 5))
+ .then((value) => refreshGeofences());
+ }
_enableCallback?.call({
"action": "PROVIDER_ENABLE",
"provider": "geofence",
"hasPermission": value.isGranted,
"success": true
});
- if (value.isGranted) {
- Geofence.initialize();
- }
});
} else {
_enableCallback?.call({
@@ -130,7 +125,6 @@ class GeofenceProvider {
await _sharedPreferences.setBool(geoDisabledKey, true);
await _sharedPreferences.remove(baseUrlKey);
- await _sharedPreferences.remove(consoleIdKey);
return {
"action": "PROVIDER_DISABLE",
"provider": "geofence",
@@ -147,6 +141,22 @@ class GeofenceProvider {
Geofence.addGeolocation(geolocation, GeolocationEvent.exit);
}
+ _startGeofenceProvider() {
+ Geofence.initialize();
+ Geofence.startListening(GeolocationEvent.entry, (geolocation) {
+ _queueSendLocation(
+ geofences.firstWhere((element) => element.id == geolocation.id), {
+ "type": "Point",
+ "coordinates": [geolocation.longitude, geolocation.latitude]
+ });
+ });
+ Geofence.startListening(GeolocationEvent.exit, (geolocation) {
+ _queueSendLocation(
+ geofences.firstWhere((element) => element.id == geolocation.id),
+ null);
+ });
+ }
+
removeGeofence(String id) {
Geofence.removeGeolocation(new Geolocation(id: id), GeolocationEvent.exit);
Geofence.removeGeolocation(new Geolocation(id: id), GeolocationEvent.entry);
@@ -239,12 +249,16 @@ class GeofenceProvider {
_sendLocation(GeofenceDefinition geofenceDefinition,
Map<String, dynamic> locationData) {
return _apiManager
- .post(overrideUrl: geofenceDefinition.url, rawModel: locationData != null ? jsonEncode(locationData) : null.toString())
+ .post(
+ overrideUrl: geofenceDefinition.url,
+ rawModel: locationData != null
+ ? jsonEncode(locationData)
+ : null.toString())
.then((value) => true)
.catchError((error) => false);
}
- getLocation(GeofenceCallback callback, BuildContext context) async {
+ getLocation(ProviderCallback callback, BuildContext context) async {
_getLocationCallback = callback;
if (await Permission.locationAlways.isGranted) {
diff --git a/console/generic_app/lib/ConsoleProviders/ProviderConstants.dart b/console/generic_app/lib/ConsoleProviders/ProviderConstants.dart
new file mode 100644
index 000000000..5d9dcf766
--- /dev/null
+++ b/console/generic_app/lib/ConsoleProviders/ProviderConstants.dart
@@ -0,0 +1 @@
+typedef ProviderCallback = Function(Map<String, dynamic>);
\ No newline at end of file
diff --git a/console/generic_app/lib/ConsoleProviders/PushProvider.dart b/console/generic_app/lib/ConsoleProviders/PushProvider.dart
new file mode 100644
index 000000000..fd3b96bdd
--- /dev/null
+++ b/console/generic_app/lib/ConsoleProviders/PushProvider.dart
@@ -0,0 +1,84 @@
+import 'package:firebase_messaging/firebase_messaging.dart';
+import 'package:permission_handler/permission_handler.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+import 'ProviderConstants.dart';
+
+class PushProvider {
+ static const String consoleIdKey = "consoleId";
+ static const String pushDisabledKey = "pushDisabled";
+
+ final String _version = "fcm";
+ final SharedPreferences _sharedPreferences;
+ final FirebaseMessaging _fcm;
+
+ String _consoleId;
+
+ PushProvider._internal(this._sharedPreferences, this._fcm);
+
+ static Future<PushProvider> getInstance() async {
+ return PushProvider._internal(
+ await SharedPreferences.getInstance(), FirebaseMessaging());
+ }
+
+ initialize() async {
+ return {
+ "action": "PROVIDER_INIT",
+ "provider": "geofence",
+ "version": _version,
+ "requiresPermission": true,
+ "hasPermission": await Permission.notification.isGranted,
+ "success": true,
+ "enabled": false,
+ "disabled": _sharedPreferences.containsKey(pushDisabledKey) &&
+ _sharedPreferences.getBool(pushDisabledKey)
+ };
+ }
+
+ enable(String consoleId, ProviderCallback callback) async {
+ _consoleId = consoleId;
+ await _sharedPreferences.setString(consoleIdKey, consoleId);
+ await _sharedPreferences.setBool(pushDisabledKey, false);
+
+ if (await Permission.notification.isGranted) {
+ } else {
+ if (await Permission.notification.isUndetermined) {
+ Permission.notification.request().then((value) {
+ if (value.isGranted) {
+ _fcm.getToken().then((token) {
+ callback?.call({
+ "action": "PROVIDER_ENABLE",
+ "provider": "push",
+ "hasPermission": value.isGranted,
+ "success": true,
+ "data": {"token": token}
+ });
+ });
+ } else {
+ callback?.call({
+ "action": "PROVIDER_ENABLE",
+ "provider": "push",
+ "hasPermission": value.isGranted,
+ "success": true
+ });
+ }
+ });
+ } else {
+ callback?.call({
+ "action": "PROVIDER_ENABLE",
+ "provider": "push",
+ "hasPermission": false,
+ "success": true
+ });
+ }
+ }
+ }
+
+ disable() async {
+ await _sharedPreferences.setBool(pushDisabledKey, true);
+ return {
+ "action": "PROVIDER_DISABLE",
+ "provider": "push",
+ };
+ }
+}
diff --git a/console/generic_app/lib/ConsoleProviders/StorageProvider.dart b/console/generic_app/lib/ConsoleProviders/StorageProvider.dart
new file mode 100644
index 000000000..40bb08e3f
--- /dev/null
+++ b/console/generic_app/lib/ConsoleProviders/StorageProvider.dart
@@ -0,0 +1,59 @@
+import 'dart:core';
+
+import 'package:shared_preferences/shared_preferences.dart';
+
+class StorageProvider {
+ final String _version = "1.0.0";
+ final SharedPreferences _sharedPreferences;
+
+ StorageProvider._internal(this._sharedPreferences);
+
+ static Future<StorageProvider> getInstance() async {
+ return StorageProvider._internal(await SharedPreferences.getInstance());
+ }
+
+ initialize() {
+ return {
+ "action": "PROVIDER_INIT",
+ "provider": "storage",
+ "version": _version,
+ "requiresPermission": false,
+ "hasPermission": true,
+ "success": true,
+ "enabled": true
+ };
+ }
+
+ enable() {
+ return {
+ "action": "PROVIDER_ENABLE",
+ "provider": "storage",
+ "hasPermission": true,
+ "success": true
+ };
+ }
+
+ disable() {
+ return {
+ "action": "PROVIDER_DISABLE",
+ "provider": "storage",
+ };
+ }
+
+ store(String key, String data) {
+ if (data == null) {
+ _sharedPreferences.remove(key);
+ } else {
+ _sharedPreferences.setString(key, data);
+ }
+ }
+
+ retrieve(String key) {
+ return {
+ "action": "RETRIEVE",
+ "provider": "storage",
+ "key": key,
+ "value": _sharedPreferences.getString(key)
+ };
+ }
+}
diff --git a/console/generic_app/lib/config/CurrentConsoleAppConfig.dart b/console/generic_app/lib/config/CurrentConsoleAppConfig.dart
index 189bc89a9..ac96fd338 100644
--- a/console/generic_app/lib/config/CurrentConsoleAppConfig.dart
+++ b/console/generic_app/lib/config/CurrentConsoleAppConfig.dart
@@ -10,7 +10,7 @@ class CurrentConsoleAppConfig {
CurrentConsoleAppConfig._privateConstructor();
- updateConfig(ConsoleAppConfig appConfig) {
+ updateConfig(ConsoleAppConfig appConfig, String project) {
this._realm = appConfig.realm;
this._url = appConfig.url;
this._menuEnabled = appConfig.menuEnabled;
@@ -18,6 +18,8 @@ class CurrentConsoleAppConfig {
this._primaryColor = appConfig.primaryColor;
this._secondaryColor = appConfig.secondaryColor;
this._links = appConfig.links;
+ this._project;
+ this._realm;
}
String _realm;
@@ -36,6 +38,9 @@ class CurrentConsoleAppConfig {
List<LinkConfig> _links;
+ String _project;
+
+
String get realm {
return _realm;
}
@@ -67,4 +72,8 @@ class CurrentConsoleAppConfig {
List<LinkConfig> get links {
return _links;
}
+
+ String get baseUrl {
+ return "https://$_project.openremote.io/api/$_realm";
+ }
}
diff --git a/console/generic_app/lib/network/ApiManager.dart b/console/generic_app/lib/network/ApiManager.dart
index 882e63fb3..313774152 100644
--- a/console/generic_app/lib/network/ApiManager.dart
+++ b/console/generic_app/lib/network/ApiManager.dart
@@ -44,9 +44,7 @@ class ApiManager {
headers.addAll(additionalHeaders);
}
- T returnValue;
-
- await http.get(urlBuffer.toString(), headers: headers).then((response) {
+ return http.get(urlBuffer.toString(), headers: headers).then((response) {
if (response.statusCode == 200) {
try {
Map<String, dynamic> json = jsonDecode(response.body);
@@ -57,7 +55,7 @@ class ApiManager {
if (jsonData is List) {
throw new Exception("Expected json object");
} else {
- returnValue = responseParser(jsonData) as T;
+ return responseParser(jsonData) as T;
}
} catch (e) {
print(e);
@@ -68,8 +66,6 @@ class ApiManager {
"Response error: ${response.statusCode} - ${response.body}");
}
});
-
- return returnValue;
}
Future<List<T>> getAll<T>(
@@ -98,9 +94,7 @@ class ApiManager {
headers.addAll(additionalHeaders);
}
- List<T> returnValue;
-
- await http.get(urlBuffer.toString(), headers: headers).then((response) {
+ return http.get(urlBuffer.toString(), headers: headers).then((response) {
if (response.statusCode == 200) {
try {
var json = jsonDecode(response.body);
@@ -109,8 +103,7 @@ class ApiManager {
jsonData = json[responseBodyDataKey];
}
if (jsonData is List) {
- returnValue =
- List<T>.from(jsonData.map((item) => responseParser(item)));
+ return List<T>.from(jsonData.map((item) => responseParser(item)));
} else {
throw new Exception("Expected array in body");
}
@@ -123,8 +116,6 @@ class ApiManager {
"Response error: ${response.statusCode} - ${response.body}");
}
});
-
- return returnValue;
}
Future<T> post<T extends BaseModel>({ResponseParser responseParser,
@@ -140,9 +131,7 @@ class ApiManager {
headers.addAll(additionalHeaders);
}
- T returnValue;
-
- await http
+ return http
.post(overrideUrl ?? urlBuffer.toString(),
headers: headers, body: model?.toJson() ?? rawModel)
.then((response) {
@@ -156,20 +145,18 @@ class ApiManager {
if (jsonData is List) {
throw new Exception("Expected json object");
} else {
- returnValue = responseParser(jsonData) as T;
+ return responseParser(jsonData) as T;
}
} catch (e) {
print(e);
rethrow;
}
} else if (response.statusCode >= 200 && response.statusCode <= 299) {
- returnValue = null;
+ return null;
} else {
throw new Exception(
"Response error: ${response.statusCode} - ${response.body}");
}
});
-
- return returnValue;
}
}
diff --git a/console/generic_app/lib/ui/ProjectPage.dart b/console/generic_app/lib/ui/ProjectPage.dart
index 3f98d395d..8441edf10 100644
--- a/console/generic_app/lib/ui/ProjectPage.dart
+++ b/console/generic_app/lib/ui/ProjectPage.dart
@@ -15,6 +15,7 @@ class _ProjectPageState extends State<ProjectPage> {
bool _isLoading;
String _projectName;
String _realmName;
+ BuildContext _innerContext;
@override
void initState() {
@@ -24,99 +25,119 @@ class _ProjectPageState extends State<ProjectPage> {
@override
Widget build(BuildContext context) {
- return Scaffold(
- body: SafeArea(
- child: SingleChildScrollView(
- physics: ClampingScrollPhysics(),
- child: Align(
- alignment: Alignment.center,
- child: Column(children: <Widget>[
- Container(
- padding: EdgeInsets.only(top: 25),
- height: MediaQuery.of(context).size.height / 2,
- child: Column(children: <Widget>[
- Expanded(
- child: Image.asset(
- 'assets/images/logo-mobile.png',
- fit: BoxFit.cover)),
- Expanded(
- child: Image.asset('assets/images/logo.png',
- fit: BoxFit.cover))
- ])),
- Container(
- child: Column(
- children: <Widget>[
- Container(
- child: TextField(
- cursorColor: CurrentConsoleAppConfig.instance.primaryColor,
- decoration:
- InputDecoration(labelText: 'Project',
- labelStyle: TextStyle(
- color: CurrentConsoleAppConfig.instance.primaryColor
- ),
- focusedBorder: UnderlineInputBorder(
- borderSide: BorderSide(color: CurrentConsoleAppConfig.instance.primaryColor),
- ),
- ),
- textInputAction: TextInputAction.next,
- onChanged: (inputText) {
- _projectName = inputText;
- },
- onSubmitted: (inputText) {
- FocusScope.of(context).nextFocus();
- }),
- padding: EdgeInsets.all(25),
- ),
- Container(
- child: TextField(
- cursorColor: CurrentConsoleAppConfig.instance.primaryColor,
- decoration:
- InputDecoration(labelText: 'Realm',
- labelStyle: TextStyle(
- color: CurrentConsoleAppConfig.instance.primaryColor
- ),
- focusedBorder: UnderlineInputBorder(
- borderSide: BorderSide(color: CurrentConsoleAppConfig.instance.primaryColor),
- )
- ),
- textInputAction: TextInputAction.done,
- onChanged: (inputText) {
- _realmName = inputText;
- },
- onSubmitted: (inputText) {
+ return Scaffold(body: Builder(builder: (BuildContext innerContext) {
+ _innerContext = innerContext;
+ return SafeArea(
+ child: SingleChildScrollView(
+ physics: ClampingScrollPhysics(),
+ child: Align(
+ alignment: Alignment.center,
+ child: Column(children: <Widget>[
+ Container(
+ padding: EdgeInsets.only(top: 25, left: 20, right: 20),
+ height: MediaQuery.of(context).size.height / 2,
+ child: Column(children: <Widget>[
+ Expanded(
+ child: Image.asset(
+ 'assets/images/logo-mobile.png',
+ fit: BoxFit.contain)),
+ Expanded(
+ child: Image.asset('assets/images/logo.png',
+ fit: BoxFit.contain))
+ ])),
+ Container(
+ child: Column(
+ children: <Widget>[
+ Container(
+ child: TextField(
+ cursorColor: CurrentConsoleAppConfig
+ .instance.primaryColor,
+ decoration: InputDecoration(
+ labelText: 'Project',
+ labelStyle: TextStyle(
+ color: CurrentConsoleAppConfig
+ .instance.primaryColor),
+ focusedBorder: UnderlineInputBorder(
+ borderSide: BorderSide(
+ color: CurrentConsoleAppConfig
+ .instance.primaryColor),
+ ),
+ ),
+ textInputAction: TextInputAction.next,
+ onChanged: (inputText) {
+ _projectName = inputText;
+ },
+ onSubmitted: (inputText) {
+ FocusScope.of(context).nextFocus();
+ }),
+ padding: EdgeInsets.all(25),
+ ),
+ Container(
+ child: TextField(
+ cursorColor: CurrentConsoleAppConfig
+ .instance.primaryColor,
+ decoration: InputDecoration(
+ labelText: 'Realm',
+ labelStyle: TextStyle(
+ color: CurrentConsoleAppConfig
+ .instance.primaryColor),
+ focusedBorder: UnderlineInputBorder(
+ borderSide: BorderSide(
+ color: CurrentConsoleAppConfig
+ .instance.primaryColor),
+ )),
+ textInputAction: TextInputAction.done,
+ onChanged: (inputText) {
+ _realmName = inputText;
+ },
+ onSubmitted: (inputText) {
+ _getConsoleAppConfig();
+ FocusScope.of(context).unfocus();
+ }),
+ padding: EdgeInsets.all(25),
+ ),
+ Container(
+ child: Align(
+ alignment: Alignment.centerRight,
+ child: RaisedButton(
+ color: CurrentConsoleAppConfig
+ .instance.primaryColor,
+ focusColor: CurrentConsoleAppConfig
+ .instance.secondaryColor,
+ textColor: Colors.white,
+ onPressed: () {
_getConsoleAppConfig();
- FocusScope.of(context).unfocus();
- }),
- padding: EdgeInsets.all(25),
+ },
+ child: Text("Press")),
),
- Container(
- child: Align(
- alignment: Alignment.centerRight,
- child: RaisedButton(
- color: CurrentConsoleAppConfig.instance.primaryColor,
- focusColor: CurrentConsoleAppConfig.instance.secondaryColor,
- textColor: Colors.white,
- onPressed: () {
- _getConsoleAppConfig();
- },
- child: Text("Press")),
- ),
- padding: EdgeInsets.all(25),
- )
- ],
- ),
- )
- ])))));
+ padding: EdgeInsets.all(25),
+ )
+ ],
+ ),
+ )
+ ])
+ )
+ )
+ );
+ })
+ );
}
void _getConsoleAppConfig() {
- var apiManager = new ApiManager("http://10.0.2.2:8080/api/${_realmName}");
+ var apiManager =
+ new ApiManager("http://192.168.2.10:8080/api/${_realmName}");
// new ApiManager("https://${_projectName}.openremote.io/${_realmName}");
- apiManager.get(["app", "config"], ConsoleAppConfig.fromJson).then(
- (value) {
- print(value);
- CurrentConsoleAppConfig.instance.updateConfig(value);
- Navigator.push(context, MaterialPageRoute(builder: (context)=>WebViewPage(initialUrl: CurrentConsoleAppConfig.instance.url,)));
- });
+ apiManager.get(["app", "config"], ConsoleAppConfig.fromJson).then((value) {
+ print(value);
+ CurrentConsoleAppConfig.instance.updateConfig(value, _projectName);
+ Navigator.push(
+ context,
+ MaterialPageRoute(
+ builder: (context) => WebViewPage(
+ initialUrl: CurrentConsoleAppConfig.instance.url,
+ )));
+ }).catchError((onError) => Scaffold.of(_innerContext).showSnackBar(
+ SnackBar(content: Text("error")),
+ ));
}
}
diff --git a/console/generic_app/lib/ui/WebViewPage.dart b/console/generic_app/lib/ui/WebViewPage.dart
index 07d52dd6a..9ac341848 100644
--- a/console/generic_app/lib/ui/WebViewPage.dart
+++ b/console/generic_app/lib/ui/WebViewPage.dart
@@ -1,7 +1,10 @@
import 'dart:async';
+import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:generic_app/ConsoleProviders/GeofenceProvider.dart';
+import 'package:generic_app/ConsoleProviders/PushProvider.dart';
+import 'package:generic_app/ConsoleProviders/StorageProvider.dart';
import 'package:generic_app/config/CurrentConsoleAppConfig.dart';
import 'package:generic_app/models/LinkConfig.dart';
import 'package:webview_flutter/webview_flutter.dart';
@@ -17,71 +20,161 @@ class WebViewPage extends StatefulWidget {
}
class _WebViewPageState extends State<WebViewPage> {
- final Completer<WebViewController> _controller =
- Completer<WebViewController>();
-
+ WebViewController _controller;
GeofenceProvider _geofenceProvider;
-
- @override
- void initState() {
- GeofenceProvider.getInstance().then((value) => _geofenceProvider = value);
- super.initState();
- }
+ PushProvider _pushProvider;
+ StorageProvider _storageProvider;
+ WebView _webView;
@override
Widget build(BuildContext context) {
- var stack = Stack(children: <Widget>[
- WebView(
- onPageStarted: (url) {
- print("started: $url");
- },
- initialUrl: Uri.encodeFull(widget.initialUrl),
- javascriptMode: JavascriptMode.unrestricted,
- onWebViewCreated: (WebViewController webViewController) {
- _controller.complete(webViewController);
- },
- javascriptChannels: <JavascriptChannel>[
- _toasterJavascriptChannel(context),
- ].toSet(),
- navigationDelegate: (navigationRequest) {
- return NavigationDecision.navigate;
- },
- )
- ]);
+ _webView = WebView(
+ onPageStarted: (url) {
+ print("started: $url");
+ },
+ initialUrl: Uri.encodeFull(widget.initialUrl),
+ javascriptMode: JavascriptMode.unrestricted,
+ onWebViewCreated: (WebViewController webViewController) {
+ _controller = webViewController;
+ },
+ javascriptChannels: <JavascriptChannel>[
+ _postMessageJavascriptChannel(context),
+ ].toSet(),
+ navigationDelegate: (navigationRequest) {
+ return NavigationDecision.navigate;
+ },
+ );
+
+ var stack = Stack(children: <Widget>[_webView]);
if (CurrentConsoleAppConfig.instance.menuEnabled) {
switch (CurrentConsoleAppConfig.instance.menuPosition) {
case "BOTTOM_RIGHT":
- stack.children.add(Positioned(bottom: 25, right: 25, child: _menuPopup()));
+ stack.children
+ .add(Positioned(bottom: 25, right: 25, child: _menuPopup(-50, -100)));
break;
case "TOP_LEFT":
- stack.children.add(Positioned(top: 25, left: 25, child: _menuPopup()));
+ stack.children
+ .add(Positioned(top: 25, left: 25, child: _menuPopup(0, 100)));
break;
case "TOP_RIGHT":
- stack.children.add(Positioned(top: 25, right: 25, child: _menuPopup()));
+ stack.children
+ .add(Positioned(top: 25, right: 25, child: _menuPopup(-50, 100)));
break;
case "BOTTOM_LEFT":
default:
- stack.children.add(Positioned(bottom: 25, left: 25, child: _menuPopup()));
+ stack.children
+ .add(Positioned(bottom: 25, left: 25, child: _menuPopup(0, -100)));
break;
}
}
- return Scaffold(body: SafeArea(child: stack));
+ return WillPopScope( onWillPop: _onBackPressed, child: Scaffold(body: SafeArea(child: stack)));
}
- JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
+ _notifyClient(Map<String, dynamic> data) {
+ final String jsonString = json.encode(data);
+ _controller.evaluateJavascript(
+ "OpenRemoteConsole._handleProviderResponse($jsonString)");
+ }
+
+ JavascriptChannel _postMessageJavascriptChannel(BuildContext context) {
return JavascriptChannel(
- name: 'Toaster',
+ name: 'postMessage',
onMessageReceived: (JavascriptMessage message) {
- Scaffold.of(context).showSnackBar(
- SnackBar(content: Text(message.message)),
- );
+ Map<String, dynamic> messageContent = json.decode(message.message);
+ String messageType = messageContent["type"];
+ Map<String, dynamic> data = messageContent["data"];
+ switch (messageType) {
+ case "error":
+ print("Received WebApp message, error: " + data["error"]);
+ Scaffold.of(context).showSnackBar(
+ SnackBar(content: Text(data["error"])),
+ );
+ break;
+ case "provider":
+ String action = data["action"];
+ if (action != null) {
+ String provider = data["provider"];
+ if (provider == "geofence") {
+ _handleGeofenceProviderMessage(data);
+ } else if (provider == "push") {
+ _handlePushProviderMessage(data);
+ } else if (provider == "storage") {
+ _handleStorageProviderMessage(data);
+ }
+ }
+ break;
+ default:
+ }
});
}
- Widget _menuPopup() =>
- PopupMenuButton<int>(
+ _handleGeofenceProviderMessage(Map<String, dynamic> data) async {
+ String action = data["action"];
+
+ if (_geofenceProvider == null) {
+ _geofenceProvider = await GeofenceProvider.getInstance();
+ }
+
+ if (action == "PROVIDER_INIT") {
+ _notifyClient(await _geofenceProvider.initialize());
+ } else if (action == "PROVIDER_ENABLE") {
+ String consoleId = data["consoleId"];
+
+ if (consoleId != null) {
+ await _geofenceProvider.enable(
+ CurrentConsoleAppConfig.instance.baseUrl, consoleId, (enableData) {
+ _notifyClient(enableData);
+ });
+ }
+ } else if (action == "PROVIDER_DISABLE") {
+ _notifyClient(await _geofenceProvider.disable());
+ } else if (action == "GEOFENCE_REFRESH") {
+ _geofenceProvider.refreshGeofences();
+ } else if (action == "GET_LOCATION") {
+ await _geofenceProvider.getLocation(
+ (locationData) => _notifyClient(locationData), context);
+ }
+ }
+
+ _handlePushProviderMessage(Map<String, dynamic> data) async {
+ String action = data["action"];
+
+ if (_pushProvider == null) {
+ _pushProvider = await PushProvider.getInstance();
+ }
+ if (action == "PROVIDER_INIT") {
+ _notifyClient(await _pushProvider.initialize());
+ } else if (action == "PROVIDER_ENABLE") {
+ String consoleId = data["consoleId"];
+
+ if (consoleId != null) {
+ await _pushProvider.enable(
+ consoleId, (enableData) => _notifyClient(enableData));
+ }
+ } else if (action == "PROVIDER_DISABLE") {
+ _notifyClient(await _pushProvider.disable());
+ }
+ }
+
+ _handleStorageProviderMessage(Map<String, dynamic> data) {
+ String action = data["action"];
+ if (action == "PROVIDER_INIT") {
+ _notifyClient(_storageProvider.initialize());
+ } else if (action == "PROVIDER_ENABLE") {
+ _notifyClient(_storageProvider.enable());
+ } else if (action == "STORE") {
+ String key = data["key"];
+ String valueJson = data["value"];
+ _storageProvider.store(key, valueJson);
+ } else if (action == "RETRIEVE") {
+ String key = data["key"];
+ _notifyClient(_storageProvider.retrieve(key));
+ }
+ }
+
+ Widget _menuPopup(double offsetX, double offsetY) => PopupMenuButton<int>(
itemBuilder: (context) {
List<PopupMenuItem<int>> items = new List<PopupMenuItem<int>>();
@@ -89,7 +182,7 @@ class _WebViewPageState extends State<WebViewPage> {
int index = 0;
for (LinkConfig linkConfig
- in CurrentConsoleAppConfig.instance.links) {
+ in CurrentConsoleAppConfig.instance.links) {
items.add(PopupMenuItem(
value: index++,
child: Text(
@@ -109,12 +202,21 @@ class _WebViewPageState extends State<WebViewPage> {
),
child: Icon(Icons.menu),
),
- offset: Offset(0, -100),
+ offset: Offset(offsetX, offsetY),
elevation: 2,
onSelected: (selectedValue) {
LinkConfig linkConfig =
- CurrentConsoleAppConfig.instance.links[selectedValue];
- print(linkConfig);
+ CurrentConsoleAppConfig.instance.links[selectedValue];
+ _controller.loadUrl(linkConfig.pageLink);
},
);
+
+ Future<bool> _onBackPressed() async {
+ if (await _controller.canGoBack()) {
+ _controller.goBack();
+ return Future.value(false);
+ } else {
+ return Future.value(true);
+ }
+ }
}
diff --git a/console/generic_app/pubspec.lock b/console/generic_app/pubspec.lock
index 5714e8bf3..902a2887b 100644
--- a/console/generic_app/pubspec.lock
+++ b/console/generic_app/pubspec.lock
@@ -162,6 +162,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.6"
+ firebase_messaging:
+ dependency: "direct main"
+ description:
+ name: firebase_messaging
+ url: "https://pub.dartlang.org"
+ source: hosted
+ version: "5.1.8"
fixnum:
dependency: transitive
description:
@@ -352,6 +359,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.4.0"
+ platform:
+ dependency: transitive
+ description:
+ name: platform
+ url: "https://pub.dartlang.org"
+ source: hosted
+ version: "2.2.1"
plugin_platform_interface:
dependency: transitive
description:
diff --git a/console/generic_app/pubspec.yaml b/console/generic_app/pubspec.yaml
index 7fad261d7..a4054f202 100644
--- a/console/generic_app/pubspec.yaml
+++ b/console/generic_app/pubspec.yaml
@@ -31,6 +31,7 @@ dependencies:
webview_flutter: ^0.3.22+1
shared_preferences: ^0.5.7+3
permission_handler: ^5.0.1+1
+ firebase_messaging: ^5.1.4
dev_dependencies:
flutter_test:
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
index b9270ee9d..d359ba9f5 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
@@ -759,7 +759,12 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
null,
"#FAFAFA",
"#AFAFAF",
- Values.createObject().put("Map", "https://maps.google.com")
+ Values.createArray().add(
+ Values.createObject()
+ .put("displayText","Map")
+ .put("pageLink","https://maps.google.com")
+ .put("queryParams", Values.createObject().put("test", "hello"))
+ )
));
});
}
diff --git a/model/src/main/java/org/openremote/model/apps/ConsoleAppConfig.java b/model/src/main/java/org/openremote/model/apps/ConsoleAppConfig.java
index fd2e0d6e2..bbe419184 100644
--- a/model/src/main/java/org/openremote/model/apps/ConsoleAppConfig.java
+++ b/model/src/main/java/org/openremote/model/apps/ConsoleAppConfig.java
@@ -1,11 +1,11 @@
package org.openremote.model.apps;
+import org.openremote.model.value.ArrayValue;
import org.openremote.model.value.ObjectValue;
import javax.persistence.*;
-import static org.openremote.model.Constants.PERSISTENCE_JSON_OBJECT_TYPE;
-import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
+import static org.openremote.model.Constants.*;
@Entity
@Table(name = "CONSOLE_APP_CONFIG")
@@ -21,7 +21,7 @@ public class ConsoleAppConfig {
public ConsoleAppConfig() {
}
- public ConsoleAppConfig(String realm, String url, Boolean menuEnabled, MenuPosition menuPosition, String menuImage, String primaryColor, String secondaryColor, ObjectValue links) {
+ public ConsoleAppConfig(String realm, String url, Boolean menuEnabled, MenuPosition menuPosition, String menuImage, String primaryColor, String secondaryColor, ArrayValue links) {
this.realm = realm;
this.url = url;
this.menuEnabled = menuEnabled;
@@ -60,6 +60,6 @@ public class ConsoleAppConfig {
protected String secondaryColor;
@Column(name = "LINKS", columnDefinition = "jsonb")
- @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_OBJECT_TYPE)
- protected ObjectValue links;
+ @org.hibernate.annotations.Type(type = PERSISTENCE_JSON_ARRAY_TYPE)
+ protected ArrayValue links;
}
diff --git a/settings.gradle b/settings.gradle
index 919df298b..e2ce0ed65 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1,7 +1,7 @@
rootProject.name = "openremote"
// Include sub-projects dynamically, every directory with a build.gradle (and no .buildignore)
-fileTree(dir: rootDir, include: "**/build.gradle", excludes: ["**/node_modules/**"])
+fileTree(dir: rootDir, include: "**/build.gradle", excludes: ["**/node_modules/**", "**/generic_app/**"])
.filter { it.parent != rootDir }
.filter { !file("${it.parent}/.buildignore").exists() }
.each {