1
0

main.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 testBinaryArray : [UInt8] = [0x11, 0x22, 0x33, 0x0D, 0x44]
  5. let arguments = CommandLine.arguments
  6. guard arguments.count >= 2 else {
  7. print("Need serial port name, e.g. /dev/ttyUSB0 or /dev/cu.usbserial as the first argument.")
  8. exit(1)
  9. }
  10. let portName = arguments[1]
  11. let serialPort: SerialPort = SerialPort(path: portName)
  12. do {
  13. print("Attempting to open port: \(portName)")
  14. try serialPort.openPort()
  15. print("Serial port \(portName) opened successfully.")
  16. defer {
  17. serialPort.closePort()
  18. print("Port Closed")
  19. }
  20. serialPort.setSettings(receiveRate: .baud9600,
  21. transmitRate: .baud9600,
  22. minimumBytesToRead: 1)
  23. print("Sending: ", terminator:"")
  24. print(testBinaryArray.map { String($0, radix: 16, uppercase: false) })
  25. let dataToSend: Data = Data(_: testBinaryArray)
  26. let bytesWritten = try serialPort.writeData(dataToSend)
  27. print("Successfully wrote \(bytesWritten) bytes")
  28. print("Waiting to receive what was written...")
  29. let dataReceived = try serialPort.readData(ofLength: bytesWritten)
  30. print("Received: ", terminator:"")
  31. print(dataReceived.map { String($0, radix: 16, uppercase: false) })
  32. if(dataToSend.elementsEqual(dataReceived)){
  33. print("Received data is the same as transmitted data. Test successful!")
  34. } else {
  35. print("Uh oh! Received data is not the same as what was transmitted. This was what we received,")
  36. print(dataReceived.map { String($0, radix: 16, uppercase: false) })
  37. }
  38. print("End of example");
  39. } catch PortError.failedToOpen {
  40. print("Serial port \(portName) failed to open. You might need root permissions.")
  41. } catch {
  42. print("Error: \(error)")
  43. }