39 Commits
0.0.7 ... 0.1.2

Author SHA1 Message Date
Yeo Kheng Meng
0e824cc38c Updated readme to reflect new binary transfer test. 0.1.2 version. 2020-01-26 17:22:21 +08:00
Yeo Kheng Meng
91a7ea35b6 add extra test for binary 2020-01-26 17:17:59 +08:00
Yeo Kheng Meng
46a834e147 Merge pull request #17 from Scanomat/master
Disabled input processing
2020-01-26 17:08:23 +08:00
Michael Rimestad
e37d2df358 Disabled input processing 2020-01-10 14:50:44 +01:00
Yeo Kheng Meng
86625ee414 Merge pull request #14 from nallick/swift-tools-version-5
Update SPM to swift-tools-version:5.0
2019-10-01 09:47:49 +08:00
Nick Nallick
29bbe8505f Update examples to Swift 5 2019-09-30 14:06:53 -06:00
Nick Nallick
005183c282 Update SPM to swift-tools-version:5.0 2019-09-30 13:50:13 -06:00
Yeo Kheng Meng
ddc06f53ef Merge pull request #12 from EmreSURK/master
XCode sandbox mode explained.
2019-05-02 22:16:54 +08:00
Emre ŞURK
1027251723 Merge pull request #1 from EmreSURK/EmreSURK-patch-1
Added XCode Sanbox advise.
2019-05-02 11:35:24 +03:00
Emre ŞURK
6db41b985c Added XCode Sanbox advise. 2019-05-02 11:35:08 +03:00
Yeo Kheng Meng
62d6742987 update readme 2019-04-08 15:29:04 +08:00
Yeo Kheng Meng
66c27258da Merge pull request #8 from 5sw/master
Update for Swift 4/5
2019-04-08 15:26:00 +08:00
Sven Weidauer
10b91eb8a2 Swift 5 2019-04-07 12:23:59 +02:00
Yeo Kheng Meng
581ebc7e10 Merge pull request #7 from DasenB/master
catch type conversion error and prevent infinite loop
2018-09-16 21:52:48 +08:00
bjarnedevel0per
db7a3b79a2 handle removal of the serialdevice 2018-09-11 10:26:36 +02:00
bjarnedevel0per
1b9591e07a catch type conversion error 2018-09-11 08:30:41 +02:00
Yeo Kheng Meng
af1fa134cc Merge pull request #6 from lagomorph/compilefix
Fix compilation error
2018-03-30 13:14:27 +08:00
John Scarfone
812a55a381 make compile 2018-03-21 19:29:05 -04:00
Yeo Kheng Meng
41ddf0247a readme formatting 2017-06-24 17:56:03 +08:00
Yeo Kheng Meng
f3c3a214e3 adjust readbyte documentation 2017-06-24 17:54:36 +08:00
Yeo Kheng Meng
5536368ba7 refactor readchar to use readbyte 2017-06-24 17:40:49 +08:00
Yeo Kheng Meng
e2063420e9 Merge pull request #1 from AleyRobotics/master
read byte feature add
2017-06-24 17:35:26 +08:00
AleyRobotics Aleynikov Yuri
cfaf24357c Merge commit 'f9981b1ceca99f34ee8f38f9efd5306eda19c657'
Conflicts:
	Sources/SwiftSerial.swift
2017-06-24 11:38:25 +03:00
AleyRobotics Aleynikov Yuri
543e7d39e0 read byte feature add 2017-06-24 11:21:58 +03:00
AleyRobotics
f9981b1cec Read byte function add
Read UInt8 from port
2016-12-25 22:13:28 +03:00
Yeo Kheng Meng
d36d0132a8 Update README.md 2016-11-24 23:30:52 +08:00
Yeo Kheng Meng
b29775dfbe Update README.md 2016-11-20 16:08:54 +08:00
Yeo Kheng Meng
8a8dfcb190 slides 2016-11-20 16:00:19 +08:00
Yeo Kheng Meng
25600e48fb add extra newlines when switching roles for SwiftIMExample 2016-10-29 21:52:06 +08:00
Yeo Kheng Meng
7c06c99bd1 add missing return nil in SwiftSerialIM example 2016-10-29 21:46:27 +08:00
Yeo Kheng Meng
ad3142da95 Update README.md 2016-10-29 21:32:58 +08:00
Yeo Kheng Meng
0c14b6d2b9 Update main.swift 2016-10-29 21:24:03 +08:00
Yeo Kheng Meng
4522b9261e Update main.swift 2016-10-29 21:23:40 +08:00
Yeo Kheng Meng
144c9bbf5a Update README.md 2016-10-29 21:22:34 +08:00
Yeo Kheng Meng
20cf246eda Update README.md 2016-10-29 21:15:58 +08:00
Yeo Kheng Meng
02e0d4837e remove nonblock flag to prevent massive cpu usage during reading. Will require use of /dev/cu.* only 2016-10-29 21:11:40 +08:00
Yeo Kheng Meng
816720e15c Mac uses gcd to run background thread 2016-10-29 19:01:04 +08:00
Yeo Kheng Meng
c60e0334bd refactor stdin prep 2016-10-29 18:49:24 +08:00
Yeo Kheng Meng
ade0cdc3cd IM example on linux 2016-10-29 18:45:28 +08:00
12 changed files with 854 additions and 569 deletions

View File

@@ -0,0 +1,20 @@
// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftSerialBinary",
dependencies: [
.package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.2")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftSerialBinary",
dependencies: ["SwiftSerial"],
path: "Sources"
),
]
)

View File

@@ -0,0 +1,60 @@
import Foundation
import SwiftSerial
print("You should do a loopback i.e short the TX and RX pins of the target serial port before testing.")
let testBinaryArray : [UInt8] = [0x11, 0x22, 0x33, 0x0D, 0x44]
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)
}
let portName = arguments[1]
let serialPort: SerialPort = SerialPort(path: portName)
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)
print("Sending: ", terminator:"")
print(testBinaryArray.map { String($0, radix: 16, uppercase: false) })
let dataToSend: Data = Data(_: testBinaryArray)
let bytesWritten = try serialPort.writeData(dataToSend)
print("Successfully wrote \(bytesWritten) bytes")
print("Waiting to receive what was written...")
let dataReceived = try serialPort.readData(ofLength: bytesWritten)
print("Received: ", terminator:"")
print(dataReceived.map { String($0, radix: 16, uppercase: false) })
if(dataToSend.elementsEqual(dataReceived)){
print("Received data is the same as transmitted data. Test successful!")
} else {
print("Uh oh! Received data is not the same as what was transmitted. This was what we received,")
print(dataReceived.map { String($0, radix: 16, uppercase: false) })
}
print("End of example");
} catch PortError.failedToOpen {
print("Serial port \(portName) failed to open. You might need root permissions.")
} catch {
print("Error: \(error)")
}

View File

