I have a program that will listen to the serial port for a string of binary data. the data has a fixed format but can have variable length like this:
source, length, destination, command, data0, datax, crc
each section is a single byte.
so far I have a basic idea of how to read the serial data, and the pseudo code i've got so far is this:
byte() = buffer contents if byte(0) is valid source src = byte(0) len = byte(1) dest = byte(2) cmd = byte(3) data(len-3) for i = 0 to len - 3 data(i) = byte(4 + i) next crc = byte(len + 2) write all these fields to the visual output. else do something else end if
I currently have this vb.net code
Private Sub SerialPort1_DataReceived1(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'retrieve number of bytes in the buffer
Dim bytes As Integer = SerialPort1.BytesToRead
'create a byte array to hold the awaiting data
If bytes >= 2 Then
Dim comBuffer As Byte() = New Byte(bytes - 1) {}
'read the data and store it
SerialPort1.Read(comBuffer, 0, bytes)
'display the data to the user
_type = MessageType.Incoming
_msg = ByteToHex(comBuffer) + "" + Environment.NewLine + ""
DisplayRawData(txtRX, MessageType.Incoming, ByteToHex(comBuffer) + "" + Environment.NewLine + "")
parseData(DataGridView1, comBuffer)
End If
End Sub
Sub parseData(ByVal grid As DataGridView, ByVal data As Byte())
If DataGridView1.InvokeRequired Then
DataGridView1.Invoke(Sub() parseData(grid, data))
Else
Dim src As Byte
Dim len As Byte
Dim dest As Byte
Dim cmd As Byte
Dim datalen As Integer
Dim crc As Byte
'50 04 68 3B 21 26
'src, len, dest, cmd, d0, crc
Debug.Print(CInt(UBound(data)))
src = data(0)
len = data(1)
datalen = CInt(len)
Debug.Print("Len=" & CInt(len))
dest = data(2)
cmd = data(3)
'datalen = 4
Dim msg As Byte() = New Byte(datalen - 3) {}
For i = 0 To datalen
msg(i) = data(i + 4)
Next
crc = data(8)
'check crc here
dt.Rows.Add(New Object() {Now(), ByteToHex(data), src.ToString("X"), len.ToString("X"), dest.ToString("X"), cmd.ToString("X"), ByteToHex(msg), crc.ToString("X"), "OK"})
DataGridView1.Refresh()
End If
End Sub
So, the question.
Am i going about this the right way? How do i ensure i get the start of the packet and not halfway through?
Any tips please?
Thanks!

New Topic/Question
Reply



MultiQuote





|