Michael Redig 2 лет назад
Родитель
Сommit
ba9f5e6773
3 измененных файлов с 52 добавлено и 15 удалено
  1. 29 0
      Sources/PortMode.swift
  2. 8 15
      Sources/SerialPort.swift
  3. 15 0
      Sources/SerialPortDeprecated.swift

+ 29 - 0
Sources/PortMode.swift

@@ -0,0 +1,29 @@
+import Foundation
+
+public enum PortMode {
+	case receive
+	case transmit
+	case receiveAndTransmit
+
+	var receive: Bool {
+		switch self {
+		case .receive:
+			true
+		case .transmit:
+			false
+		case .receiveAndTransmit:
+			true
+		}
+	}
+
+	var transmit: Bool {
+		switch self {
+		case .receive:
+			false
+		case .transmit:
+			true
+		case .receiveAndTransmit:
+			true
+		}
+	}
+}

+ 8 - 15
Sources/SerialPort.swift

@@ -15,26 +15,19 @@ public class SerialPort {
 		self.path = path
 	}
 
-	public func openPort() throws {
-		try openPort(toReceive: true, andTransmit: true)
-	}
-
-	public func openPort(toReceive receive: Bool, andTransmit transmit: Bool) throws {
+	public func openPort(portMode: PortMode = .receiveAndTransmit) throws {
 		guard !path.isEmpty else { throw PortError.invalidPath }
 		guard isOpen == false else { throw PortError.instanceAlreadyOpen }
 
-		guard receive || transmit else { throw PortError.mustReceiveOrTransmit }
-
-		var readWriteParam : Int32
+		let readWriteParam: Int32
 
-		if receive && transmit {
-			readWriteParam = O_RDWR
-		} else if receive {
+		switch portMode {
+		case .receive:
 			readWriteParam = O_RDONLY
-		} else if transmit {
+		case .transmit:
 			readWriteParam = O_WRONLY
-		} else {
-			fatalError()
+		case .receiveAndTransmit:
+			readWriteParam = O_RDWR
 		}
 
 		#if os(Linux)
@@ -49,7 +42,7 @@ public class SerialPort {
 		}
 
 		guard
-			receive,
+			portMode.receive,
 			let fileDescriptor
 		else { return }
 		let pollSource = DispatchSource.makeReadSource(fileDescriptor: fileDescriptor, queue: .global(qos: .default))

+ 15 - 0
Sources/SerialPortDeprecated.swift

@@ -1,6 +1,21 @@
 import Foundation
 
 extension SerialPort {
+	@available(*, deprecated, message: "Use `open(portMode:)` instead")
+	public func openPort(toReceive receive: Bool, andTransmit transmit: Bool) throws {
+		switch (receive, transmit) {
+		case (true, false):
+			try openPort(portMode: .receive)
+		case (false, true):
+			try openPort(portMode: .transmit)
+		case (true, true):
+			try openPort(portMode: .receiveAndTransmit)
+		case (false, false):
+			throw PortError.mustReceiveOrTransmit
+		}
+	}
+
+
 	@available(*, deprecated, message: "Use async reading methods")
 	public func readBytes(into buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int {
 		guard let fileDescriptor = fileDescriptor else {