Sub ReceiveMessage( tchar As Byte )
' Note: with the TSIP protocol, messages start with DLE-0x8F-0xAB or DLE-Ox8F-0xAC
' we cannot be sure to identify the beginning of a message because these sequences are legal inside a message
' However we can identify the end of a message because it is (odd number of DLE)-ETX
' So we start collecting a message when we get DLE-0x8F, but we have to check for
' early DLE-ETX and scrap the message if length is not good
Select Case RxState
Case WAIT_FOR_START:
If tchar = DLE Then
' this is a tentative start
RxBuf = ""
RxBuf = RxBuf & Chr(tchar)
RxState = WAIT_FOR_ID
bDLE = True ' will be used to identify the end of a message
Else
' do nothing, just keep waiting
bDLE = False
End If
Case WAIT_FOR_ID: ' make sure it's a clean DLE (followed by not-ETX)
' there are many more message IDs than 0x8E and 0x8F...
' even though we can have DLE-0x8F inside a message
If tchar = 0x8E Or tchar = 0x8F Then
' still not 100% sure it's a good start, it just looks like it might
RxState = COLLECT_MSG
RxBuf = RxBuf & Chr(tchar)
Else
' pretty sure that was not a start
RxState = WAIT_FOR_START
RxBuf = ""
bDLE = False
End If
bDLE = False
Case COLLECT_MSG:
If tchar = ETX And bDLE = True Then
' ETX preceded by odd number of DLEs: unequivocaly end of message
' RxPending = True ' not sure RxPending is useful in this context
' Check length versus third character of the message:
' Primary packet is 0xAB and length is 19,
' Secondary packet is 0xAC and length is 70
'Debug.Print "Message type: 0x" & Hex$(Asc(Mid$(RxBuffer, 2, 1))) & Hex$(Asc(Mid$(RxBuffer, 3, 1))) & ", length: " & Len(RxBuffer)
'Debug.Print "Received message"
'ProcessMessage (RxBuf & Chr(tchar))
RxBuf = ""
RxState = WAIT_FOR_START ' get ready for next message
bDLE = False
Else If tchar = DLE And bDLE = False Then
' we just received a DLE
RxBuf = RxBuf & Chr(tchar)
bDLE = True
Else If tchar = DLE And bDLE = True Then
' duplicate DLE, ignore it
bDLE = False
Else
' any other situation, accumulate character
RxBuf = RxBuf & Chr(tchar)
bDLE = False
End If
Case Else:
RxState = WAIT_FOR_START
RxBuf = ""
bDLE = False
' RxPending = False
End Select
End Sub ' ReceiveMessage()