From d107baa1d8a22808fb4f8a4f09f0731cf9c37da8 Mon Sep 17 00:00:00 2001 From: Piv <18462828+Piv200@users.noreply.github.com> Date: Sun, 13 Sep 2020 21:19:34 +0930 Subject: [PATCH] Move settings/open of port into convenience initialiser. This avoids attempting to open a serial port multiple times, which can be problematic if a blocking connection is used. Instead settings and port connection should be handled prior to designated inititializer. --- Package.resolved | 25 +++++++++++++++++++++++ Sources/Swift2dCar/Esp32ServoOutput.swift | 9 ++++---- 2 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 Package.resolved diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 0000000..73e5140 --- /dev/null +++ b/Package.resolved @@ -0,0 +1,25 @@ +{ + "object": { + "pins": [ + { + "package": "SwiftSerial", + "repositoryURL": "https://vato.ddns.net/gitlab/vato007/SwiftSerial.git", + "state": { + "branch": "master", + "revision": "0e824cc38c6802e69543d0c1406d34babfd68e2e", + "version": null + } + }, + { + "package": "SwiftyGPIO", + "repositoryURL": "https://github.com/uraimo/SwiftyGPIO.git", + "state": { + "branch": null, + "revision": "2038228e020cf12a62012b1ebe36bb9b8e6fdb6a", + "version": "1.2.5" + } + } + ] + }, + "version": 1 +} diff --git a/Sources/Swift2dCar/Esp32ServoOutput.swift b/Sources/Swift2dCar/Esp32ServoOutput.swift index 07a255d..b43ef35 100644 --- a/Sources/Swift2dCar/Esp32ServoOutput.swift +++ b/Sources/Swift2dCar/Esp32ServoOutput.swift @@ -30,14 +30,15 @@ public class Esp32ServoOutput : PWMOutput { self.serialPort = port } - public convenience init?(forChannel channel: UInt8, forPin pin: UInt8, onPort port: String) { - self.init(forChannel: channel, forPin: pin, onPort: SerialPort(path: port)) + public convenience init?(forChannel channel: UInt8, forPin pin: UInt8, onPort port: String) throws { + let initPort = SerialPort(path: port) + try initPort.openPort() + initPort.setSettings(receiveRate: .baud115200, transmitRate: .baud115200, minimumBytesToRead: 1) + self.init(forChannel: channel, forPin: pin, onPort: initPort) } public func initPWM() { do { - try serialPort.openPort() - serialPort.setSettings(receiveRate: .baud115200, transmitRate: .baud115200, minimumBytesToRead: 1) let bytesWritten = try serialPort.writeData(Data([0, 1, channel, pin])) if bytesWritten != 4 { print("Wrote %d bytes, but should have written 4", bytesWritten)