Library for handling subset of coap functionality by radio transmitter.

Dependencies:   nRF24L01P cantcoap

Dependents:   server2

coapServer.cpp

Committer:
Ka_myk
Date:
2019-01-20
Revision:
1:1d936c763440
Parent:
0:6a6f97ca5572
Child:
2:c3ca8b8526e0

File content as of revision 1:1d936c763440:

//
// Created by Kamil Mykitiuk on 2019-01-18.
//

#include "coapServer.h"

int CoapServer::listen(uint8_t* buffer, int len, METHOD* requestMethod, int* uriNumber) {
    uint8_t requestBuffer[radioWrapper.packetSize()];
    int ret = radioWrapper.read(requestBuffer, radioWrapper.packetSize(), this->listeningTimeout);
    if (ret < 0) {
        return RADIO_NOT_WORKING;
    } else {
        CoapPDU request(requestBuffer, radioWrapper.packetSize(), ret);
        if (request.validate()) {

            this->lastMessageId = request.getMessageID();
            std::memcpy(this->lastMessageToken, request.getTokenPointer(), 4);
            if (request.getPayloadLength() <= len) {
                std::memcpy(buffer, request.getPayloadPointer(), static_cast<size_t>(request.getPayloadLength()));
                if (request.getCode() == CoapPDU::COAP_GET) {
                    *requestMethod = GET;
                } else if (request.getCode() == CoapPDU::COAP_POST) {
                    *requestMethod = POST;
                }
                char requestUri[32];
                int requestUriLen = 0;
                request.getURI(requestUri, 32, &requestUriLen);
                bool foundMatchingUri = false;
                for (int i = 0; i < urisNumber; ++i) {
                    if(std::strcmp(requestUri, this->uris[i].data()) == 0) {
                        *uriNumber = i;
                        foundMatchingUri = true;
                    }
                }
                if(!foundMatchingUri) {
                    return UNKNOWN_URI;
                }
                return request.getPayloadLength();
            } else {
                return SMALL_BUFFER;
            }
        }
    }
    return 0;
}

int CoapServer::respond(int uri, uint8_t* buffer, int len, CoapPDU::Code responseCode) {
    CoapPDU response = CoapPDU();
    prepareAckPDU(response);
    response.setCode(responseCode);
    response.setPayload(buffer, len);
    response.setURI((char*) uris[uri].data(), (int)uris[uri].size());
    int ret = radioWrapper.write(response.getPDUPointer(), response.getPDULength());
    if(ret < 0) {
        return RADIO_NOT_WORKING;
    }
    return 0;
}

void CoapServer::prepareAckPDU(CoapPDU& coapPDU) {
    coapPDU.setVersion(1);
    coapPDU.setType(CoapPDU::COAP_ACKNOWLEDGEMENT);
    coapPDU.setMessageID(this->lastMessageId);
    coapPDU.setToken(this->lastMessageToken, 4);
}

CoapServer::CoapServer(int timeout, std::string* uris, int urisNumber, int channel, unsigned long long rx_address,  unsigned long long tx_address): 
listeningTimeout(timeout), radioWrapper(channel, rx_address, tx_address), urisNumber(urisNumber), uris(uris) {}