Skip to content

Instantly share code, notes, and snippets.

@howiemnet
Created August 17, 2015 06:27
Show Gist options
  • Save howiemnet/99bb7349af062ae4fdac to your computer and use it in GitHub Desktop.
Save howiemnet/99bb7349af062ae4fdac to your computer and use it in GitHub Desktop.
Serial port lister for OS X in Swift
//
// GetSerialPortList.swift
// serialTestsIokitSwift
//
// Created by h on 17/08/2015.
// Copyright © 2015 h. All rights reserved.
//
// Simple function returns array of serial port
// paths as Strings
//
import Foundation
import IOKit
import IOKit.serial
func getSerialPortList() -> [String] {
var mySerialPortNameArray = [String]()
var portIterator: io_iterator_t = 0
let kernResult = findSerialDevices(kIOSerialBSDModemType, serialPortIterator: &portIterator)
if kernResult == KERN_SUCCESS {
var serialService: io_object_t
repeat {
serialService = IOIteratorNext(portIterator)
if (serialService != 0) {
let key: CFString! = "IOCalloutDevice"
let bsdPathAsCFtring: AnyObject? = IORegistryEntryCreateCFProperty(serialService, key, kCFAllocatorDefault, 0).takeUnretainedValue()
let bsdPath = String(bsdPathAsCFtring!)
//serialListButton.addItemWithTitle(bsdPath)
mySerialPortNameArray.append(bsdPath)
}
} while serialService != 0
}
return mySerialPortNameArray
}
func findSerialDevices(deviceType: String, inout serialPortIterator: io_iterator_t ) -> kern_return_t {
var result: kern_return_t = KERN_FAILURE
let classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue) //.takeUnretainedValue()
let classesToMatchCFDictRef = classesToMatch as CFDictionaryRef
result = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatchCFDictRef, &serialPortIterator);
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment