100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
added missing files
Michael Rademakercae0c7aad5a3
diff --git a/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj b/console/iOS/ORLib/ORLib.xcodeproj/project.pbxprojindex d2329182b..36bf8c7c6 100644--- a/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj+++ b/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj@@ -138,12 +138,10 @@isa = PBXNativeTarget;buildConfigurationList = 4C82D7421FC58ED2009DE853 /* Build configuration list for PBXNativeTarget "ORLib" */;buildPhases = (- 96B4118FFE24AACE46B60F45 /* [CP] Check Pods Manifest.lock */,4C82D7351FC58ED2009DE853 /* Sources */,4C82D7361FC58ED2009DE853 /* Frameworks */,4C82D7371FC58ED2009DE853 /* Headers */,4C82D7381FC58ED2009DE853 /* Resources */,- C4FE859AEC10E3D92C80C6BB /* [CP] Copy Pods Resources */,);buildRules = ();@@ -197,42 +195,6 @@};/* End PBXResourcesBuildPhase section */-/* Begin PBXShellScriptBuildPhase section */- 96B4118FFE24AACE46B60F45 /* [CP] Check Pods Manifest.lock */ = {- isa = PBXShellScriptBuildPhase;- buildActionMask = 2147483647;- files = (- );- inputPaths = (- "${PODS_PODFILE_DIR_PATH}/Podfile.lock",- "${PODS_ROOT}/Manifest.lock",- );- name = "[CP] Check Pods Manifest.lock";- outputPaths = (- "$(DERIVED_FILE_DIR)/Pods-ORLib-checkManifestLockResult.txt",- );- runOnlyForDeploymentPostprocessing = 0;- shellPath = /bin/sh;- shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";- showEnvVarsInLog = 0;- };- C4FE859AEC10E3D92C80C6BB /* [CP] Copy Pods Resources */ = {- isa = PBXShellScriptBuildPhase;- buildActionMask = 2147483647;- files = (- );- inputPaths = (- );- name = "[CP] Copy Pods Resources";- outputPaths = (- );- runOnlyForDeploymentPostprocessing = 0;- shellPath = /bin/sh;- shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ORLib/Pods-ORLib-resources.sh\"\n";- showEnvVarsInLog = 0;- };-/* End PBXShellScriptBuildPhase section */-/* Begin PBXSourcesBuildPhase section */4C82D7351FC58ED2009DE853 /* Sources */ = {isa = PBXSourcesBuildPhase;diff --git a/console/iOS/ORLib/ORLib/GeofenceProvider.swift b/console/iOS/ORLib/ORLib/GeofenceProvider.swiftnew file mode 100644index 000000000..7940d6d4d--- /dev/null+++ b/console/iOS/ORLib/ORLib/GeofenceProvider.swift@@ -0,0 +1,229 @@+import UIKit+import CoreLocation++public class GeofenceProvider: NSObject, URLSessionDelegate {++ static let baseUrlKey = "baseUrl"+ static let consoleIdKey = "consoleId"+ static let geoPostUrlsKey = "geoPostUrls"++ let version = "ORConsole"+ let geofenceFetchEndpoint = "rules/geofences/"+ let locationManager = CLLocationManager()+ let userdefaults = UserDefaults.standard+ var geoPostUrls = [String:[String]]()+ var enableCallback : (([String: Any]) -> (Void))?++ public var baseURL: String = ""+ public var consoleId: String = ""++ public override init() {+ super.init()+ locationManager.delegate = self+ self.baseURL = userdefaults.string(forKey: GeofenceProvider.baseUrlKey) ?? ""+ self.consoleId = userdefaults.string(forKey: GeofenceProvider.consoleIdKey) ?? ""+ self.geoPostUrls = userdefaults.value(forKey: GeofenceProvider.geoPostUrlsKey) as? [String:[String]] ?? [String:[String]]()+ }++ public func initialize() -> [String: Any] {+ return [+ DefaultsKey.actionKey: Actions.providerInit,+ DefaultsKey.providerKey: Providers.geofence,+ DefaultsKey.versionKey: version,+ DefaultsKey.requiresPermissionKey: true,+ DefaultsKey.hasPermissionKey: checkPermission(),+ DefaultsKey.successKey: true+ ]+ }++ private func checkPermission() -> Bool {+ if CLLocationManager.locationServicesEnabled() {+ if CLLocationManager.authorizationStatus() == .authorizedAlways {+ return true+ }+ }+ return false+ }++ private func registerPermissions() {+ locationManager.requestAlwaysAuthorization()+ }++ public func addGeofence(geofence: GeofenceDefinition) {+ let region = CLCircularRegion(center: CLLocationCoordinate2DMake(geofence.lat, geofence.lng), radius: geofence.radius, identifier:geofence.id)+ locationManager.startMonitoring(for: region)+ geoPostUrls[geofence.id] = [geofence.httpMethod, geofence.url]+ userdefaults.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)+ userdefaults.synchronize()+ }++ public func removeGeofence(id: String) {+ for region in locationManager.monitoredRegions {+ guard let circularRegion = region as? CLCircularRegion, circularRegion.identifier == id else {continue}+ locationManager.stopMonitoring(for: circularRegion)+ geoPostUrls.removeValue(forKey: circularRegion.identifier)+ userdefaults.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)+ userdefaults.synchronize()+ break+ }+ }++ public func clearAllRegions() {+ for region in locationManager.monitoredRegions {+ locationManager.stopMonitoring(for: region)+ }+ geoPostUrls = [String:[String]]()+ userdefaults.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)+ userdefaults.synchronize()+ }++ public func enable(baseUrl: String, consoleId: String, callback:@escaping ([String: Any]) ->(Void)) {+ self.baseURL = baseUrl+ self.consoleId = consoleId+ userdefaults.set(self.baseURL, forKey: GeofenceProvider.baseUrlKey)+ userdefaults.set(self.consoleId, forKey: GeofenceProvider.consoleIdKey)+ userdefaults.synchronize()+ enableCallback = callback+ if checkPermission() {+ enableCallback?([+ DefaultsKey.actionKey: Actions.providerEnable,+ DefaultsKey.providerKey: Providers.geofence,+ DefaultsKey.hasPermissionKey: checkPermission(),+ DefaultsKey.successKey: true+ ])+ } else {+ if CLLocationManager.authorizationStatus() == .notDetermined {+ registerPermissions()+ } else {+ enableCallback?([+ DefaultsKey.actionKey: Actions.providerEnable,+ DefaultsKey.providerKey: Providers.geofence,+ DefaultsKey.hasPermissionKey: false,+ DefaultsKey.successKey: true+ ])+ }+ }+ }++ public func disbale()-> [String: Any] {+ return [+ DefaultsKey.actionKey: "PROVIDER_DISABLE",+ DefaultsKey.providerKey: Providers.geofence+ ]+ }++ public func refreshGeofences() {+ fetchGeofences()+ }++ func fetchGeofences(callback: (([GeofenceDefinition]) -> ())? = nil) {+ if let tkurlRequest = URL(string: "\(baseURL)/\(geofenceFetchEndpoint)\(consoleId)") {+ let tkRequest = NSMutableURLRequest(url: tkurlRequest)+ tkRequest.httpMethod = "GET"+ let sessionConfiguration = URLSessionConfiguration.default+ let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)+ let req = session.dataTask(with: tkRequest as URLRequest, completionHandler: { (data, response, error) in+ if (data != nil){+ guard let geofences = try? JSONDecoder().decode([GeofenceDefinition].self, from: data!) else {+ callback?([])+ return+ }+ self.clearAllRegions()+ print("Geofences count: \(geofences.count)")+ for geofence in geofences {+ self.addGeofence(geofence: geofence)+ }+ callback?(geofences)+ } else {+ NSLog("error %@", (error! as NSError).localizedDescription)+ let error = NSError(domain: "", code: 0, userInfo: [+ NSLocalizedDescriptionKey : NSLocalizedString("NoDataReceived", value: "Did not receive any data", comment: "")+ ])+ print(error)+ callback?([])+ }+ })+ req.resume()+ } else {+ callback?([])+ }+ }++ private func sendGeofenceRequest(url: URL, httpMethod: String, data:[String: Any]?) {+ let request = NSMutableURLRequest(url: url)+ request.addValue("application/json", forHTTPHeaderField:"Content-Type");+ request.httpMethod = httpMethod++ if (data != nil) {+ if let postBody = try? JSONSerialization.data(withJSONObject: data!, options: []) {+ request.httpBody = postBody+ }+ } else {+ request.httpBody = "null".data(using: .utf8)+ }++ let sessionConfiguration = URLSessionConfiguration.default+ let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)+ let req = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in+ if (data != nil){++ } else {+ NSLog("error %@", (error! as NSError).localizedDescription)+ let error = NSError(domain: "", code: 0, userInfo: [+ NSLocalizedDescriptionKey : NSLocalizedString("NoDataReceived", value: "Did not receive any data", comment: "")+ ])+ print(error)+ }+ })+ req.resume()+ }++ public class GeofenceDefinition: NSObject, Decodable {+ public var id: String = ""+ public var lat: Double = 0.0+ public var lng: Double = 0.0+ public var radius: Double = 0.0+ public var httpMethod: String = ""+ public var url: String = ""+ }+}++extension GeofenceProvider: CLLocationManagerDelegate {+ public func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {+ guard let circularRegion = region as? CLCircularRegion else {return}++ guard let urlData = geoPostUrls[circularRegion.identifier] else {+ return+ }+ guard let tkurlRequest = URL(string: "\(baseURL)\(urlData[1])") else { return }++ let postData = [+ "type": "Point",+ "coordinates": [manager.location?.coordinate.longitude, manager.location?.coordinate.latitude]+ ] as [String : Any]++ sendGeofenceRequest(url: tkurlRequest, httpMethod: urlData[0], data: postData)+ }++ public func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {+ guard let circularRegion = region as? CLCircularRegion else {return}++ guard let urlData = geoPostUrls[circularRegion.identifier] else {+ return+ }+ guard let tkurlRequest = URL(string: "\(baseURL)\(urlData[1])") else { return }++ sendGeofenceRequest(url: tkurlRequest, httpMethod: urlData[0], data: nil)+ }++ public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {+ if status != .notDetermined {+ enableCallback?([+ DefaultsKey.actionKey: Actions.providerEnable,+ DefaultsKey.providerKey: Providers.geofence,+ DefaultsKey.hasPermissionKey: checkPermission(),+ DefaultsKey.successKey: true+ ])+ }+ }+}diff --git a/console/iOS/ORLib/ORLib/ORAssetResoure.swift b/console/iOS/ORLib/ORLib/ORAssetResoure.swiftnew file mode 100644index 000000000..150e0ce65--- /dev/null+++ b/console/iOS/ORLib/ORLib/ORAssetResoure.swift@@ -0,0 +1,60 @@+//+// ORAssetResoure.swift+// GoogleToolboxForMac+//+// Created by Michael Rademaker on 04/06/2018.+//++import UIKit++open class ORAssetResoure: NSObject, URLSessionDelegate {++ public static let sharedInstance = ORAssetResoure()++ private override init() {+ super.init()+ }++ open func updateAssetAttribute(assetId : String, attributeName : String, rawJson : Data) {+ UIApplication.shared.isNetworkActivityIndicatorVisible = true+ TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in+ switch accessTokenResult {+ case .Failure(let error) :+ UIApplication.shared.isNetworkActivityIndicatorVisible = false+ ErrorManager.showError(error: error!)+ case .Success(let accessToken) :+ self.updateAssetAttribute(assetId: assetId, attributeName: attributeName, accessToken: accessToken, rawJson: rawJson)+ }+ }+ }++ open func updatePublicAssetAttibute(assetId : String, attributeName : String, rawJson : Data) {+ updateAssetAttribute(assetId: assetId, attributeName: attributeName, accessToken: nil, rawJson: rawJson)+ }++ private func updateAssetAttribute(assetId : String, attributeName : String, accessToken :String?, rawJson : Data) {+ guard let urlRequest = URL(string: String(String(format: "\(ORServer.scheme)://%@/%@/asset/%@/attribute/%@", ORServer.hostURL, ORServer.realm, assetId, attributeName))) else { return }+ let request = NSMutableURLRequest(url: urlRequest)+ request.httpMethod = "PUT"+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = rawJson+ if let token = accessToken {+ request.addValue(String(format:"Bearer %@", token), forHTTPHeaderField: "Authorization")+ }+ let sessionConfiguration = URLSessionConfiguration.default+ let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue : nil)+ let reqDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in+ DispatchQueue.main.async {+ UIApplication.shared.isNetworkActivityIndicatorVisible = false+ if (error != nil) {+ NSLog("error %@", (error! as NSError).localizedDescription)+ let error = NSError(domain: "", code: 0, userInfo: [+ NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")+ ])+ ErrorManager.showError(error: error)+ }+ }+ })+ reqDataTask.resume()+ }+}diff --git a/console/iOS/ORLib/ORLib/PushNotificationProvider.swift b/console/iOS/ORLib/ORLib/PushNotificationProvider.swiftnew file mode 100644index 000000000..024cca879--- /dev/null+++ b/console/iOS/ORLib/ORLib/PushNotificationProvider.swift@@ -0,0 +1,103 @@+//+// PushNotificationProvider.swift+// Eindhoven+//+// Created by Michael Rademaker on 25/05/2018.+// Copyright © 2018 OpenRemote Inc. All rights reserved.+//++import UIKit+import UserNotifications++class PushNotificationProvider: NSObject {++ let version = "fcm"++ public override init() {+ super.init()+ }++ public func initialize(callback:@escaping ([String: Any]) ->(Void)) {+ UNUserNotificationCenter.current().getNotificationSettings { (settings) in+ switch settings.authorizationStatus {++ case .authorized:+ callback( [+ DefaultsKey.actionKey: Actions.providerInit,+ DefaultsKey.providerKey: Providers.push,+ DefaultsKey.versionKey: self.version,+ DefaultsKey.hasPermissionKey: true,+ DefaultsKey.requiresPermissionKey: true,+ DefaultsKey.successKey: true+ ])++ case .denied:+ callback( [+ DefaultsKey.actionKey: Actions.providerInit,+ DefaultsKey.providerKey: Providers.push,+ DefaultsKey.versionKey: self.version,+ DefaultsKey.hasPermissionKey: false,+ DefaultsKey.requiresPermissionKey: true,+ DefaultsKey.successKey: true+ ])++ case .notDetermined:+ callback( [+ DefaultsKey.actionKey: Actions.providerInit,+ DefaultsKey.providerKey: Providers.push,+ DefaultsKey.versionKey: self.version,+ DefaultsKey.hasPermissionKey: false,+ DefaultsKey.requiresPermissionKey: true,+ DefaultsKey.successKey: true+ ])+ }+ }+ }++ public func enable(callback:@escaping ([String: Any]) ->(Void)) {+ UNUserNotificationCenter.current().getNotificationSettings { (settings) in++ switch settings.authorizationStatus {+ case .authorized:+ callback([+ DefaultsKey.actionKey: Actions.providerEnable,+ DefaultsKey.providerKey: Providers.push,+ DefaultsKey.hasPermissionKey: true,+ DefaultsKey.successKey: true,+ DefaultsKey.dataKey: [DefaultsKey.token: TokenManager.sharedInstance.deviceId]+ ])++ case .denied:+ callback([+ DefaultsKey.actionKey: Actions.providerEnable,+ DefaultsKey.providerKey: Providers.push,+ DefaultsKey.hasPermissionKey: false,+ DefaultsKey.successKey: true,+ DefaultsKey.dataKey: [DefaultsKey.token: TokenManager.sharedInstance.deviceId]+ ])++ case .notDetermined:+ let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]+ UNUserNotificationCenter.current().requestAuthorization(+ options: authOptions,+ completionHandler: {granted, _ in+ callback([+ DefaultsKey.actionKey: Actions.providerEnable,+ DefaultsKey.providerKey: Providers.push,+ DefaultsKey.hasPermissionKey: granted,+ DefaultsKey.successKey: true,+ DefaultsKey.dataKey: [DefaultsKey.token: TokenManager.sharedInstance.deviceId]+ ])+ })++ }+ }+ }++ public func disbale()-> [String: Any] {+ return [+ DefaultsKey.actionKey: Actions.providerDisable,+ DefaultsKey.providerKey: Providers.push+ ]+ }+}