-1

我在使用 C 编写的 contiki 的单播示例中发现了这一点。

#define MSG_LEN 20
msg_header_t * header;
uint8_t *data;

packetbuf_clear();
header = (msg_header_t *)(packetbuf_dataptr());
data = (uint8_t *)(header + 1);
random_data(data, MSG_LEN);
hton_uint16(&header->data_len, MSG_LEN);

packetbuf_set_datalen(sizeof(msg_header_t) + MSG_LEN);
rimeaddr_t addr;
addr.u8[0] = 2;
addr.u8[1] = 0;
if(!rimeaddr_cmp(&addr, &rimeaddr_node_addr)) {
    unicast_send(&uc, &addr);
}

这里有一些关于细节

typedef struct {
    unsigned char data[2]; 
} nw_uint16_t;

typedef struct msg_header 
{
    NN_DIGIT r[NUMWORDS]; //NN_DIGIT = uint32_t, NUMWORDS = 6
    NN_DIGIT s[NUMWORDS];
    nw_uint16_t data_len; 
} msg_header_t;

inline uint16_t hton_uint16(void * target, uint16_t value);

inline uint16_t ntoh_uint16(void * source);

方法

inline uint16_t  hton_uint16(void * target, uint16_t value) 
{
    uint8_t *base = target;
    base[1] = value;
    base[0] = value >> 8;
    return value;
}
/*---------------------------------------------------------------------------*/
inline uint16_t ntoh_uint16(void * source)
{
    uint8_t *base = source;
    return (uint16_t)(base[0] << 8 | base[1]);
}
/*---------------------------------------------------------------------------*/
static void random_data(void *ptr, uint16_t len)
{
    uint16_t i;
    for(i=0; i<len; i++) {
        srand(100);
        ((uint8_t *)(ptr))[i] = 2; 
    }
}

packetbuf 方法 http://dak664.github.com/contiki-doxygen/a01563.html#_details

谁能解释我这些packetbuf_clear(); header = (msg_header_t *)(packetbuf_dataptr()); data = (uint8_t *)(header + 1); random_data(data, MSG_LEN);

4

1 回答 1

0

据我了解:

packetbuf_dataptr()分配足够的内存来保存数据包头、数据长度和有效负载。

header = (msg_header_t *)(packetbuf_dataptr());将指向标头的指针设置为该内存数组的开头。

data = (uint8_t *)(header + 1);将数据“有效负载”的开头设置为标头之后的第一个内存地址,header + 1这意味着<address of header> + sizeof(msg_header_t)

random_data(data, MSG_LEN);将一些随机的MSG_LEN字节数据放入有效负载中。

hton_uint16(&header->data_len, MSG_LEN);以网络字节顺序将数据段的长度写入数据包头data_len字段。

packetbuf_set_datalen(sizeof(msg_header_t) + MSG_LEN);将标头与其有效负载一起发送出去。

于 2012-09-29T18:01:23.903 回答