Saturday, September 29, 2012

Unicast example in Contiki

Simple unicast example, Click button in each node to unicast message.

Please consider that this code is written for cooja simulator.

UniA.c for node 1
#include "contiki.h"
#include "net/rime.h"
#include "dev/button-sensor.h"
#include "dev/leds.h"
#include <stdio.h>

PROCESS(example_unicast_process, "Example unicast");
AUTOSTART_PROCESSES(&example_unicast_process);

static void
recv_uc(struct unicast_conn *c, const rimeaddr_t *from)
{
  printf("broadcast message received from %d.%d: '%s'\n",from->u8[0], from->u8[1], (char *)packetbuf_dataptr());
}

static const struct unicast_callbacks unicast_callbacks = {recv_uc};

static struct unicast_conn uc;

static void unicast_message()
{
    unicast_open(&uc, 146, &unicast_callbacks);

    rimeaddr_t addr;
    
    packetbuf_copyfrom("AAAAA", 5);
    addr.u8[0] = 2;
    addr.u8[1] = 0;
    if(!rimeaddr_cmp(&addr, &rimeaddr_node_addr))
    {
      unicast_send(&uc, &addr);
    }
}

PROCESS_THREAD(example_unicast_process, ev, data)
{
  PROCESS_EXITHANDLER(unicast_close(&uc);)
    
  PROCESS_BEGIN();
  
  while(1) {
    PROCESS_WAIT_EVENT_UNTIL(ev == sensors_event && data == &button_sensor);
    unicast_message();
    printf("message sent.\n");
  }  
    
  PROCESS_END();
}

UniB.c for node2
#include "contiki.h"
#include "net/rime.h"
#include "dev/button-sensor.h"
#include "dev/leds.h"
#include <stdio.h>

PROCESS(example_unicast_process, "Example unicast");
AUTOSTART_PROCESSES(&example_unicast_process);

static void
recv_uc(struct unicast_conn *c, const rimeaddr_t *from)
{
  printf("broadcast message received from %d.%d: '%s'\n",from->u8[0], from->u8[1], (char *)packetbuf_dataptr());
}

static const struct unicast_callbacks unicast_callbacks = {recv_uc};

static struct unicast_conn uc;

static void unicast_message()
{
    unicast_open(&uc, 146, &unicast_callbacks);

    rimeaddr_t addr;
    
    packetbuf_copyfrom("BBBBB", 5);
    addr.u8[0] = 1;
    addr.u8[1] = 0;
    if(!rimeaddr_cmp(&addr, &rimeaddr_node_addr))
    {
      unicast_send(&uc, &addr);
    }
}

PROCESS_THREAD(example_unicast_process, ev, data)
{
  PROCESS_EXITHANDLER(unicast_close(&uc);)
    
  PROCESS_BEGIN();
  
  while(1) {
    PROCESS_WAIT_EVENT_UNTIL(ev == sensors_event && data == &button_sensor);
    unicast_message();
    printf("message sent.\n");
  }  
    
  PROCESS_END();
}

2 comments:

  1. Hai,
    I have doing some basic programs on Contiki, now I would like to set up a star network using the same. What do you recommend or how to go about it.
    Kindly mail me at ssgokusai@gmail.com

    ReplyDelete
  2. Good note. But one question. How do I set the target address?

    ReplyDelete