Skip to content

Instantly share code, notes, and snippets.

@obiltschnig
Created June 11, 2021 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obiltschnig/fb77dffe00c594706b591f2eb9abf239 to your computer and use it in GitHub Desktop.
Save obiltschnig/fb77dffe00c594706b591f2eb9abf239 to your computer and use it in GitHub Desktop.
libcoap example client
// g++ -o coap-get coap-get.cpp -lcoap-2-openssl -lPocoNet -lPocoFoundation
#include <Poco/Net/SocketAddress.h>
#include <Poco/Exception.h>
#include <coap2/coap.h>
#include <cstring>
#include <iostream>
int main(int argc, char** argv)
{
coap_context_t* pCoapContext = nullptr;
coap_session_t* pCoapSession = 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");
pCoapSession = coap_new_client_session(pCoapContext, nullptr, &coapAddr, COAP_PROTO_UDP);
if (!pCoapSession) throw Poco::IOException("cannot create CoAP client session");
coap_register_response_handler(pCoapContext,
[](coap_context_t* pCtx, coap_session_t* pSess, coap_pdu_t* pSent, coap_pdu_t* pReceived, const coap_tid_t id)
{
coap_show_pdu(LOG_WARNING, pReceived);
std::size_t len;
std::uint8_t* pData;
coap_get_data(pReceived, &len, &pData);
std::string data(reinterpret_cast<char*>(pData), len);
std::cout << data << std::endl;
}
);
coap_pdu_t* pRequestPDU = coap_pdu_init(
COAP_MESSAGE_CON,
COAP_REQUEST_GET,
coap_new_message_id(pCoapSession),
coap_session_max_pdu_size(pCoapSession)
);
if (!pRequestPDU) throw Poco::IOException("canot create PDU");
std::string path("rssi");
coap_add_option(pRequestPDU, COAP_OPTION_URI_PATH, path.size(), reinterpret_cast<const uint8_t*>(path.data()));
coap_show_pdu(LOG_WARNING, pRequestPDU);
coap_send(pCoapSession, pRequestPDU);
coap_run_once(pCoapContext, 0);
}
catch (Poco::Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
}
if (pCoapSession) coap_session_release(pCoapSession);
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