1
0

main.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 or /dev/cu.usbserial 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. print("Port Closed")
  21. }
  22. serialPort.setSettings(receiveRate: .baud9600,
  23. transmitRate: .baud9600,
  24. minimumBytesToRead: 1)
  25. print("Writing test string <\(testString)> of \(testString.count) characters to serial port")
  26. let bytesWritten = try serialPort.writeString(testString)
  27. print("Successfully wrote \(bytesWritten) bytes")
  28. print("Waiting to receive what was written...")
  29. let stringReceived = try serialPort.readString(ofLength: bytesWritten)
  30. if testString == stringReceived {
  31. print("Received string is the same as transmitted string. Test successful!")
  32. } else {
  33. print("Uh oh! Received string is not the same as what was transmitted. This was what we received,")
  34. print("<\(stringReceived)>")
  35. }
  36. print("Now testing reading/writing of \(numberOfMultiNewLineTest) lines")
  37. var multiLineString: String = ""
  38. for _ in 1...numberOfMultiNewLineTest {
  39. multiLineString += testString + "\n"
  40. }
  41. print("Now writing multiLineString")
  42. var _ = try serialPort.writeString(multiLineString)
  43. for i in 1...numberOfMultiNewLineTest {
  44. let stringReceived = try serialPort.readLine()
  45. if testString == stringReceived {
  46. print("Received string \(i) is the same as transmitted section. Moving on...")
  47. } else {
  48. print("Uh oh! Received string \(i) is not the same as what was transmitted. This was what we received,")
  49. print("<\(stringReceived)>")
  50. break
  51. }
  52. }
  53. print("End of example");
  54. } catch PortError.failedToOpen {
  55. print("Serial port \(portName) failed to open. You might need root permissions.")
  56. } catch {
  57. print("Error: \(error)")
  58. }