// // PiLoader.swift // CarController // // Created by Michael Pivato on 4/5/20. // Copyright © 2020 Michael Pivato. All rights reserved. // import Foundation import SwiftUI import GRPC import NIO class PiLoader: ObservableObject { // Find a cleaner way to handle these properties @Published var throttle: Float = 0.5 @Published var steering: Float = 0.5 var stopped = false func startUpdating(forPort port: Int, atHost host: String) { DispatchQueue.global(qos: .background).async{ let group = PlatformSupport.makeEventLoopGroup(loopCount: 1) defer { try? group.syncShutdownGracefully() } let client = makeClient(port: port, host: host, group: group) let options = CallOptions(timeout: .seconds(rounding: 10)) let call = client.stream_vehicle_2d(callOptions: options) call.response.whenFailure { error in print("Failed: \(error)") self.stop() } call.status.whenComplete { _ in print("Finished") self.stop() } call.response.whenSuccess { summary in print("Finished") self.stop() } // Running in background. Do the update thread stuff. while (!self.stopped){ call.sendMessage(self.createProto(), promise: nil) Thread.sleep(forTimeInterval: 0.2) } } } func stop(){ stopped = true } func createProto() -> MotorControl_Vehicle2DRequest { return .with{ $0.throttle = .with{ $0.throttle = self.throttle } $0.steering = .with{ $0.steering = self.steering } } } } func makeClient(port: Int, host: String, group: EventLoopGroup) -> MotorControl_CarControlClient { let channel = ClientConnection.insecure(group: group) // TODO: Pass the host in based on the settings. .connect(host: host, port: port) return MotorControl_CarControlClient(channel: channel) }