Last active
August 29, 2015 14:04
-
-
Save azdle/b2d477ff183b8bbb0aa0 to your computer and use it in GitHub Desktop.
CoAP Message Parsing in Erlang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
coap(<<Version:2, Type:2, TKL: 4, Code:8, MID:16, Token:TKL/bytes, Tail/bytes>>) when Version =:= 1-> | |
{Options, Payload} = coap_parse_options(Tail), | |
{coap, {Type, Code, MID, Token, Options, Payload}}. | |
coap_parse_options(OptionBin) -> | |
coap_parse_options(OptionBin, 0, []). | |
coap_parse_options(<<>>, _LastNum, OptionList) -> | |
{OptionList, <<>>}; | |
coap_parse_options(<<16#FF, Payload/bytes>>, _LastNum, OptionList) -> | |
{OptionList, Payload}; | |
coap_parse_options(<<BaseOptNum:4, BaseOptLen:4, Tail/bytes>>, LastNum, OptionList) -> | |
{Tail1, OptNum} = case BaseOptNum of | |
X when X < 13 -> | |
{Tail, BaseOptNum + LastNum}; | |
X when X =:= 13 -> | |
<<ExtOptNum, NewTail/bytes>> = Tail, | |
{NewTail, ExtOptNum + 13 + LastNum}; | |
X when X =:= 14 -> | |
<<ExtOptNum:2/bytes, NewTail/bytes>> = Tail, | |
{NewTail, ExtOptNum + 269 + LastNum} | |
end, | |
case BaseOptLen of | |
X when X < 13 -> | |
Tail2 = Tail1, | |
OptLen = BaseOptLen; | |
X when X =:= 13 -> | |
<<ExtOptLen, Tail2/bytes>> = Tail1, | |
OptLen = ExtOptLen + 13; | |
X when X =:= 14 -> | |
<<ExtOptLen:2/bytes, Tail2/bytes>> = Tail1, | |
OptLen = ExtOptLen + 269 | |
end, | |
<<OptVal:OptLen/bytes, NextOpt/bytes>> = Tail2, | |
coap_parse_options([{coap_option, OptNum, OptVal} |OptionList], OptNum, NextOpt). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment