I found this in unicast example of contiki written using C.
#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);
}
Here are some regarding details
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);
methods
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 methods http://dak664.github.com/contiki-doxygen/a01563.html#_details
Can anyone explain me these packetbuf_clear(); header = (msg_header_t *)(packetbuf_dataptr()); data = (uint8_t *)(header + 1); random_data(data, MSG_LEN);
From what I can understand:
packetbuf_dataptr()
allocates enough memory to hold a packet header, data length and it's payload.
header = (msg_header_t *)(packetbuf_dataptr());
sets the pointer to the header to the beginning of that memory array.
data = (uint8_t *)(header + 1);
sets the beginning of the data "payload" to the first memory address after the header header + 1
which means as much as <address of header> + sizeof(msg_header_t)
random_data(data, MSG_LEN);
puts some random data of MSG_LEN
bytes into the payload.
hton_uint16(&header->data_len, MSG_LEN);
writes the length of the data segment in network byte order into the packet header data_len
field.
packetbuf_set_datalen(sizeof(msg_header_t) + MSG_LEN);
sends the header off together with it's payload.