24 Commits

Author SHA1 Message Date
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
9 changed files with 597 additions and 526 deletions

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 import PackageDescription
let package = Package( let package = Package(
name: "SwiftSerialExample", name: "SwiftSerialExample",
dependencies: [ dependencies: [
.Package(url: "https://github.com/yeokm1/SwiftSerial.git", majorVersion: 0) .package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.1")
],
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

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

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 import PackageDescription
let package = Package( let package = Package(
name: "SwiftSerialIM", name: "SwiftSerialIM",
dependencies: [ dependencies: [
.Package(url: "https://github.com/yeokm1/SwiftSerial.git", majorVersion: 0) .package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.1")
],
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

@@ -113,7 +113,7 @@ do {
while true { while true {
var enteredKey = getKeyPress() let enteredKey = getKeyPress()
printToScreenFrom(myself: true, characterToPrint: enteredKey) printToScreenFrom(myself: true, characterToPrint: enteredKey)
var _ = try serialPort.writeChar(enteredKey) var _ = try serialPort.writeChar(enteredKey)
} }

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 import PackageDescription
let package = Package( let package = Package(
name: "SwiftSerial" name: "SwiftSerial",
products: [
.library(name: "SwiftSerial", targets: ["SwiftSerial"]),
],
dependencies: [],
targets: [
.target(
name: "SwiftSerial",
dependencies: [],
path: "Sources"
),
]
) )

View File

@@ -1,5 +1,5 @@
# SwiftSerial # 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). 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).
@@ -9,10 +9,23 @@ 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://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> <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 ## Mac OS Preparation
You should have Xcode 8 installed with the command line tools. 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 ## 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).
@@ -104,7 +117,7 @@ Add SwiftSerial as a dependency to your project by editing the `Package.swift` f
let package = Package( let package = Package(
name: "NameOfMyProject", name: "NameOfMyProject",
dependencies: [ dependencies: [
.Package(url: "https://github.com/yeokm1/SwiftSerial.git", majorVersion: 0), .package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.1"),
... ...
] ]
... ...
@@ -188,10 +201,15 @@ func readUntilChar(_ terminator: CChar) throws -> String
``` ```
Keep reading until the specified CChar is encountered. Return the string read so far without that value. 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 ```swift
func readChar() throws -> UnicodeScalar 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 ### Writing data to the port

View File

@@ -209,6 +209,8 @@ public enum PortError: Int32, Error {
case mustReceiveOrTransmit case mustReceiveOrTransmit
case mustBeOpen case mustBeOpen
case stringsMustBeUTF8 case stringsMustBeUTF8
case unableToConvertByteToCharacter
case deviceNotConnected
} }
public class SerialPort { public class SerialPort {
@@ -371,6 +373,12 @@ extension SerialPort {
throw PortError.mustBeOpen throw PortError.mustBeOpen
} }
var s: stat = stat()
fstat(fileDescriptor, &s)
if s.st_nlink != 1 {
throw PortError.deviceNotConnected
}
let bytesRead = read(fileDescriptor, buffer, size) let bytesRead = read(fileDescriptor, buffer, size)
return bytesRead return bytesRead
} }
@@ -378,7 +386,7 @@ extension SerialPort {
public func readData(ofLength length: Int) throws -> Data { public func readData(ofLength length: Int) throws -> Data {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: length) let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: length)
defer { defer {
buffer.deallocate(capacity: length) buffer.deallocate()
} }
let bytesRead = try readBytes(into: buffer, size: length) let bytesRead = try readBytes(into: buffer, size: length)
@@ -417,13 +425,16 @@ extension SerialPort {
var data = Data() var data = Data()
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1) let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
defer { defer {
buffer.deallocate(capacity: 1) buffer.deallocate()
} }
while true { while true {
let bytesRead = try readBytes(into: buffer, size: 1) let bytesRead = try readBytes(into: buffer, size: 1)
if bytesRead > 0 { if bytesRead > 0 {
if ( buffer[0] > 127) {
throw PortError.unableToConvertByteToCharacter
}
let character = CChar(buffer[0]) let character = CChar(buffer[0])
if character == terminator { if character == terminator {
@@ -446,22 +457,26 @@ extension SerialPort {
return try readUntilChar(newlineChar) return try readUntilChar(newlineChar)
} }
public func readChar() throws -> UnicodeScalar { public func readByte() throws -> UInt8 {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1) let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
defer { defer {
buffer.deallocate(capacity: 1) buffer.deallocate()
} }
while true { while true {
let bytesRead = try readBytes(into: buffer, size: 1) let bytesRead = try readBytes(into: buffer, size: 1)
if bytesRead > 0 { if bytesRead > 0 {
let character = UnicodeScalar(buffer[0]) return buffer[0]
return character }
} }
} }
public func readChar() throws -> UnicodeScalar {
let byteRead = try readByte()
let character = UnicodeScalar(byteRead)
return character
} }
} }
@@ -483,7 +498,7 @@ extension SerialPort {
let size = data.count let size = data.count
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size) let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size)
defer { defer {
buffer.deallocate(capacity: size) buffer.deallocate()
} }
data.copyBytes(to: buffer, count: size) data.copyBytes(to: buffer, count: size)

BIN
first-slide.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 KiB

Binary file not shown.