Files
picar/SwiftyCar/Sources/SwiftyCar/VehicleFactory.swift
Michael Pivato 2d93438eb8 Stop using gradlew in gitlab-ci, collapse proto codegen into a single job, add pipeline cacheing
These changes all make the pipeline run much faster for incremental builds.
2020-11-22 05:52:53 +00:00

46 lines
1.8 KiB
Swift

//
// VehicleFactory.swift
//
//
// Created by Michael Pivato on 20/5/20.
//
import Foundation
import SwiftyGPIO
import Swift2dCar
import SwiftSerial
func getVehicle2D() throws -> Vehicle2D? {
// TODO: Clean up this factory, or see if we can get dependency injection working.
if let value = ProcessInfo.processInfo.environment["CAR_VEHICLE"] {
switch value{
case "VEHICLE_2D":
// Get car for rpi.
let pwms = SwiftyGPIO.hardwarePWMs(for:.RaspberryPi3)!
return try RPiVehicle2D(withThrottlePin: PWMHardwareServo(forPin: (pwms[0]?[.P18])!)!, withSteeringPin:PWMHardwareServo(forPin: (pwms[1]?[.P19])!)!)
case "VEHICLE_SERIAL":
// TODO: Get from environment variable. tty won't work in macos anyway.
// We share the serialport object, as cu will block on macOS (required by SwiftSerial), so can't open 2 of the same port.
let serialPort = SerialPort(path: "/dev/ttyUSB0")
// The port does not open/initialise inside of the ESP32ServoOutputs, as on macOS /dev/cu.* blocks.
try serialPort.openPort()
serialPort.setSettings(receiveRate: .baud115200, transmitRate: .baud115200, minimumBytesToRead: 1)
guard let throttlePin = Esp32ServoOutput(forChannel: 1, forPin: 14, onPort: serialPort) else {
print("Failed to create throttle pin.")
return nil
}
guard let steeringPin = Esp32ServoOutput(forChannel: 2, forPin: 12, onPort: serialPort) else {
print("Failed to create steering pin.")
return nil
}
return try RPiVehicle2D(withThrottlePin: PWMHardwareServo(forPin: throttlePin)!, withSteeringPin: PWMHardwareServo(forPin: steeringPin)!)
default:
return MockVehicle()
}
}
return MockVehicle()
}