204 lines
6.9 KiB
Swift
204 lines
6.9 KiB
Swift
//
|
|
// ChannelDetailViewController.swift
|
|
// pocloud
|
|
//
|
|
// Created by Patrick McDonagh on 5/25/18.
|
|
// Copyright © 2018 patrickjmcd. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
import RealmSwift
|
|
import SwiftyJSON
|
|
import PromiseKit
|
|
import Alamofire
|
|
import SVProgressHUD
|
|
|
|
class ChannelDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
|
|
let realm = try! Realm()
|
|
let baseURL = (UIApplication.shared.delegate as! AppDelegate).baseURL
|
|
let formatter = DateFormatter()
|
|
|
|
|
|
|
|
|
|
var user : User?
|
|
var thisDevice : Device?
|
|
var thisChannel : Channel?
|
|
|
|
var channelHistory : [ChannelHistoryValue] = [ChannelHistoryValue]()
|
|
|
|
let channelDataTypes: [Int : String] = [
|
|
0: "Unknown",
|
|
1: "Float",
|
|
2: "String",
|
|
3: "Integer",
|
|
4: "Boolean",
|
|
5: "DateTime",
|
|
6: "Timespan",
|
|
7 :"File",
|
|
8: "LatLng"
|
|
]
|
|
|
|
@IBOutlet weak var deviceNameLabel: UILabel!
|
|
@IBOutlet weak var nameLabel: UILabel!
|
|
@IBOutlet weak var helpDescriptionLabel: UILabel!
|
|
@IBOutlet weak var meshifyNameLabel: UILabel!
|
|
@IBOutlet weak var dataTypeLabel: UILabel!
|
|
@IBOutlet weak var historyTableView: UITableView!
|
|
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
|
|
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
|
|
|
historyTableView.delegate = self
|
|
historyTableView.dataSource = self
|
|
setupChannelDisplay()
|
|
SVProgressHUD.show()
|
|
firstly {
|
|
getChannelHistory()
|
|
}.done { _ in
|
|
self.historyTableView.reloadData()
|
|
SVProgressHUD.dismiss()
|
|
}.catch { error in
|
|
print("Error in ChannelDetailViewController promise: \(error)")
|
|
}
|
|
}
|
|
|
|
@IBAction func writeButtonPressed(_ sender: UIButton) {
|
|
}
|
|
|
|
//MARK: - TABLE METHODS
|
|
|
|
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
|
return channelHistory.count
|
|
}
|
|
|
|
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
|
let cell = tableView.dequeueReusableCell(withIdentifier: "channelHistoryCell", for: indexPath) as! ChannelHistoryCell
|
|
if let timestamp = channelHistory[indexPath.row].timestamp {
|
|
cell.timestampLabel.text = formatter.string(from: timestamp)
|
|
} else {
|
|
cell.timestampLabel.text = "Error"
|
|
}
|
|
cell.valueLabel.text = channelHistory[indexPath.row].value
|
|
return cell
|
|
}
|
|
|
|
//MARK: - ChannelDefinition Methods
|
|
func setupChannelDisplay(){
|
|
deviceNameLabel.text = thisDevice?.vanityName ?? "Unknown"
|
|
nameLabel.text = thisChannel?.subTitle ?? "Unknown"
|
|
helpDescriptionLabel.text = thisChannel?.helpExplanation ?? "Unknown"
|
|
meshifyNameLabel.text = thisChannel?.name ?? "Unknown"
|
|
dataTypeLabel.text = channelDataTypes[thisChannel?.dataType ?? 0]
|
|
self.navigationItem.rightBarButtonItem?.isEnabled = (thisChannel?.io)!
|
|
}
|
|
|
|
|
|
@IBAction func openWriteValuePressed(_ sender: UIBarButtonItem) {
|
|
var textField = UITextField()
|
|
|
|
let alert = UIAlertController(title: "Write Value", message: "What value would you like to write to \(thisChannel!.name)?", preferredStyle: .alert)
|
|
let action = UIAlertAction(title: "Write", style: .default) { (action) in
|
|
// what will happen once the user clicks the add item button on our UIAlert
|
|
SVProgressHUD.show()
|
|
firstly {
|
|
self.writeChannelValue(value: textField.text!)
|
|
}.then{ _ in
|
|
self.getChannelHistory()
|
|
}.done { _ in
|
|
self.historyTableView.reloadData()
|
|
SVProgressHUD.dismiss()
|
|
}.catch { error in
|
|
print("ERROR IN openWriteValue: \(error)")
|
|
}
|
|
|
|
}
|
|
alert.addTextField { (valueTextField) in
|
|
valueTextField.placeholder = "123.4567"
|
|
textField = valueTextField
|
|
}
|
|
|
|
alert.addAction(action)
|
|
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
|
|
|
|
present(alert, animated: true, completion: nil)
|
|
}
|
|
|
|
func getChannelHistory() -> Promise<Any> {
|
|
let url = "\(baseURL)/devices/\(thisDevice!.id)/values/\(thisChannel!.id)"
|
|
let headers : HTTPHeaders = [
|
|
"Authorization": user!.authToken
|
|
]
|
|
|
|
return Promise { promise in
|
|
Alamofire.request(url, method: .get, headers: headers)
|
|
.responseJSON { response in
|
|
switch response.result {
|
|
|
|
case .success:
|
|
let channelHistoryJSON : JSON = JSON(response.result.value!)
|
|
self.channelHistory.removeAll()
|
|
for(_, json) : (String, JSON) in channelHistoryJSON {
|
|
let chHistVal = ChannelHistoryValue()
|
|
chHistVal.timestamp = Date(timeIntervalSince1970: Double(json["timestamp"].intValue))
|
|
chHistVal.value = json["value"].stringValue
|
|
self.channelHistory.append(chHistVal)
|
|
}
|
|
self.channelHistory.reverse()
|
|
promise.fulfill(true)
|
|
case .failure(let error):
|
|
promise.reject(error)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func writeChannelValue(value : String) -> Promise<Any> {
|
|
let timestamp: Int = Int(Date().timeIntervalSince1970)
|
|
let channelName = thisChannel?.name
|
|
var channelJson : JSON = JSON()
|
|
channelJson["name"].string = channelName
|
|
channelJson["timestamp"].int = timestamp
|
|
channelJson["value"].string = value
|
|
|
|
var listJson = JSON()
|
|
listJson.arrayObject = [channelJson]
|
|
|
|
let url = "\(baseURL)/devices/\(thisDevice!.id)/values"
|
|
let headers : HTTPHeaders = [
|
|
"Authorization": user!.authToken
|
|
]
|
|
|
|
|
|
|
|
return Promise { promise in
|
|
Alamofire.request(url, method: .put, parameters: [:], encoding: listJson.rawString()!, headers: headers)
|
|
.response { response in
|
|
if response.response?.statusCode == 200 {
|
|
promise.fulfill(true)
|
|
} else {
|
|
promise.reject(String(response.response!.statusCode) as! Error)
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
extension String: ParameterEncoding {
|
|
|
|
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
|
|
var request = try urlRequest.asURLRequest()
|
|
request.httpBody = data(using: .utf8, allowLossyConversion: false)
|
|
return request
|
|
}
|
|
|
|
}
|
|
|