@@ -0,0 +1,4 @@
.DS_Store
/.build
/Packages
/*.xcodeproj

View File

@@ -1,8 +1,20 @@
// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftSerialExample",
dependencies: [
.Package(url: "https://github.com/yeokm1/SwiftSerial.git", majorVersion: 0)
]
.package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.2")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftSerialExample",
dependencies: ["SwiftSerial"],
path: "Sources"
),
]
)

View File

@@ -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)
}
@@ -32,9 +32,9 @@ do {
transmitRate: .baud9600,
minimumBytesToRead: 1)
print("Writing test string <\(testString)> of \(testString.characters.count) characters to serial port")
print("Writing test string <\(testString)> of \(testString.count) characters to serial port")
var bytesWritten = try serialPort.writeString(testString)
let bytesWritten = try serialPort.writeString(testString)
print("Successfully wrote \(bytesWritten) bytes")
print("Waiting to receive what was written...")
@@ -54,7 +54,7 @@ do {
var multiLineString: String = ""
for i in 1...numberOfMultiNewLineTest {
for _ in 1...numberOfMultiNewLineTest {
multiLineString += testString + "\n"
}

View File

@@ -0,0 +1,20 @@
// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftSerialIM",
dependencies: [
.package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.2")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftSerialIM",
dependencies: ["SwiftSerial"],
path: "Sources"
),
]
)

View 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 {
let 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)")
}

View File

@@ -1,5 +1,19 @@
// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftSerial"
name: "SwiftSerial",
products: [
.library(name: "SwiftSerial", targets: ["SwiftSerial"]),
],
dependencies: [],
targets: [
.target(
name: "SwiftSerial",
dependencies: [],
path: "Sources"
),
]
)

117
README.md
View File

@@ -1,66 +1,33 @@
# SwiftSerial
A Swift 3 Linux and Mac library for reading and writing to serial ports. This library has been tested to work on macOS Sierra, Linux Mint 18 (based on Ubuntu 16.04) and on the [Raspberry Pi 3 on Ubuntu 16.04](https://wiki.ubuntu.com/ARM/RaspberryPi). Other platforms using Ubuntu like the Beaglebone might work as well.
A Swift Linux and Mac library for reading and writing to serial ports. This library has been tested to work on macOS Mojove, Linux Mint 18 (based on Ubuntu 16.04) and on the [Raspberry Pi 3 on Ubuntu 16.04](https://wiki.ubuntu.com/ARM/RaspberryPi) and Raspberry Pi 4 on Raspian Buster. Other platforms using Ubuntu like the Beaglebone might work as well.
This library is an improvement over my previous now deprecated library [SwiftLinuxSerial](https://github.com/yeokm1/SwiftLinuxSerial) which was less Swifty and supported only Linux. This library is thanks largely to [Jay Jun](https://github.com/jayjun). His original pull request can be found [here](https://github.com/yeokm1/SwiftLinuxSerial/pull/1).
<p>
![macOS](https://img.shields.io/badge/os-macOS-green.svg?style=flat)
<img src="https://img.shields.io/badge/OS-Ubuntu-blue.svg?style=flat" alt="Swift 3.0">
<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.
[![My slides on slideshare](first-slide.png)](http://www.slideshare.net/yeokm1/a-science-project-swift-serial-chat)
[![](http://img.youtube.com/vi/6PWP1eZo53s/0.jpg)](https://www.youtube.com/watch?v=6PWP1eZo53s)
## Mac OS Preparation
You should have Xcode 8 installed with the command line tools.
To develop app with XCode, enable the App Sandbox capability in Xcode, and under Hardware, select USB. (Mac Apps are sandboxed and you need the USB entitlement.)
<img src="https://user-images.githubusercontent.com/5688874/55690960-6ff8fb00-5998-11e9-9df6-7e3ebe50e19a.png" alt="Swift 3.0">
## 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).
Varies depending on system...
### Install Swift 3 on Ubuntu on x86-based machines
Reference instructions obtained from [here](http://dev.iachieved.it/iachievedit/swift-3-0-for-ubuntu-16-04-xenial-xerus/). We will use a Swift binary produced by iachievedit.
```bash
#Add the repository key for iachievedit
wget -qO- http://dev.iachieved.it/iachievedit.gpg.key | sudo apt-key add -
#Add the Xenial repository to sources.list
echo "deb http://iachievedit-repos.s3.amazonaws.com/ xenial main" | sudo tee --append /etc/apt/sources.list
sudo apt-get update
sudo apt-get install swift-3.0
nano ~/.profile
#This command can be added to your bash profile so Swift will be in your PATH after a reboot
export PATH=/opt/swift/swift-3.0/usr/bin:$PATH
```
### Install Swift 3 on Ubuntu on Raspberry Pi 3
Instructions from this section is referenced from this [link](http://dev.iachieved.it/iachievedit/swift-3-0-on-raspberry-pi-2-and-3/).
Since Swift 3 is still rapidly evolving, we should not use the Swift packages provided via the apt package manager if they exist and instead use prebuilt binaries instead. We will also not install Swift 3 to the system-level directories to avoid problems in case we have to update the version.
Go to this [page](http://swift-arm.ddns.net/job/Swift-3.0-Pi3-ARM-Incremental/lastSuccessfulBuild/artifact/) and find what it is the link to the latest Swift compiled `tar.gz` package.
```bash
#Install dependencies
sudo apt-get install libcurl4-openssl-dev libicu-dev clang-3.6
sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100
sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100
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
mkdir swift-3.0
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
@@ -71,11 +38,46 @@ swift build
sudo ./.build/debug/SwiftSerialExample /dev/ttyUSB0
#For Mac: Root is not required
./.build/debug/SwiftSerialExample /dev/tty.usbserial
./.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: Binary Loopback Test
Variant of example 1 but testing the transfer of binary data specifically ensuring the`0x0D` bit is not converted to another character.
```bash
git clone https://github.com/yeokm1/SwiftSerial.git
cd SwiftSerial/Examples/SwiftSerialBinary/
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/SwiftSerialBinary /dev/ttyUSB0
#For Mac: Root is not required
./.build/debug/SwiftSerialBinary /dev/cu.usbserial
#If all goes well you should see a series of messages informing you that data transmitted has been received properly.
```
### Example 3: 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.
@@ -84,7 +86,7 @@ Add SwiftSerial as a dependency to your project by editing the `Package.swift` f
let package = Package(
name: "NameOfMyProject",
dependencies: [
.Package(url: "https://github.com/yeokm1/SwiftSerial.git", majorVersion: 0),
.package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.2"),
...
]
...
@@ -102,7 +104,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
@@ -117,7 +121,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.
@@ -166,10 +170,15 @@ 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 `readBytes()`.
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

File diff suppressed because it is too large Load Diff

BIN
first-slide.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 KiB

Binary file not shown.