Created
June 11, 2021 15:01
-
-
Save obiltschnig/2b4ec184a6d8efea70ec4ab6a9110fbf to your computer and use it in GitHub Desktop.
libcoap example server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -o coap-server coap-server.cpp -lcoap-2-openssl -lPocoNet -lPocoFoundation | |
#include <Poco/Net/SocketAddress.h> | |
#include <Poco/Random.h> | |
#include <Poco/NumberFormatter.h> | |
#include <Poco/Exception.h> | |
#include <coap2/coap.h> | |
#include <iostream> | |
int main(int argc, char** argv) | |
{ | |
coap_context_t* pCoapContext = nullptr; | |
coap_startup(); | |
try | |
{ | |
Poco::Net::SocketAddress sockAddr("localhost", "5683"); | |
coap_address_t coapAddr; | |
coapAddr.size = sockAddr.length(); | |
std::memcpy(&coapAddr.addr.sin, sockAddr.addr(), sockAddr.length()); | |
pCoapContext = coap_new_context(nullptr); | |
if (!pCoapContext) throw Poco::IOException("cannot create CoAP context"); | |
coap_endpoint_t* pCoapEndpoint = coap_new_endpoint(pCoapContext, &coapAddr, COAP_PROTO_UDP); | |
if (!pCoapEndpoint) throw Poco::IOException("cannot create CoAP endpoint"); | |
coap_str_const_t uri = { 4, reinterpret_cast<const uint8_t*>("rssi") }; | |
coap_resource_t* pCoapResource = coap_resource_init(&uri, 0); | |
coap_register_handler(pCoapResource, COAP_REQUEST_GET, | |
[](auto, auto, auto, auto, auto, auto, coap_pdu_t* pResponse) | |
{ | |
static Poco::Random rnd; | |
pResponse->code = COAP_RESPONSE_CODE(205); | |
int rssi = -50 - rnd.next(20); | |
std::string data = Poco::NumberFormatter::format(rssi); | |
coap_add_data(pResponse, data.size(), reinterpret_cast<const uint8_t*>(data.data())); | |
}); | |
coap_add_resource(pCoapContext, pCoapResource); | |
for (;;) | |
{ | |
coap_run_once(pCoapContext, 0); | |
} | |
} | |
catch (Poco::Exception& exc) | |
{ | |
std::cerr << exc.displayText() << std::endl; | |
} | |
if (pCoapContext) coap_free_context(pCoapContext); | |
coap_cleanup(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment