// // 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 let port: Int = 50051 var stopped = false func makeClient(port: Int, group: EventLoopGroup) -> MotorControl_CarControlClient { let channel = ClientConnection.insecure(group: group) // TODO: Pass the host in based on the settings. .connect(host: "10.0.0.55", port: port) return MotorControl_CarControlClient(channel: channel) } func startUpdating() { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { try? group.syncShutdownGracefully() } let client = makeClient(port: self.port, group: group) let options = CallOptions(timeout: .seconds(rounding: 10)) let call = client.stream_vehicle_2d(callOptions: options) call.response.whenFailure { error in print("RecordRoute Failed: \(error)") self.stop() } call.status.whenComplete { _ in print("Finished RecordRoute") self.stop() } call.response.whenSuccess { summary in print("Finished") self.stop() } DispatchQueue.global(qos: .userInteractive).async{ // 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 } } } }