adjust code to read until new character is encountered. Example code now tests for this.
This commit is contained in:
@@ -5,6 +5,10 @@ print("You should do a loopback i.e short the TX and RX pins of the target seria
|
||||
|
||||
let testString: String = "The quick brown fox jumps over the lazy dog 01234567890."
|
||||
|
||||
let numberOfMultiNewLineTest : Int = 5
|
||||
|
||||
let test3Strings: String = testString + "\n" + testString + "\n" + testString + "\n"
|
||||
|
||||
let arguments = CommandLine.arguments
|
||||
guard arguments.count >= 2 else {
|
||||
print("Need serial port name, e.g. /dev/ttyUSB0 as the first argument.")
|
||||
@@ -15,6 +19,8 @@ let portName = arguments[1]
|
||||
let serialPort: SerialPort = SerialPort(path: portName)
|
||||
|
||||
do {
|
||||
|
||||
print("Attempting to open port: \(portName)")
|
||||
try serialPort.openPort()
|
||||
print("Serial port \(portName) opened successfully.")
|
||||
defer {
|
||||
@@ -41,6 +47,36 @@ do {
|
||||
print("<\(stringReceived)>")
|
||||
}
|
||||
|
||||
|
||||
print("Now testing reading/writing of \(numberOfMultiNewLineTest) lines")
|
||||
|
||||
var multiLineString: String = ""
|
||||
|
||||
|
||||
for i in 1...numberOfMultiNewLineTest {
|
||||
multiLineString += testString + "\n"
|
||||
}
|
||||
|
||||
print("Now writing multiLineString")
|
||||
|
||||
var _ = try serialPort.writeString(multiLineString)
|
||||
|
||||
|
||||
for i in 1...numberOfMultiNewLineTest {
|
||||
let stringReceived = try serialPort.readLine()
|
||||
|
||||
if testString == stringReceived {
|
||||
print("Received string \(i) is the same as transmitted section. Moving on...")
|
||||
} else {
|
||||
print("Uh oh! Received string \(i) is not the same as what was transmitted. This was what we received,")
|
||||
print("<\(stringReceived)>")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
print("We successfully received back \(numberOfMultiNewLineTest) lines")
|
||||
|
||||
} catch PortError.failedToOpen {
|
||||
print("Serial port \(portName) failed to open. You might need root permissions.")
|
||||
} catch {
|
||||
|
||||
@@ -420,13 +420,17 @@ extension SerialPort {
|
||||
buffer.deallocate(capacity: 1)
|
||||
}
|
||||
|
||||
// Read byte by byte
|
||||
while try readBytes(into: buffer, size: 1) > 0 {
|
||||
while true {
|
||||
let bytesRead = try readBytes(into: buffer, size: 1)
|
||||
|
||||
if bytesRead > 0 {
|
||||
let character = CChar(buffer[0])
|
||||
if character != terminator {
|
||||
data.append(buffer, count: 1)
|
||||
} else {
|
||||
|
||||
if character == terminator {
|
||||
break
|
||||
} else {
|
||||
data.append(buffer, count: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user