Skip to content
This repository has been archived by the owner on Jan 27, 2024. It is now read-only.

Latest commit

 

History

History
223 lines (155 loc) · 10.5 KB

README.md

File metadata and controls

223 lines (155 loc) · 10.5 KB

SwiftSerial

(This repository is now archived as I'm no longer maintaining this. You may consider using a fork of this library by mredig https://github.com/mredig/SwiftSerial)

A Swift Linux and Mac library for reading and writing to serial ports. This library has been tested to work on macOS Mojave, Linux Mint 18 (based on Ubuntu 16.04) and on the Raspberry Pi 3 on Ubuntu 16.04 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 which was less Swifty and supported only Linux. This library is thanks largely to Jay Jun. His original pull request can be found here.

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

Mac OS Preparation

You should have Xcode 8 or above installed with the command line tools.

You may need to enable USB and/or serial entitlement.

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.) Swift 3.0

For Serial entitlement, there is no checkbox for it. So com.apple.security.device.serial needs to be manually added to the "YourApp.entitlements" file in the Xcode project. Thanks to this issue raised by @doHernandezM.

Linux System Preparation

Varies depending on system...

Jumping straight into sample code

To get started quickly, you can take a look at my example projects here.

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.

git clone https://github.com/yeokm1/SwiftSerial.git
cd SwiftSerial/Examples/SwiftSerialExample/
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/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: Binary Loopback Test

Variant of example 1 but testing the transfer of binary data specifically ensuring the0x0D bit is not converted to another character.

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 or 2 USB-Serial adapters with the TX-RX pins connected to each other. Run a copy of my program on both machines.

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.

let package = Package(
    name: "NameOfMyProject",
    dependencies: [
        .package(url: "https://github.com/yeokm1/SwiftSerial.git", from: "0.1.2"),
        ...
    ]
    ...
)

Make sure to import SwiftSerial in the source files that use my API.

Then run swift build to download the dependencies and compile your project. Your executable will be found in the ./.build/debug/ directory.

API usage

Initialise the class

let serialPort: SerialPort = SerialPort(path: portName)

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. If there is a problem, open an issue describing your situation and let me look into it.

Opening the Serial Port

func openPort()
func openPort(toReceive receive: Bool, andTransmit transmit: Bool)

Opening the port without any parameters will set the port to receive and transmit by default. You can still choose to receive-only, transmit-only or both. Will throw PortError.mustReceiveOrTransmit if you set both parameters to false. Can also throw PortError.failedToOpen and PortError.invalidPath.

Set port settings

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.

minimumBytesToRead determines how many characters the system must wait to receive before it will return from a read() function. If in doubt, just put 1.

This function has been defined with default settings as shown in the function definition.

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)

If the default settings do not suit you, just pass in extra parameters to override them.

Reading data from port

There are several functions you can use to read data. All functions here are blocking till the expected number of bytes has been received or a condition has been met. All functions can throw PortError.mustBeOpen.

func readString(ofLength length: Int) throws -> String

This is the easiest to use if you are sending text data. Just provide how many bytes you expect to read. The result will then be returned as a typical Swift String. This function internally calls readData().

func readData(ofLength length: Int) throws -> Data

This function is if you intend to receive binary data. This function internally calls readBytes()

func readBytes(into buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int

If you intend to play with unsafe pointers directly, this is the function for you! Will return the number of bytes read. Note that you are responsible for allocating the pointer before passing into this function then deallocate the pointer once you are done.

func readLine() throws -> String

Read byte by byte till the newline character \n is encountered. A String containing the result so far will be returned without the newline character. This function internally calls readUntilChar(). Can throw PortError.stringsMustBeUTF8.

func readUntilChar(_ terminator: CChar) throws -> String

Keep reading until the specified CChar is encountered. Return the string read so far without that value.

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().

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.

func writeString(_ string: String) throws -> Int

Most straightforward function, String in then transmit! Will return how many bytes actually written. Internally calls writeData()

func writeData(_ data: Data) throws -> Int

Binary data in, then transmit! Will return how many bytes actually written. Internally calls writeBytes().

func writeBytes(from buffer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int

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.

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.

External References

This library cannot be written without the amazing reference code I depended on.

  1. Xanthium's Serial Port Programming on Linux
  2. Chrishey Drick's Reading data from Serial Port