def buildMessage(msgtype,token,code,messageId,options=[],payload=[]):
    assert msgtype in d.TYPE_ALL
    assert code in d.METHOD_ALL+d.COAP_RC_ALL
    
    message   = []
    
    # determine token length
    TKL = None
    for tokenLen in range(1,8+1):
        if token < (1<<(8*tokenLen)):
            TKL = tokenLen
            break
    if not TKL:
        raise ValueError('token {0} too long'.format(token))
    
    # header
    message += [d.COAP_VERSION<<6 | msgtype<<4 | TKL]
    message += [code]
    message += u.int2buf(messageId,2)
    message += u.int2buf(token,TKL)
    
    # options
    options  = sortOptions(options)
    lastOptionNum = 0
    for option in options:
        assert option.optionNumber>=lastOptionNum
        message += option.toBytes(lastOptionNum)
        lastOptionNum = option.optionNumber
    
    # payload
    if payload:
        message += [d.COAP_PAYLOAD_MARKER]
        message += payload
    
    return message
dataset/ETHPy150Open openwsn-berkeley/coap/coap/coapMessage.py/buildMessage/original