Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af1fa134cc | ||
|
|
812a55a381 | ||
|
|
41ddf0247a | ||
|
|
f3c3a214e3 | ||
|
|
5536368ba7 | ||
|
|
e2063420e9 | ||
|
|
cfaf24357c | ||
|
|
543e7d39e0 | ||
|
|
f9981b1cec | ||
|
|
d36d0132a8 | ||
|
|
b29775dfbe | ||
|
|
8a8dfcb190 | ||
|
|
25600e48fb | ||
|
|
7c06c99bd1 | ||
|
|
ad3142da95 | ||
|
|
0c14b6d2b9 | ||
|
|
4522b9261e | ||
|
|
144c9bbf5a | ||
|
|
20cf246eda | ||
|
|
02e0d4837e | ||
|
|
816720e15c | ||
|
|
c60e0334bd | ||
|
|
ade0cdc3cd | ||
|
|
3e4b905e7b | ||
|
|
e73ea6056d | ||
|
|
640cf2f7c3 | ||
|
|
21adc2c8f4 |
@@ -11,7 +11,7 @@ let test3Strings: String = testString + "\n" + testString + "\n" + testString +
|
||||
|
||||
let arguments = CommandLine.arguments
|
||||
guard arguments.count >= 2 else {
|
||||
print("Need serial port name, e.g. /dev/ttyUSB0 as the first argument.")
|
||||
print("Need serial port name, e.g. /dev/ttyUSB0 or /dev/cu.usbserial as the first argument.")
|
||||
exit(1)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ do {
|
||||
print("Serial port \(portName) opened successfully.")
|
||||
defer {
|
||||
serialPort.closePort()
|
||||
print("Port Closed")
|
||||
}
|
||||
|
||||
serialPort.setSettings(receiveRate: .baud9600,
|
||||
@@ -73,10 +74,10 @@ do {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
print("End of example");
|
||||
|
||||
|
||||
print("We successfully received back \(numberOfMultiNewLineTest) lines")
|
||||
|
||||
} catch PortError.failedToOpen {
|
||||
print("Serial port \(portName) failed to open. You might need root permissions.")
|
||||
} catch {
|
||||
|
||||
8
Examples/SwiftSerialIM/Package.swift
Normal file
8
Examples/SwiftSerialIM/Package.swift
Normal file
@@ -0,0 +1,8 @@
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "SwiftSerialIM",
|
||||
dependencies: [
|
||||
.Package(url: "https://github.com/yeokm1/SwiftSerial.git", majorVersion: 0)
|
||||
]
|
||||
)
|
||||
128
Examples/SwiftSerialIM/Sources/main.swift
Normal file
128
Examples/SwiftSerialIM/Sources/main.swift
Normal file
@@ -0,0 +1,128 @@
|
||||
import Foundation
|
||||
import SwiftSerial
|
||||
|
||||
|
||||
let arguments = CommandLine.arguments
|
||||
guard arguments.count >= 2 else {
|
||||
print("Need serial port name, e.g. /dev/ttyUSB0 or /dev/cu.usbserial as the first argument.")
|
||||
exit(1)
|
||||
}
|
||||
|
||||
print("Connect a null modem serial cable between two machines before you continue to use this program")
|
||||
|
||||
let portName = arguments[1]
|
||||
let serialPort: SerialPort = SerialPort(path: portName)
|
||||
|
||||
var myturn = true
|
||||
|
||||
// Prepares the stdin so we can getchar() without echoing
|
||||
func prepareStdin() {
|
||||
|
||||
// Set up the control structure
|
||||
var settings = termios()
|
||||
|
||||
// Get options structure for stdin
|
||||
tcgetattr(STDIN_FILENO, &settings)
|
||||
|
||||
//Turn off ICANON and ECHO
|
||||
settings.c_lflag &= ~tcflag_t(ICANON | ECHO)
|
||||
|
||||
tcsetattr(STDIN_FILENO, TCSANOW, &settings)
|
||||
}
|
||||
|
||||
func getKeyPress () -> UnicodeScalar {
|
||||
let valueRead: Int = Int(getchar())
|
||||
|
||||
guard let charRead = UnicodeScalar(valueRead) else{
|
||||
return UnicodeScalar("")!
|
||||
}
|
||||
|
||||
return charRead
|
||||
}
|
||||
|
||||
func printToScreenFrom(myself: Bool, characterToPrint: UnicodeScalar){
|
||||
|
||||
if(myturn && !myself){
|
||||
myturn = false
|
||||
print("\n\nOther: ", terminator:"")
|
||||
} else if (!myturn && myself){
|
||||
myturn = true
|
||||
print("\n\nMe: ", terminator:"")
|
||||
}
|
||||
|
||||
print(characterToPrint, terminator:"")
|
||||
}
|
||||
|
||||
func backgroundRead() {
|
||||
while true{
|
||||
do{
|
||||
let readCharacter = try serialPort.readChar()
|
||||
printToScreenFrom(myself: false, characterToPrint: readCharacter)
|
||||
} catch {
|
||||
print("Error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
do {
|
||||
|
||||
print("Attempting to open port: \(portName)")
|
||||
try serialPort.openPort()
|
||||
print("Serial port \(portName) opened successfully.")
|
||||
defer {
|
||||
serialPort.closePort()
|
||||
print("Port Closed")
|
||||
}
|
||||
|
||||
serialPort.setSettings(receiveRate: .baud9600,
|
||||
transmitRate: .baud9600,
|
||||
minimumBytesToRead: 1)
|
||||
|
||||
prepareStdin()
|
||||
|
||||
|
||||
//Turn off output buffering if not multiple threads will have problems printing
|
||||
setbuf(stdout, nil);
|
||||
|
||||
|
||||
//Run the serial port reading function in another thread
|
||||
#if os(Linux)
|
||||
var readingThread = pthread_t()
|
||||
|
||||
let pthreadFunc: @convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? = {
|
||||
observer in
|
||||
|
||||
backgroundRead()
|
||||
return nil
|
||||
}
|
||||
|
||||
pthread_create(&readingThread, nil, pthreadFunc, nil)
|
||||
|
||||
#elseif os(OSX)
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
backgroundRead()
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
print("\nReady to send and receive messages in realtime!")
|
||||
print("\nMe: ", terminator:"")
|
||||
|
||||
|
||||
while true {
|
||||
var enteredKey = getKeyPress()
|
||||
printToScreenFrom(myself: true, characterToPrint: enteredKey)
|
||||
var _ = try serialPort.writeChar(enteredKey)
|
||||
}
|
||||
|
||||
|
||||
} catch PortError.failedToOpen {
|
||||
print("Serial port \(portName) failed to open. You might need root permissions.")
|
||||
} catch {
|
||||
print("Error: \(error)")
|
||||
}
|
||||
|
||||
|
||||
63
README.md
63
README.md
@@ -9,13 +9,21 @@ This library is an improvement over my previous now deprecated library [SwiftLin
|
||||
<a href="https://developer.apple.com/swift"><img src="https://img.shields.io/badge/swift3-compatible-orange.svg?style=flat" alt="Swift 3 compatible" /></a>
|
||||
<a href="https://raw.githubusercontent.com/uraimo/SwiftyGPIO/master/LICENSE"><img src="http://img.shields.io/badge/license-MIT-blue.svg?style=flat" alt="License: MIT" /></a>
|
||||
|
||||
## Talk on this library
|
||||
|
||||
I gave a talk on this library and one of its examples SwiftSerialIM. Click on the links below to see the slides and video.
|
||||
|
||||
[](http://www.slideshare.net/yeokm1/a-science-project-swift-serial-chat)
|
||||
|
||||
[](https://www.youtube.com/watch?v=6PWP1eZo53s)
|
||||
|
||||
## Mac OS Preparation
|
||||
|
||||
You should have Xcode 8 installed with the command line tools.
|
||||
|
||||
## Linux System Preparation
|
||||
|
||||
Before using this library, I assume you already have Ubuntu installed and fully updated on your system or single-board computer. To get Ubuntu installed on the Raspberry Pi, use this [link](https://wiki.ubuntu.com/ARM/RaspberryPi).
|
||||
Before using this library, I assume you already have Ubuntu installed and fully updated on your system or single-board computer. To get Ubuntu installed on the Raspberry Pi, use this [link](https://wiki.ubuntu.com/ARM/RaspberryPi).
|
||||
|
||||
### Install Swift 3 on Ubuntu on x86-based machines
|
||||
|
||||
@@ -50,28 +58,52 @@ sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6
|
||||
|
||||
cd ~
|
||||
#Replace the link below with the latest version
|
||||
wget http://swift-arm.ddns.net/job/Swift-3.0-Pi3-ARM-Incremental/lastSuccessfulBuild/artifact/swift-3.0-2016-10-13-RPi23-ubuntu16.04.tar.gz
|
||||
wget http://swift-arm.ddns.net/job/Swift-3.0-Pi3-ARM-Incremental/lastSuccessfulBuild/artifact/swift-3.0-2016-10-13-RPi23-ubuntu16.04.tar.gz
|
||||
mkdir swift-3.0
|
||||
cd swift-3.0 && tar -xzf ../swift-3.0-2016-10-13-RPi23-ubuntu16.04.tar.gz
|
||||
cd swift-3.0 && tar -xzf ../swift-3.0-2016-10-13-RPi23-ubuntu16.04.tar.gz
|
||||
|
||||
#This command can be added to your bash profile so Swift will be in your PATH after a reboot
|
||||
nano ~/.profile
|
||||
export PATH=$HOME/swift-3.0/usr/bin:$PATH
|
||||
```
|
||||
## Jumping straight into sample code
|
||||
To get started quickly, you can take a look at my example projects [here](Examples/).
|
||||
|
||||
To get started quickly, you can take a look at my example project [here](Examples/SwiftSerialExample). In order to run the example properly, you need to connect one of your (USB/UART) serial ports in a loopback manner. Basically, you short the TX and RX pins of the serial port.
|
||||
### Example 1: Loopback Test
|
||||
|
||||
In order to run this example properly, you need to connect one of your (USB/UART) serial ports in a loopback manner. Basically, you short the TX and RX pins of the serial port. This library currently only support the `/dev/cu.*` variant on Mac. Read the beginning of the API usage section for more details.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yeokm1/SwiftSerial.git
|
||||
cd SwiftSerial/Examples/SwiftSerialExample/
|
||||
swift build
|
||||
#You need root to access the serial port. Replace /dev/ttyUSB0 with the name of your serial port under test
|
||||
|
||||
#For Linux: You need root to access the serial port. Replace /dev/ttyUSB0 with the name of your serial port under test
|
||||
sudo ./.build/debug/SwiftSerialExample /dev/ttyUSB0
|
||||
|
||||
#For Mac: Root is not required
|
||||
./.build/debug/SwiftSerialExample /dev/cu.usbserial
|
||||
|
||||
#If all goes well you should see a series of messages informing you that data transmitted has been received properly.
|
||||
```
|
||||
|
||||
### Example 2: A chat app between 2 machines
|
||||
|
||||
In order to run this example properly, you need 2 machines connected by a [null-modem cable](https://en.wikipedia.org/wiki/Null_modem) or 2 USB-Serial adapters with the TX-RX pins connected to each other. Run a copy of my program on both machines.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yeokm1/SwiftSerial.git
|
||||
cd SwiftSerial/Examples/SwiftSerialIM/
|
||||
swift build
|
||||
|
||||
#For Linux: You need root to access the serial port. Replace /dev/ttyUSB0 with the name of your serial port under test
|
||||
sudo ./.build/debug/SwiftSerialIM /dev/ttyUSB0
|
||||
|
||||
#For Mac: Root is not required
|
||||
./.build/debug/SwiftSerialIM /dev/cu.usbserial
|
||||
```
|
||||
People at both machines can now "chat" with each other.
|
||||
|
||||
## Integrating with your project
|
||||
|
||||
Add SwiftSerial as a dependency to your project by editing the `Package.swift` file.
|
||||
@@ -98,7 +130,9 @@ Then run `swift build` to download the dependencies and compile your project. Yo
|
||||
```swift
|
||||
let serialPort: SerialPort = SerialPort(path: portName)
|
||||
```
|
||||
Supply the portname that you wish to open like `/dev/ttyUSB0` or `/dev/tty.usbserial`.
|
||||
Supply the portname that you wish to open like `/dev/ttyUSB0` or `/dev/cu.usbserial`.
|
||||
|
||||
For Macs, this library currently only works with the `/dev/cu.*` ports instead of the `/dev/tty.*`. I have enabled blocking on the serial port to prevent high CPU usage which will prevent the `/dev/tty.*` from working. Read more about the differences between the two [here](http://stackoverflow.com/questions/8632586/macos-whats-the-difference-between-dev-tty-and-dev-cu). If there is a problem, open an issue describing your situation and let me look into it.
|
||||
|
||||
### Opening the Serial Port
|
||||
|
||||
@@ -113,7 +147,7 @@ Opening the port without any parameters will set the port to receive and transmi
|
||||
```swift
|
||||
serialPort.setSettings(receiveRate: .baud9600, transmitRate: .baud9600, minimumBytesToRead: 1)
|
||||
```
|
||||
The port settings call can be as simple as the above. For the baud rate, just supply both transmit and receive even if you are only intending to use one transfer direction. For example, transmitRate will be ignored if you specified `andTransmit : false` when opening the port.
|
||||
The port settings call can be as simple as the above. For the baud rate, just supply both transmit and receive even if you are only intending to use one transfer direction. For example, transmitRate will be ignored if you specified `andTransmit : false` when opening the port.
|
||||
|
||||
`minimumBytesToRead` determines how many characters the system must wait to receive before it will return from a [read()](https://linux.die.net/man/2/read) function. If in doubt, just put 1.
|
||||
|
||||
@@ -162,6 +196,16 @@ func readUntilChar(_ terminator: CChar) throws -> String
|
||||
```
|
||||
Keep reading until the specified CChar is encountered. Return the string read so far without that value.
|
||||
|
||||
```swift
|
||||
func readByte() throws -> UInt8
|
||||
```
|
||||
Read only one byte. This works best if `minimumBytesToRead` has been set to `1` when opening the port. This function internally calls `readBytes()`.
|
||||
|
||||
```swift
|
||||
func readChar() throws -> UnicodeScalar
|
||||
```
|
||||
Read only one character. This works best if `minimumBytesToRead` has been set to `1` when opening the port. This function internally calls `readByte()`.
|
||||
|
||||
### Writing data to the port
|
||||
|
||||
There are several functions you can use to write data. All functions here are blocking till all the data has been written. All functions can throw `PortError.mustBeOpen`.
|
||||
@@ -181,6 +225,11 @@ func writeBytes(from buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> I
|
||||
```
|
||||
Function for those that want to mess with unsafe pointers. You have to specify how many bytes have to be written. Will return how many bytes actually written.
|
||||
|
||||
```swift
|
||||
func writeChar(_ character: UnicodeScalar) throws -> Int{
|
||||
```
|
||||
Writes only one character. Will return `1` if successful. This function internally calls `writeString()`. Pull requests for a better way of doing this is appreciated.
|
||||
|
||||
### Closing the port
|
||||
|
||||
Just do `serialPort.closePort()` to close the port once you are done using it.
|
||||
|
||||
@@ -1,483 +1,512 @@
|
||||
import Foundation
|
||||
|
||||
#if os(Linux)
|
||||
public enum BaudRate {
|
||||
case baud0
|
||||
case baud50
|
||||
case baud75
|
||||
case baud110
|
||||
case baud134
|
||||
case baud150
|
||||
case baud200
|
||||
case baud300
|
||||
case baud600
|
||||
case baud1200
|
||||
case baud1800
|
||||
case baud2400
|
||||
case baud4800
|
||||
case baud9600
|
||||
case baud19200
|
||||
case baud38400
|
||||
case baud57600
|
||||
case baud115200
|
||||
case baud230400
|
||||
case baud460800
|
||||
case baud500000
|
||||
case baud576000
|
||||
case baud921600
|
||||
case baud1000000
|
||||
case baud1152000
|
||||
case baud1500000
|
||||
case baud2000000
|
||||
case baud2500000
|
||||
case baud3500000
|
||||
case baud4000000
|
||||
|
||||
var speedValue: speed_t {
|
||||
switch self {
|
||||
case .baud0:
|
||||
return speed_t(B0)
|
||||
case .baud50:
|
||||
return speed_t(B50)
|
||||
case .baud75:
|
||||
return speed_t(B75)
|
||||
case .baud110:
|
||||
return speed_t(B110)
|
||||
case .baud134:
|
||||
return speed_t(B134)
|
||||
case .baud150:
|
||||
return speed_t(B150)
|
||||
case .baud200:
|
||||
return speed_t(B200)
|
||||
case .baud300:
|
||||
return speed_t(B300)
|
||||
case .baud600:
|
||||
return speed_t(B600)
|
||||
case .baud1200:
|
||||
return speed_t(B1200)
|
||||
case .baud1800:
|
||||
return speed_t(B1800)
|
||||
case .baud2400:
|
||||
return speed_t(B2400)
|
||||
case .baud4800:
|
||||
return speed_t(B4800)
|
||||
case .baud9600:
|
||||
return speed_t(B9600)
|
||||
case .baud19200:
|
||||
return speed_t(B19200)
|
||||
case .baud38400:
|
||||
return speed_t(B38400)
|
||||
case .baud57600:
|
||||
return speed_t(B57600)
|
||||
case .baud115200:
|
||||
return speed_t(B115200)
|
||||
case .baud230400:
|
||||
return speed_t(B230400)
|
||||
case .baud460800:
|
||||
return speed_t(B460800)
|
||||
case .baud500000:
|
||||
return speed_t(B500000)
|
||||
case .baud576000:
|
||||
return speed_t(B576000)
|
||||
case .baud921600:
|
||||
return speed_t(B921600)
|
||||
case .baud1000000:
|
||||
return speed_t(B1000000)
|
||||
case .baud1152000:
|
||||
return speed_t(B1152000)
|
||||
case .baud1500000:
|
||||
return speed_t(B1500000)
|
||||
case .baud2000000:
|
||||
return speed_t(B2000000)
|
||||
case .baud2500000:
|
||||
return speed_t(B2500000)
|
||||
case .baud3500000:
|
||||
return speed_t(B3500000)
|
||||
case .baud4000000:
|
||||
return speed_t(B4000000)
|
||||
}
|
||||
}
|
||||
}
|
||||
#elseif os(OSX)
|
||||
public enum BaudRate {
|
||||
case baud0
|
||||
case baud50
|
||||
case baud75
|
||||
case baud110
|
||||
case baud134
|
||||
case baud150
|
||||
case baud200
|
||||
case baud300
|
||||
case baud600
|
||||
case baud1200
|
||||
case baud1800
|
||||
case baud2400
|
||||
case baud4800
|
||||
case baud9600
|
||||
case baud19200
|
||||
case baud38400
|
||||
case baud57600
|
||||
case baud115200
|
||||
case baud230400
|
||||
|
||||
var speedValue: speed_t {
|
||||
switch self {
|
||||
case .baud0:
|
||||
return speed_t(B0)
|
||||
case .baud50:
|
||||
return speed_t(B50)
|
||||
case .baud75:
|
||||
return speed_t(B75)
|
||||
case .baud110:
|
||||
return speed_t(B110)
|
||||
case .baud134:
|
||||
return speed_t(B134)
|
||||
case .baud150:
|
||||
return speed_t(B150)
|
||||
case .baud200:
|
||||
return speed_t(B200)
|
||||
case .baud300:
|
||||
return speed_t(B300)
|
||||
case .baud600:
|
||||
return speed_t(B600)
|
||||
case .baud1200:
|
||||
return speed_t(B1200)
|
||||
case .baud1800:
|
||||
return speed_t(B1800)
|
||||
case .baud2400:
|
||||
return speed_t(B2400)
|
||||
case .baud4800:
|
||||
return speed_t(B4800)
|
||||
case .baud9600:
|
||||
return speed_t(B9600)
|
||||
case .baud19200:
|
||||
return speed_t(B19200)
|
||||
case .baud38400:
|
||||
return speed_t(B38400)
|
||||
case .baud57600:
|
||||
return speed_t(B57600)
|
||||
case .baud115200:
|
||||
return speed_t(B115200)
|
||||
case .baud230400:
|
||||
return speed_t(B230400)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
public enum DataBitsSize {
|
||||
case bits5
|
||||
case bits6
|
||||
case bits7
|
||||
case bits8
|
||||
|
||||
var flagValue: tcflag_t {
|
||||
switch self {
|
||||
case .bits5:
|
||||
return tcflag_t(CS5)
|
||||
case .bits6:
|
||||
return tcflag_t(CS6)
|
||||
case .bits7:
|
||||
return tcflag_t(CS7)
|
||||
case .bits8:
|
||||
return tcflag_t(CS8)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public enum ParityType {
|
||||
case none
|
||||
case even
|
||||
case odd
|
||||
|
||||
var parityValue: tcflag_t {
|
||||
switch self {
|
||||
case .none:
|
||||
return 0
|
||||
case .even:
|
||||
return tcflag_t(PARENB)
|
||||
case .odd:
|
||||
return tcflag_t(PARENB | PARODD)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum PortError: Int32, Error {
|
||||
case failedToOpen = -1 // refer to open()
|
||||
case invalidPath
|
||||
case mustReceiveOrTransmit
|
||||
case mustBeOpen
|
||||
case stringsMustBeUTF8
|
||||
}
|
||||
|
||||
public class SerialPort {
|
||||
|
||||
var path: String
|
||||
var fileDescriptor: Int32?
|
||||
|
||||
public init(path: String) {
|
||||
self.path = path
|
||||
}
|
||||
|
||||
public func openPort() throws {
|
||||
try openPort(toReceive: true, andTransmit: true)
|
||||
}
|
||||
|
||||
public func openPort(toReceive receive: Bool, andTransmit transmit: Bool) throws {
|
||||
guard !path.isEmpty else {
|
||||
throw PortError.invalidPath
|
||||
}
|
||||
|
||||
guard receive || transmit else {
|
||||
throw PortError.mustReceiveOrTransmit
|
||||
}
|
||||
|
||||
var readWriteParam : Int32
|
||||
|
||||
if receive && transmit {
|
||||
readWriteParam = O_RDWR
|
||||
} else if receive {
|
||||
readWriteParam = O_RDONLY
|
||||
} else if transmit {
|
||||
readWriteParam = O_WRONLY
|
||||
} else {
|
||||
fatalError()
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
fileDescriptor = open(path, readWriteParam | O_NOCTTY)
|
||||
#elseif os(OSX)
|
||||
fileDescriptor = open(path, readWriteParam | O_NOCTTY | O_EXLOCK | O_NONBLOCK)
|
||||
#endif
|
||||
|
||||
// Throw error if open() failed
|
||||
if fileDescriptor == PortError.failedToOpen.rawValue {
|
||||
throw PortError.failedToOpen
|
||||
}
|
||||
}
|
||||
|
||||
public func setSettings(receiveRate: BaudRate,
|
||||
transmitRate: BaudRate,
|
||||
minimumBytesToRead: Int,
|
||||
timeout: Int = 0, /* 0 means wait indefinitely */
|
||||
parityType: ParityType = .none,
|
||||
sendTwoStopBits: Bool = false, /* 1 stop bit is the default */
|
||||
dataBitsSize: DataBitsSize = .bits8,
|
||||
useHardwareFlowControl: Bool = false,
|
||||
useSoftwareFlowControl: Bool = false,
|
||||
processOutput: Bool = false) {
|
||||
|
||||
guard let fileDescriptor = fileDescriptor else {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// Set up the control structure
|
||||
var settings = termios()
|
||||
|
||||
// Get options structure for the port
|
||||
tcgetattr(fileDescriptor, &settings)
|
||||
|
||||
// Set baud rates
|
||||
cfsetispeed(&settings, receiveRate.speedValue)
|
||||
cfsetospeed(&settings, transmitRate.speedValue)
|
||||
|
||||
// Enable parity (even/odd) if needed
|
||||
settings.c_cflag |= parityType.parityValue
|
||||
|
||||
// Set stop bit flag
|
||||
if sendTwoStopBits {
|
||||
settings.c_cflag |= tcflag_t(CSTOPB)
|
||||
} else {
|
||||
settings.c_cflag &= ~tcflag_t(CSTOPB)
|
||||
}
|
||||
|
||||
// Set data bits size flag
|
||||
settings.c_cflag &= ~tcflag_t(CSIZE)
|
||||
settings.c_cflag |= dataBitsSize.flagValue
|
||||
|
||||
// Set hardware flow control flag
|
||||
#if os(Linux)
|
||||
if useHardwareFlowControl {
|
||||
settings.c_cflag |= tcflag_t(CRTSCTS)
|
||||
} else {
|
||||
settings.c_cflag &= ~tcflag_t(CRTSCTS)
|
||||
}
|
||||
#elseif os(OSX)
|
||||
if useHardwareFlowControl {
|
||||
settings.c_cflag |= tcflag_t(CRTS_IFLOW)
|
||||
settings.c_cflag |= tcflag_t(CCTS_OFLOW)
|
||||
} else {
|
||||
settings.c_cflag &= ~tcflag_t(CRTS_IFLOW)
|
||||
settings.c_cflag &= ~tcflag_t(CCTS_OFLOW)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Set software flow control flags
|
||||
let softwareFlowControlFlags = tcflag_t(IXON | IXOFF | IXANY)
|
||||
if useSoftwareFlowControl {
|
||||
settings.c_iflag |= softwareFlowControlFlags
|
||||
} else {
|
||||
settings.c_iflag &= ~softwareFlowControlFlags
|
||||
}
|
||||
|
||||
// Turn on the receiver of the serial port, and ignore modem control lines
|
||||
settings.c_cflag |= tcflag_t(CREAD | CLOCAL)
|
||||
|
||||
// Turn off canonical mode
|
||||
settings.c_lflag &= ~tcflag_t(ICANON | ECHO | ECHOE | ISIG)
|
||||
|
||||
// Set output processing flag
|
||||
if processOutput {
|
||||
settings.c_oflag |= tcflag_t(OPOST)
|
||||
} else {
|
||||
settings.c_oflag &= ~tcflag_t(OPOST)
|
||||
}
|
||||
|
||||
//Special characters
|
||||
//We do this as c_cc is a C-fixed array which is imported as a tuple in Swift.
|
||||
//To avoid hardcoding the VMIN or VTIME value to access the tuple value, we use the typealias instead
|
||||
#if os(Linux)
|
||||
typealias specialCharactersTuple = (VINTR: cc_t, VQUIT: cc_t, VERASE: cc_t, VKILL: cc_t, VEOF: cc_t, VTIME: cc_t, VMIN: cc_t, VSWTC: cc_t, VSTART: cc_t, VSTOP: cc_t, VSUSP: cc_t, VEOL: cc_t, VREPRINT: cc_t, VDISCARD: cc_t, VWERASE: cc_t, VLNEXT: cc_t, VEOL2: cc_t, spare1: cc_t, spare2: cc_t, spare3: cc_t, spare4: cc_t, spare5: cc_t, spare6: cc_t, spare7: cc_t, spare8: cc_t, spare9: cc_t, spare10: cc_t, spare11: cc_t, spare12: cc_t, spare13: cc_t, spare14: cc_t, spare15: cc_t)
|
||||
var specialCharacters: specialCharactersTuple = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) // NCCS = 32
|
||||
#elseif os(OSX)
|
||||
typealias specialCharactersTuple = (VEOF: cc_t, VEOL: cc_t, VEOL2: cc_t, VERASE: cc_t, VWERASE: cc_t, VKILL: cc_t, VREPRINT: cc_t, spare1: cc_t, VINTR: cc_t, VQUIT: cc_t, VSUSP: cc_t, VDSUSP: cc_t, VSTART: cc_t, VSTOP: cc_t, VLNEXT: cc_t, VDISCARD: cc_t, VMIN: cc_t, VTIME: cc_t, VSTATUS: cc_t, spare: cc_t)
|
||||
var specialCharacters: specialCharactersTuple = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) // NCCS = 20
|
||||
#endif
|
||||
|
||||
specialCharacters.VMIN = cc_t(minimumBytesToRead)
|
||||
specialCharacters.VTIME = cc_t(timeout)
|
||||
settings.c_cc = specialCharacters
|
||||
|
||||
// Commit settings
|
||||
tcsetattr(fileDescriptor, TCSANOW, &settings)
|
||||
}
|
||||
|
||||
public func closePort() {
|
||||
if let fileDescriptor = fileDescriptor {
|
||||
close(fileDescriptor)
|
||||
}
|
||||
fileDescriptor = nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Receiving
|
||||
|
||||
extension SerialPort {
|
||||
|
||||
public func readBytes(into buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int {
|
||||
guard let fileDescriptor = fileDescriptor else {
|
||||
throw PortError.mustBeOpen
|
||||
}
|
||||
|
||||
let bytesRead = read(fileDescriptor, buffer, size)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
public func readData(ofLength length: Int) throws -> Data {
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
|
||||
defer {
|
||||
buffer.deallocate(capacity: length)
|
||||
}
|
||||
|
||||
let bytesRead = try readBytes(into: buffer, size: length)
|
||||
|
||||
var data : Data
|
||||
|
||||
if bytesRead > 0 {
|
||||
data = Data(bytes: buffer, count: bytesRead)
|
||||
} else {
|
||||
//This is to avoid the case where bytesRead can be negative causing problems allocating the Data buffer
|
||||
data = Data(bytes: buffer, count: 0)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
public func readString(ofLength length: Int) throws -> String {
|
||||
var remainingBytesToRead = length
|
||||
var result = ""
|
||||
|
||||
while remainingBytesToRead > 0 {
|
||||
let data = try readData(ofLength: remainingBytesToRead)
|
||||
|
||||
if let string = String(data: data, encoding: String.Encoding.utf8) {
|
||||
result += string
|
||||
remainingBytesToRead -= data.count
|
||||
} else {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
public func readUntilChar(_ terminator: CChar) throws -> String {
|
||||
var data = Data()
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
|
||||
defer {
|
||||
buffer.deallocate(capacity: 1)
|
||||
}
|
||||
|
||||
while true {
|
||||
let bytesRead = try readBytes(into: buffer, size: 1)
|
||||
|
||||
if bytesRead > 0 {
|
||||
let character = CChar(buffer[0])
|
||||
|
||||
if character == terminator {
|
||||
break
|
||||
} else {
|
||||
data.append(buffer, count: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let string = String(data: data, encoding: String.Encoding.utf8) {
|
||||
return string
|
||||
} else {
|
||||
throw PortError.stringsMustBeUTF8
|
||||
}
|
||||
}
|
||||
|
||||
public func readLine() throws -> String {
|
||||
let newlineChar = CChar(10) // Newline/Line feed character `\n` is 10
|
||||
return try readUntilChar(newlineChar)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Transmitting
|
||||
|
||||
extension SerialPort {
|
||||
|
||||
public func writeBytes(from buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int {
|
||||
guard let fileDescriptor = fileDescriptor else {
|
||||
throw PortError.mustBeOpen
|
||||
}
|
||||
|
||||
let bytesWritten = write(fileDescriptor, buffer, size)
|
||||
return bytesWritten
|
||||
}
|
||||
|
||||
public func writeData(_ data: Data) throws -> Int {
|
||||
let size = data.count
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
|
||||
defer {
|
||||
buffer.deallocate(capacity: size)
|
||||
}
|
||||
|
||||
data.copyBytes(to: buffer, count: size)
|
||||
|
||||
let bytesWritten = try writeBytes(from: buffer, size: size)
|
||||
return bytesWritten
|
||||
}
|
||||
|
||||
public func writeString(_ string: String) throws -> Int {
|
||||
guard let data = string.data(using: String.Encoding.utf8) else {
|
||||
throw PortError.stringsMustBeUTF8
|
||||
}
|
||||
|
||||
return try writeData(data)
|
||||
}
|
||||
}
|
||||
import Foundation
|
||||
|
||||
#if os(Linux)
|
||||
public enum BaudRate {
|
||||
case baud0
|
||||
case baud50
|
||||
case baud75
|
||||
case baud110
|
||||
case baud134
|
||||
case baud150
|
||||
case baud200
|
||||
case baud300
|
||||
case baud600
|
||||
case baud1200
|
||||
case baud1800
|
||||
case baud2400
|
||||
case baud4800
|
||||
case baud9600
|
||||
case baud19200
|
||||
case baud38400
|
||||
case baud57600
|
||||
case baud115200
|
||||
case baud230400
|
||||
case baud460800
|
||||
case baud500000
|
||||
case baud576000
|
||||
case baud921600
|
||||
case baud1000000
|
||||
case baud1152000
|
||||
case baud1500000
|
||||
case baud2000000
|
||||
case baud2500000
|
||||
case baud3500000
|
||||
case baud4000000
|
||||
|
||||
var speedValue: speed_t {
|
||||
switch self {
|
||||
case .baud0:
|
||||
return speed_t(B0)
|
||||
case .baud50:
|
||||
return speed_t(B50)
|
||||
case .baud75:
|
||||
return speed_t(B75)
|
||||
case .baud110:
|
||||
return speed_t(B110)
|
||||
case .baud134:
|
||||
return speed_t(B134)
|
||||
case .baud150:
|
||||
return speed_t(B150)
|
||||
case .baud200:
|
||||
return speed_t(B200)
|
||||
case .baud300:
|
||||
return speed_t(B300)
|
||||
case .baud600:
|
||||
return speed_t(B600)
|
||||
case .baud1200:
|
||||
return speed_t(B1200)
|
||||
case .baud1800:
|
||||
return speed_t(B1800)
|
||||
case .baud2400:
|
||||
return speed_t(B2400)
|
||||
case .baud4800:
|
||||
return speed_t(B4800)
|
||||
case .baud9600:
|
||||
return speed_t(B9600)
|
||||
case .baud19200:
|
||||
return speed_t(B19200)
|
||||
case .baud38400:
|
||||
return speed_t(B38400)
|
||||
case .baud57600:
|
||||
return speed_t(B57600)
|
||||
case .baud115200:
|
||||
return speed_t(B115200)
|
||||
case .baud230400:
|
||||
return speed_t(B230400)
|
||||
case .baud460800:
|
||||
return speed_t(B460800)
|
||||
case .baud500000:
|
||||
return speed_t(B500000)
|
||||
case .baud576000:
|
||||
return speed_t(B576000)
|
||||
case .baud921600:
|
||||
return speed_t(B921600)
|
||||
case .baud1000000:
|
||||
return speed_t(B1000000)
|
||||
case .baud1152000:
|
||||
return speed_t(B1152000)
|
||||
case .baud1500000:
|
||||
return speed_t(B1500000)
|
||||
case .baud2000000:
|
||||
return speed_t(B2000000)
|
||||
case .baud2500000:
|
||||
return speed_t(B2500000)
|
||||
case .baud3500000:
|
||||
return speed_t(B3500000)
|
||||
case .baud4000000:
|
||||
return speed_t(B4000000)
|
||||
}
|
||||
}
|
||||
}
|
||||
#elseif os(OSX)
|
||||
public enum BaudRate {
|
||||
case baud0
|
||||
case baud50
|
||||
case baud75
|
||||
case baud110
|
||||
case baud134
|
||||
case baud150
|
||||
case baud200
|
||||
case baud300
|
||||
case baud600
|
||||
case baud1200
|
||||
case baud1800
|
||||
case baud2400
|
||||
case baud4800
|
||||
case baud9600
|
||||
case baud19200
|
||||
case baud38400
|
||||
case baud57600
|
||||
case baud115200
|
||||
case baud230400
|
||||
|
||||
var speedValue: speed_t {
|
||||
switch self {
|
||||
case .baud0:
|
||||
return speed_t(B0)
|
||||
case .baud50:
|
||||
return speed_t(B50)
|
||||
case .baud75:
|
||||
return speed_t(B75)
|
||||
case .baud110:
|
||||
return speed_t(B110)
|
||||
case .baud134:
|
||||
return speed_t(B134)
|
||||
case .baud150:
|
||||
return speed_t(B150)
|
||||
case .baud200:
|
||||
return speed_t(B200)
|
||||
case .baud300:
|
||||
return speed_t(B300)
|
||||
case .baud600:
|
||||
return speed_t(B600)
|
||||
case .baud1200:
|
||||
return speed_t(B1200)
|
||||
case .baud1800:
|
||||
return speed_t(B1800)
|
||||
case .baud2400:
|
||||
return speed_t(B2400)
|
||||
case .baud4800:
|
||||
return speed_t(B4800)
|
||||
case .baud9600:
|
||||
return speed_t(B9600)
|
||||
case .baud19200:
|
||||
return speed_t(B19200)
|
||||
case .baud38400:
|
||||
return speed_t(B38400)
|
||||
case .baud57600:
|
||||
return speed_t(B57600)
|
||||
case .baud115200:
|
||||
return speed_t(B115200)
|
||||
case .baud230400:
|
||||
return speed_t(B230400)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
public enum DataBitsSize {
|
||||
case bits5
|
||||
case bits6
|
||||
case bits7
|
||||
case bits8
|
||||
|
||||
var flagValue: tcflag_t {
|
||||
switch self {
|
||||
case .bits5:
|
||||
return tcflag_t(CS5)
|
||||
case .bits6:
|
||||
return tcflag_t(CS6)
|
||||
case .bits7:
|
||||
return tcflag_t(CS7)
|
||||
case .bits8:
|
||||
return tcflag_t(CS8)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public enum ParityType {
|
||||
case none
|
||||
case even
|
||||
case odd
|
||||
|
||||
var parityValue: tcflag_t {
|
||||
switch self {
|
||||
case .none:
|
||||
return 0
|
||||
case .even:
|
||||
return tcflag_t(PARENB)
|
||||
case .odd:
|
||||
return tcflag_t(PARENB | PARODD)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum PortError: Int32, Error {
|
||||
case failedToOpen = -1 // refer to open()
|
||||
case invalidPath
|
||||
case mustReceiveOrTransmit
|
||||
case mustBeOpen
|
||||
case stringsMustBeUTF8
|
||||
}
|
||||
|
||||
public class SerialPort {
|
||||
|
||||
var path: String
|
||||
var fileDescriptor: Int32?
|
||||
|
||||
public init(path: String) {
|
||||
self.path = path
|
||||
}
|
||||
|
||||
public func openPort() throws {
|
||||
try openPort(toReceive: true, andTransmit: true)
|
||||
}
|
||||
|
||||
public func openPort(toReceive receive: Bool, andTransmit transmit: Bool) throws {
|
||||
guard !path.isEmpty else {
|
||||
throw PortError.invalidPath
|
||||
}
|
||||
|
||||
guard receive || transmit else {
|
||||
throw PortError.mustReceiveOrTransmit
|
||||
}
|
||||
|
||||
var readWriteParam : Int32
|
||||
|
||||
if receive && transmit {
|
||||
readWriteParam = O_RDWR
|
||||
} else if receive {
|
||||
readWriteParam = O_RDONLY
|
||||
} else if transmit {
|
||||
readWriteParam = O_WRONLY
|
||||
} else {
|
||||
fatalError()
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
fileDescriptor = open(path, readWriteParam | O_NOCTTY)
|
||||
#elseif os(OSX)
|
||||
fileDescriptor = open(path, readWriteParam | O_NOCTTY | O_EXLOCK)
|
||||
#endif
|
||||
|
||||
// Throw error if open() failed
|
||||
if fileDescriptor == PortError.failedToOpen.rawValue {
|
||||
throw PortError.failedToOpen
|
||||
}
|
||||
}
|
||||
|
||||
public func setSettings(receiveRate: BaudRate,
|
||||
transmitRate: BaudRate,
|
||||
minimumBytesToRead: Int,
|
||||
timeout: Int = 0, /* 0 means wait indefinitely */
|
||||
parityType: ParityType = .none,
|
||||
sendTwoStopBits: Bool = false, /* 1 stop bit is the default */
|
||||
dataBitsSize: DataBitsSize = .bits8,
|
||||
useHardwareFlowControl: Bool = false,
|
||||
useSoftwareFlowControl: Bool = false,
|
||||
processOutput: Bool = false) {
|
||||
|
||||
guard let fileDescriptor = fileDescriptor else {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// Set up the control structure
|
||||
var settings = termios()
|
||||
|
||||
// Get options structure for the port
|
||||
tcgetattr(fileDescriptor, &settings)
|
||||
|
||||
// Set baud rates
|
||||
cfsetispeed(&settings, receiveRate.speedValue)
|
||||
cfsetospeed(&settings, transmitRate.speedValue)
|
||||
|
||||
// Enable parity (even/odd) if needed
|
||||
settings.c_cflag |= parityType.parityValue
|
||||
|
||||
// Set stop bit flag
|
||||
if sendTwoStopBits {
|
||||
settings.c_cflag |= tcflag_t(CSTOPB)
|
||||
} else {
|
||||
settings.c_cflag &= ~tcflag_t(CSTOPB)
|
||||
}
|
||||
|
||||
// Set data bits size flag
|
||||
settings.c_cflag &= ~tcflag_t(CSIZE)
|
||||
settings.c_cflag |= dataBitsSize.flagValue
|
||||
|
||||
// Set hardware flow control flag
|
||||
#if os(Linux)
|
||||
if useHardwareFlowControl {
|
||||
settings.c_cflag |= tcflag_t(CRTSCTS)
|
||||
} else {
|
||||
settings.c_cflag &= ~tcflag_t(CRTSCTS)
|
||||
}
|
||||
#elseif os(OSX)
|
||||
if useHardwareFlowControl {
|
||||
settings.c_cflag |= tcflag_t(CRTS_IFLOW)
|
||||
settings.c_cflag |= tcflag_t(CCTS_OFLOW)
|
||||
} else {
|
||||
settings.c_cflag &= ~tcflag_t(CRTS_IFLOW)
|
||||
settings.c_cflag &= ~tcflag_t(CCTS_OFLOW)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Set software flow control flags
|
||||
let softwareFlowControlFlags = tcflag_t(IXON | IXOFF | IXANY)
|
||||
if useSoftwareFlowControl {
|
||||
settings.c_iflag |= softwareFlowControlFlags
|
||||
} else {
|
||||
settings.c_iflag &= ~softwareFlowControlFlags
|
||||
}
|
||||
|
||||
// Turn on the receiver of the serial port, and ignore modem control lines
|
||||
settings.c_cflag |= tcflag_t(CREAD | CLOCAL)
|
||||
|
||||
// Turn off canonical mode
|
||||
settings.c_lflag &= ~tcflag_t(ICANON | ECHO | ECHOE | ISIG)
|
||||
|
||||
// Set output processing flag
|
||||
if processOutput {
|
||||
settings.c_oflag |= tcflag_t(OPOST)
|
||||
} else {
|
||||
settings.c_oflag &= ~tcflag_t(OPOST)
|
||||
}
|
||||
|
||||
//Special characters
|
||||
//We do this as c_cc is a C-fixed array which is imported as a tuple in Swift.
|
||||
//To avoid hardcoding the VMIN or VTIME value to access the tuple value, we use the typealias instead
|
||||
#if os(Linux)
|
||||
typealias specialCharactersTuple = (VINTR: cc_t, VQUIT: cc_t, VERASE: cc_t, VKILL: cc_t, VEOF: cc_t, VTIME: cc_t, VMIN: cc_t, VSWTC: cc_t, VSTART: cc_t, VSTOP: cc_t, VSUSP: cc_t, VEOL: cc_t, VREPRINT: cc_t, VDISCARD: cc_t, VWERASE: cc_t, VLNEXT: cc_t, VEOL2: cc_t, spare1: cc_t, spare2: cc_t, spare3: cc_t, spare4: cc_t, spare5: cc_t, spare6: cc_t, spare7: cc_t, spare8: cc_t, spare9: cc_t, spare10: cc_t, spare11: cc_t, spare12: cc_t, spare13: cc_t, spare14: cc_t, spare15: cc_t)
|
||||
var specialCharacters: specialCharactersTuple = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) // NCCS = 32
|
||||
#elseif os(OSX)
|
||||
typealias specialCharactersTuple = (VEOF: cc_t, VEOL: cc_t, VEOL2: cc_t, VERASE: cc_t, VWERASE: cc_t, VKILL: cc_t, VREPRINT: cc_t, spare1: cc_t, VINTR: cc_t, VQUIT: cc_t, VSUSP: cc_t, VDSUSP: cc_t, VSTART: cc_t, VSTOP: cc_t, VLNEXT: cc_t, VDISCARD: cc_t, VMIN: cc_t, VTIME: cc_t, VSTATUS: cc_t, spare: cc_t)
|
||||
var specialCharacters: specialCharactersTuple = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) // NCCS = 20
|
||||
#endif
|
||||
|
||||
specialCharacters.VMIN = cc_t(minimumBytesToRead)
|
||||
specialCharacters.VTIME = cc_t(timeout)
|
||||
settings.c_cc = specialCharacters
|
||||
|
||||
// Commit settings
|
||||
tcsetattr(fileDescriptor, TCSANOW, &settings)
|
||||
}
|
||||
|
||||
public func closePort() {
|
||||
if let fileDescriptor = fileDescriptor {
|
||||
close(fileDescriptor)
|
||||
}
|
||||
fileDescriptor = nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Receiving
|
||||
|
||||
extension SerialPort {
|
||||
|
||||
public func readBytes(into buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int {
|
||||
guard let fileDescriptor = fileDescriptor else {
|
||||
throw PortError.mustBeOpen
|
||||
}
|
||||
|
||||
let bytesRead = read(fileDescriptor, buffer, size)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
public func readData(ofLength length: Int) throws -> Data {
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
|
||||
defer {
|
||||
buffer.deallocate(capacity: length)
|
||||
}
|
||||
|
||||
let bytesRead = try readBytes(into: buffer, size: length)
|
||||
|
||||
var data : Data
|
||||
|
||||
if bytesRead > 0 {
|
||||
data = Data(bytes: buffer, count: bytesRead)
|
||||
} else {
|
||||
//This is to avoid the case where bytesRead can be negative causing problems allocating the Data buffer
|
||||
data = Data(bytes: buffer, count: 0)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
public func readString(ofLength length: Int) throws -> String {
|
||||
var remainingBytesToRead = length
|
||||
var result = ""
|
||||
|
||||
while remainingBytesToRead > 0 {
|
||||
let data = try readData(ofLength: remainingBytesToRead)
|
||||
|
||||
if let string = String(data: data, encoding: String.Encoding.utf8) {
|
||||
result += string
|
||||
remainingBytesToRead -= data.count
|
||||
} else {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
public func readUntilChar(_ terminator: CChar) throws -> String {
|
||||
var data = Data()
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
|
||||
defer {
|
||||
buffer.deallocate(capacity: 1)
|
||||
}
|
||||
|
||||
while true {
|
||||
let bytesRead = try readBytes(into: buffer, size: 1)
|
||||
|
||||
if bytesRead > 0 {
|
||||
let character = CChar(buffer[0])
|
||||
|
||||
if character == terminator {
|
||||
break
|
||||
} else {
|
||||
data.append(buffer, count: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let string = String(data: data, encoding: String.Encoding.utf8) {
|
||||
return string
|
||||
} else {
|
||||
throw PortError.stringsMustBeUTF8
|
||||
}
|
||||
}
|
||||
|
||||
public func readLine() throws -> String {
|
||||
let newlineChar = CChar(10) // Newline/Line feed character `\n` is 10
|
||||
return try readUntilChar(newlineChar)
|
||||
}
|
||||
|
||||
public func readByte() throws -> UInt8 {
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
|
||||
|
||||
defer {
|
||||
buffer.deallocate(capacity: 1)
|
||||
}
|
||||
|
||||
while true {
|
||||
let bytesRead = try readBytes(into: buffer, size: 1)
|
||||
|
||||
if bytesRead > 0 {
|
||||
return buffer[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func readChar() throws -> UnicodeScalar {
|
||||
let byteRead = try readByte()
|
||||
let character = UnicodeScalar(byteRead)
|
||||
return character
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: Transmitting
|
||||
|
||||
extension SerialPort {
|
||||
|
||||
public func writeBytes(from buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int {
|
||||
guard let fileDescriptor = fileDescriptor else {
|
||||
throw PortError.mustBeOpen
|
||||
}
|
||||
|
||||
let bytesWritten = write(fileDescriptor, buffer, size)
|
||||
return bytesWritten
|
||||
}
|
||||
|
||||
public func writeData(_ data: Data) throws -> Int {
|
||||
let size = data.count
|
||||
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
|
||||
defer {
|
||||
buffer.deallocate(capacity: size)
|
||||
}
|
||||
|
||||
data.copyBytes(to: buffer, count: size)
|
||||
|
||||
let bytesWritten = try writeBytes(from: buffer, size: size)
|
||||
return bytesWritten
|
||||
}
|
||||
|
||||
public func writeString(_ string: String) throws -> Int {
|
||||
guard let data = string.data(using: String.Encoding.utf8) else {
|
||||
throw PortError.stringsMustBeUTF8
|
||||
}
|
||||
|
||||
return try writeData(data)
|
||||
}
|
||||
|
||||
public func writeChar(_ character: UnicodeScalar) throws -> Int{
|
||||
let stringEquiv = String(character)
|
||||
let bytesWritten = try writeString(stringEquiv)
|
||||
return bytesWritten
|
||||
}
|
||||
}
|
||||
|
||||
BIN
first-slide.png
Normal file
BIN
first-slide.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 311 KiB |
BIN
swift-serial-talk-slides.pptx
Normal file
BIN
swift-serial-talk-slides.pptx
Normal file
Binary file not shown.
Reference in New Issue
Block a user