Search code examples
contiki

Http client mode with Contiki?


I want to make a webAPI call from a sensor using http, is it possible to do http requests using Contiki OS?

As far as I've searched I found only coap client examples.


Solution

  • Check the examples/http-socket example, it shows how to use CRUD methods such as PUT, GET, etc.

    Here's the link to the example (working with the latest master commit)

    This example relies on IP64, but can be changed to work with IPv6, basically you need to include the http-socket library. Here are the more relevant parts of the example:

    #include "contiki-net.h"
    #include "http-socket.h"
    #include "ip64-addr.h"
    #include <stdio.h>
    
    static struct http_socket s;
    static int bytes_received = 0;
    
    static void
    callback(struct http_socket *s, void *ptr,
             http_socket_event_t e,
             const uint8_t *data, uint16_t datalen)
    {
      if(e == HTTP_SOCKET_ERR) {
        printf("HTTP socket error\n");
      } else if(e == HTTP_SOCKET_DATA) {
        bytes_received += datalen;
        printf("HTTP socket received %d bytes of data\n", datalen);
      }
    }
    
    PROCESS_THREAD(http_example_process, ev, data)
    {
      PROCESS_BEGIN();
    
      /* Initializes the socket */
      http_socket_init(&s);
    
      /* GET request */
      http_socket_get(&s, "http://www.contiki-os.org/", 0, 0,
                      callback, NULL);
    
      /* Waits forever for the HTTP callback */
      while(1) {
        PROCESS_WAIT_EVENT_UNTIL(0);
      }
    
      PROCESS_END();
    }