Skip to content

Guest Post: Serial Communications with Xojo

Wayne Golding has been a Xojo developer since 2005. He operates an IT Company Axis Direct Ltd which primarily develops applications using Xojo that integrate with Xero  Wayne’s hobby is robotics where he uses Xojo to build applications for his Pi2 often implementing IoT for remote control.

When receiving data from remote sources there are two options available, one option is where the source will send a packet size followed by the data, the other is where the packet is terminated. Today we’re going to look at the terminated version.

Termination means there will be some kind of end of transmission byte(s). These can be end of file ChrB(26) or various end of line sequences CRLF, CR, LF, LFCR depending on the OS & remote device.

Xojo being event driven requires developers to manage the process and this is my implementation of the data available event.

Sub DataAvailable()
  Dim PacketSize As Integer

  Dim Terminator As String = ChrB(26) // This is the data terminator, in this case it is an EndOfFile, but could be multiple byte like CRLF (#0D0A)

  PacketSize = InStrB(0, me.Lookahead, Terminator) - 1 // Check the buffer for at least one full packet. Instr returns the position of the first byte of the Terminator, so we subtract 1 to get the actual packet size

  If PacketSize < 0 Then // Wait for at least one full packet
    Return // Exit this routine
  End If
    Dim DataPacket As String = me.Read(PacketSize) // Read the data packet without the terminator
    Call me.Read(LenB(Terminator)) // Remove the terminator from the buffer
    // Deal with the Data (DataPacket)
    PacketSize = InStrB(0, me.Lookahead, Terminator) -1 // Recheck the buffer for a full packet
  Loop Until PacketSize < 0
End Sub

The key to this is the termination sequence of bytes in this case I’m using a single byte <CTRL> + Z or ChrB(26) which is the old style end of file marker. In the first instance, I check to see if there is at least one full packet and if not exit and wait for another dataavailable event. If there is a full packet, I read it in from the buffer and discard the terminator. After processing the packet, I check to see if there’s another full packet in the buffer and loop through again.

Changing the terminator byte(s) will allow this system to work with any serial communication that is data terminated.