Skip to content

Instantly share code, notes, and snippets.

@DiogoAndre
Created December 16, 2018 20:22
Show Gist options
  • Save DiogoAndre/d473125d31d825e010094c1964e2f383 to your computer and use it in GitHub Desktop.
Save DiogoAndre/d473125d31d825e010094c1964e2f383 to your computer and use it in GitHub Desktop.
//
// DeviceDriver.swift
// spt
//
// Created by Diogo Andre de Assumpcao on 22/10/18.
import RealmSwift // Realm Mobile Database. Used instead of CoreData.
import Alamofire // HTTP networking library written in Swift.
class DeviceDriver {
let device: Device
var timeout: Int
let configuration = URLSessionConfiguration.ephemeral
var sessionManager = Alamofire.SessionManager()
var base_url: String
var default_headers: HTTPHeaders = ["Content-Type": "text/plain"]
init(_ device: Device) {
self.device = device
self.timeout = device.timeout
self.base_url = "https://\(device.ipv4):\(device.port)/admin/exec"
setSessionManager()
addAuthHeaders()
}
func setSessionManager() {
// This will disable certificate check. Not a great idea in production.
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"\(self.device.ipv4)": .disableEvaluation
]
self.sessionManager = SessionManager(
configuration: self.configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
}
// Add authentication headers
func addAuthHeaders() {
if let authorizationHeader = Request.authorizationHeader(user: device.username, password: device.password) {
default_headers[authorizationHeader.key] = authorizationHeader.value
}
}
// Test connection to device
func isAlive(_ completionHandler: @escaping (DataResponse<String>) -> Void) {
let url = "\(self.base_url)/show+version"
self.sessionManager.request(url, headers: self.default_headers)
.validate(statusCode: 200..<300)
.validate(contentType: ["text/plain"])
.responseString { response in
completionHandler(response)
}
}
// Send request to device
func sendRequest(endpoint: String = "", _ completionHandler: @escaping (DataResponse<String>) -> Void) {
let url = "\(self.base_url)/\(endpoint)"
let _ = self.sessionManager.request(url, headers: self.default_headers)
.validate(statusCode: 200..<300)
.validate(contentType: ["text/plain"])
.responseString { response in
completionHandler(response)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment