我在使用 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);