Coap Client and Server

Dependencies:   DebugLib EthernetInterface cantcoap mbed-rtos

Dependents:   COAP coap

Fork of yeswecancoap by Sille Van Landschoot

YesWeCanCoap

Is a small coap client and server library for mbed based on the cantcoap library.

Import librarycantcoap

This is CoAP library with a focus on simplicity. It offers minimal CoAP PDU construction and decoding to and from byte buffers.

yeswecancoap server enables easy implementation of coap resources, each with a dedicated function. When the function is registered by the server, it will do the rest.

Coap server example

Repository: YesWeCanCoap-example

Coap client example

under construction

server.cpp

Committer:
sillevl
Date:
2015-10-20
Revision:
3:e03960f91763
Parent:
1:ab04e3d36ade
Child:
4:34a62b7cb2f9

File content as of revision 3:e03960f91763:

#include "server.h"


Server::Server()
{
    debug_init();
    debug_set_newline("\r\n");
    
    eth.init(); //Use DHCP
    eth.connect();
    printf("\r\nServer IP Address is %s\r\n", eth.getIPAddress());
    
    server.bind(5683);
}

void Server::add(char* uri, void (*fnc)(CoapPDU*, CoapPDU*), Method method)
{
    Resource res = {uri, fnc, method};
    resources.push_back(res);
}

void Server::waitForRequest()
{

    char buffer[256];
    printf("\r\nWaiting for UDP packet...\r\n");
    int size = server.receiveFrom(client, buffer, sizeof(buffer));
    buffer[size] = '\0';
    
    char uriBuffer[32];
    int recvURILen;
    int msgId;
    uint8_t token[20];
    int tokenLength;

    CoapPDU *recvPDU = new CoapPDU((uint8_t*)buffer,256, size);
    if(recvPDU->validate()) {
        recvPDU->printHuman();

        recvPDU->getURI(uriBuffer,32,&recvURILen); 
        msgId = recvPDU->getMessageID();
        tokenLength = recvPDU->getTokenLength();
        memcpy(token, recvPDU->getTokenPointer(), tokenLength);
    }
    
    
    for(int i = 0; i < resources.size(); i++){
        if(strcmp(uriBuffer, resources[i].uri) == 0){
               
            CoapPDU *pdu = new CoapPDU();
            pdu->setType(CoapPDU::COAP_ACKNOWLEDGEMENT);
            pdu->setCode(CoapPDU::COAP_CONTENT);
            pdu->setMessageID(msgId);
            pdu->setToken(token,4);
            
            resources[i].function(recvPDU, pdu);
                    
            server.sendTo(client, (char*) pdu->getPDUPointer(),pdu->getPDULength());
            delete pdu;
            
        }
    }
    
    delete recvPDU;
}