// // ArduinoTask.swift - The task to configure an arduino // once all configuration has been provided. // // Created by Marcus Handte on 02.11.22. // import Foundation import Network import NetworkExtension import MoWeStaApi class ArduinoTask: BaseTask { let appState = AppState.shared let credentials = AppState.shared.credentials let taskState: ArduinoState init(taskState: ArduinoState) { self.taskState = taskState } public func execute() { taskState.phase = .register taskState.failure = nil super.execute(completion: { success in if success { self.taskState.phase = .success } else { self.taskState.failure = self.taskState.phase self.taskState.phase = .failure } }) } override func executeAsync() -> Bool { // check preconditions guard let c = credentials, let lon = taskState.lon, let lat = taskState.lat else { return false } let creator = ArduinoCreator(c, taskState.model) guard let handle = creator.createDevice(), let id = handle.id else { return false } let config = ArduinoConfig(ssid: taskState.network, password: taskState.password, token: handle.token, id: id, latitude: lat, longitude: lon) DispatchQueue.main.async { self.taskState.phase = .connect } // connect to the network let joiner = ArduinoJoiner() if !joiner.connect() { creator.deleteDevice() return false } DispatchQueue.main.async { self.taskState.phase = .transfer } // transfer the data let transfer = ArduinoTransfer(config) if !transfer.transfer() { joiner.disconnect() creator.deleteDevice() return false } // disconnect joiner.disconnect() return true } } class ArduinoTransfer { let config: ArduinoConfig var transmit = false var success = false init(_ config: ArduinoConfig) { self.config = config } public func transfer() -> Bool { let queue = DispatchQueue.init(label: "transfer") let tcpOptions = NWProtocolTCP.Options() tcpOptions.connectionTimeout = 60 tcpOptions.noDelay = true tcpOptions.connectionDropTime = 30 let connection = NWConnection( host: NWEndpoint.Host(ArduinoConstants.ip.rawValue), port: NWEndpoint.Port(rawValue: UInt16(ArduinoConstants.port.rawValue)!)!, using: NWParameters(tls: nil, tcp: tcpOptions)) let sender = DispatchSemaphore(value: 0) let receiver = DispatchSemaphore(value: 0) connection.stateUpdateHandler = { state in switch state { case .setup: self.dprint("Tcp setup") case .cancelled: self.dprint("Tcp cancelled") sender.signal() case let .failed(error): self.dprint("Tcp failed \(error)") sender.signal() case .preparing: self.dprint("Tcp preparing") case .ready: self.dprint("Tcp ready") sender.signal() case let .waiting(error): self.dprint("Tcp waiting \(error)") default: self.dprint("Tcp unknown") } } dprint("Waitng for connection") connection.start(queue: queue) sender.wait() dprint("Continue connection") if connection.state != .ready { dprint("Connection state not ready but \(connection.state)") connection.cancel() return false } dprint("Start receiving data") connection.receive(minimumIncompleteLength: 5, maximumLength: 10, completion: { data, context, complete, error in if let d = data { let s = String(decoding: d, as: UTF8.self) self.dprint("Reception ok \(s)") self.success = s.lowercased().contains("success") receiver.signal() } else if let e = error { self.dprint("Reception error \(e)") receiver.signal() } }) dprint("Sending data") connection.send( content: config.toJson(), completion: .contentProcessed({ error in self.dprint("Processed") if let e = error { self.dprint("Transmission error \(e)") } self.transmit = error == nil sender.signal() }) ) sender.wait() dprint("Continue sending") if !transmit { dprint("Aborting since sending failed") connection.cancel() return false } let result = receiver.wait(timeout: .now() + 30) if (result == .timedOut) { dprint("Timeout") } dprint("Closing connection \(success)") connection.cancel() return success } func dprint(_ text: String) { // heavy debug // print(text) } } /// A class to join the wifi network of the station. class ArduinoJoiner { let config: NEHotspotConfiguration var success = false public init() { self.config = NEHotspotConfiguration(ssidPrefix: ArduinoConstants.ssid.rawValue, passphrase: ArduinoConstants.password.rawValue, isWEP: false) self.config.joinOnce = false } public func connect() -> Bool { let group = DispatchGroup() group.enter() NEHotspotConfigurationManager.shared.apply(self.config) { error in if error == nil { self.success = true } else { self.success = false self.disconnect() } group.leave() } group.wait() return success } public func disconnect() { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: ArduinoConstants.ssid.rawValue) } } /// A class to create and delete a device entry for a weather station. class ArduinoCreator { private static let MAX_ATTEMPT = 8 let credential: UserCredentials let model: String var handle: DeviceHandle? = nil init(_ credential: UserCredentials, _ model: String) { self.credential = credential self.model = model } public func createDevice() -> DeviceHandle? { print("Creating device handle.") let info = DeviceInfo(os: .arduino, manufacturer: "MoWeSta", device: "Arduino", model: model) let group = DispatchGroup() group.enter() let rb = DefaultAPI.createDeviceWithRequestBuilder(deviceInfo: info) rb.addHeaders(ApiHeader.create(credential)) rb.execute() { result in switch result { case let .success(response): print("Sucessfully created device.") self.handle = response.body case let .failure(.error(code, _, _, _)): print("Failed to create device \(code).") } group.leave() } group.wait() return handle } public func deleteDevice() { retryDeleteDevice(attempt: 0) } private func retryDeleteDevice(attempt: Int) { if let h = handle, let id = h.id { print("Deleting device \(id) (\(attempt)).") let group = DispatchGroup() group.enter() let rb = DefaultAPI.deleteDeviceWithRequestBuilder(id: id) rb.addHeaders(ApiHeader.create(credential)) rb.execute() { result in switch result { case .success(_): print("Successfully deleted device.") self.handle = nil case let .failure(.error(code, _, _, _)): if (code == -1 && attempt < ArduinoCreator.MAX_ATTEMPT) { BaseTask.queue.asyncAfter(deadline: .now() + 5) { self.retryDeleteDevice(attempt: attempt + 1) } } else { print("Failed to delete device \(code).") } } group.leave() } group.wait() } } }