Search code examples
ccontiki

Contiki: print data received using Rime


How can I print the received data in the recv_uc function? In this case is the value of var. I used packetbuf_copyfrom(&var, 5) to put var in the sent packet.

PROCESS(sending_rand, "Sending rand");
AUTOSTART_PROCESSES(&sending_rand);

static void
recv_uc(struct unicast_conn *c, const rimeaddr_t *from)
{
    printf("unicast message received from %d.%d\nreceived data: %d\n",
            from->u8[0], from->u8[1], /* print data received */);
}

static const struct unicast_callbacks unicast_call = {recv_uc};
static struct unicast_conn unicast;

PROCESS_THREAD(sending_rand, ev, data)
{
    static struct etimer et;//oggetto di tipo etimer
    int var;  

    PROCESS_EXITHANDLER(unicast_close(&unicast);)

    PROCESS_BEGIN();

    unicast_open(&unicast, 129, &unicast_call);

    while(1) {

        /* Delay 2-4 seconds */
        etimer_set(&et, CLOCK_SECOND * 4 + random_rand() % (CLOCK_SECOND * 4));

        PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

        var = random_rand();

        packetbuf_copyfrom(&var, 5);
        addr.u8[0] = 1;
        addr.u8[1] = 0;
        if(!rimeaddr_cmp(&addr, &rimeaddr_node_addr)) {
            unicast_send(&unicast, &addr);
        }

        printf("unicast message sent\n");
    }

    PROCESS_END();
}

Solution

  • One way is to use packetbuf_dataptr() function to access the contents.

    int var;
    memcpy(&var, packetbuf_dataptr(), sizeof(var));
    printf("var=%d\n", var);
    

    Your sending code has a bug related to the size of var. It's either 2, 4, or 8 bytes depending on the platform. It's never 5, so this is wrong:

    packetbuf_copyfrom(&var, 5); // Undefined behavior!
    

    Always use int16_t / uint16_t or int32_t / uint32_t if the size matters! They are typedef'd in header that is effectively included in each Contiki file.