1
0

main.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import Foundation
  2. import SwiftSerial
  3. print("You should do a loopback i.e short the TX and RX pins of the target serial port before testing.")
  4. let testString: String = "The quick brown fox jumps over the lazy dog 01234567890."
  5. let numberOfMultiNewLineTest : Int = 5
  6. let test3Strings: String = testString + "\n" + testString + "\n" + testString + "\n"
  7. let arguments = CommandLine.arguments
  8. guard arguments.count >= 2 else {
  9. print("Need serial port name, e.g. /dev/ttyUSB0 as the first argument.")
  10. exit(1)
  11. }
  12. let portName = arguments[1]
  13. let serialPort: SerialPort = SerialPort(path: portName)
  14. do {
  15. print("Attempting to open port: \(portName)")
  16. try serialPort.openPort()
  17. print("Serial port \(portName) opened successfully.")
  18. defer {
  19. serialPort.closePort()
  20. }
  21. serialPort.setSettings(receiveRate: .baud9600,
  22. transmitRate: .baud9600,
  23. minimumBytesToRead: 1)
  24. print("Writing test string <\(testString)> of \(testString.characters.count) characters to serial port")
  25. var bytesWritten = try serialPort.writeString(testString)
  26. print("Successfully wrote \(bytesWritten) bytes")
  27. print("Waiting to receive what was written...")
  28. let stringReceived = try serialPort.readString(ofLength: bytesWritten)
  29. if testString == stringReceived {
  30. print("Received string is the same as transmitted string. Test successful!")
  31. } else {
  32. print("Uh oh! Received string is not the same as what was transmitted. This was what we received,")
  33. print("<\(stringReceived)>")
  34. }
  35. print("Now testing reading/writing of \(numberOfMultiNewLineTest) lines")
  36. var multiLineString: String = ""
  37. for i in 1...numberOfMultiNewLineTest {
  38. multiLineString += testString + "\n"
  39. }
  40. print("Now writing multiLineString")
  41. var _ = try serialPort.writeString(multiLineString)
  42. for i in 1...numberOfMultiNewLineTest {
  43. let stringReceived = try serialPort.readLine()
  44. if testString == stringReceived {
  45. print("Received string \(i) is the same as transmitted section. Moving on...")
  46. } else {
  47. print("Uh oh! Received string \(i) is not the same as what was transmitted. This was what we received,")
  48. print("<\(stringReceived)>")
  49. break
  50. }
  51. }
  52. print("We successfully received back \(numberOfMultiNewLineTest) lines")
  53. } catch PortError.failedToOpen {
  54. print("Serial port \(portName) failed to open. You might need root permissions.")
  55. } catch {
  56. print("Error: \(error)")
  57. }