lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Russell Haley once stated:
> Hi,
> 
> I am writing a little Lua program to parse binary data received via serial
> communications. I'm wondering if someone on the mailing list has a novel
> approach to parsing the data? The communications protocol is something like
> this:
> 
> <HEADER> - 4 bytes
> <MSG_TYPE> - 1 byte
> <SEQUENCE> - 2 bytes
> <PAYLOAD_LENGTH> - 2 bytes
> <PAYLOAD> - X bytes (variable based on message type)
> <CHECKSUM> - 4 bytes
> 
> I see two options for parsing messages received via serial:
> 1) Process each character.  Lots of examples here:
> https://stackoverflow.com/questions/829063/how-to-iterate-individual-characters-in-lua-string.
> Once the header is found, just count until I find the payload length (+
> checksum) and then count that number of characters
> 2) Using pattern matching and captures to search for the <HEADER> + 5
> bytes. Then parse out the payload length (+ checksum) and take that many
> characters. This seems potentially very fast, but creates a great deal of
> complexity if I don't get the entire message in one serial port read.
> Something like this (where 'ABCD' represents the header):
>    local m = input:match('ABCD(.+5)')
>    if m then
>    local typ, seq, pl_len = string.unpack('>B>H>H',m)
>    local msg_len =
>    if pl_len > 0 then
>        ...
>    end
> 
> Does anyone have a suggestion for parsing the data or even an existing
> project? Any and all input is welcome.

  How about:

	data = serial:read(9)
	header,type,seq,len = string.unpack(">I4 I1 I2 I2")
	data = serial:read(len)
	crc  = string.unpack(">I4",serial:read(4))

  Seems straightforward to me

  -spc (Just add some error checking ... )