// // BaseDeviceViewController.swift // pocloud // // Created by Patrick McDonagh on 6/11/18. // Copyright © 2018 patrickjmcd. All rights reserved. // import UIKit import RealmSwift import FirebaseDatabase import SVProgressHUD import PromiseKit class BaseDeviceViewController: UIViewController { let realm = try! Realm() var ref: DatabaseReference! let baseURL = (UIApplication.shared.delegate as! AppDelegate).baseURL let user = (UIApplication.shared.delegate as! AppDelegate).user var thisDevice : Device? var deviceTypes : Results? var selectedChannel : Channel? var channelLookup : [String : Int] = [:] var values : [String : MeshifyValue] = [:] var updatedChannelNames : [String] = [String]() var changedChannelNames : [String] = [String]() let numFormatter = NumberFormatter() override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference() numFormatter.minimumFractionDigits = 0 numFormatter.maximumFractionDigits = 3 numFormatter.minimumIntegerDigits = 1 initializeData() } func initializeData() { let macAddress = String((thisDevice?.macAddress.replacingOccurrences(of: ":", with: "").uppercased().dropLast(4))!) let deviceTypeName = (thisDevice?.parentDeviceType.first?.name)! SVProgressHUD.show() firstly { loadData() }.then { _ in getChannels(deviceTypeId: self.thisDevice!.deviceTypeId, baseURL: self.baseURL, authToken: (self.user?.authToken)!) }.then { _ in getChannelValues(deviceId: self.thisDevice!.id, baseURL: self.baseURL, authToken: (self.user?.authToken)!) }.done { (valueDict) in self.values = valueDict self.updateGauges() self.updateChartData() SVProgressHUD.dismiss() if let dev = self.thisDevice { for chanIndex in 0.. String { if let doubledValue = Double(value) { if let formattedString = numFormatter.string(from: NSNumber(value: doubledValue)) { return formattedString } else { return value } } else { return value } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToChannelView" { let destinationVC = segue.destination as! ChannelDetailViewController destinationVC.thisDevice = thisDevice! destinationVC.thisChannel = selectedChannel! } } func loadData() -> Promise { return Promise { promise in deviceTypes = realm.objects(DeviceType.self) thisDevice = realm.objects(Device.self).filter("id == %d", thisDevice!.id).first! promise.fulfill(()) } } }