Skip to content

Instantly share code, notes, and snippets.

@Pwera
Created August 6, 2016 19:23
Show Gist options
  • Save Pwera/e2955856bd5d52e30618885c96050852 to your computer and use it in GitHub Desktop.
Save Pwera/e2955856bd5d52e30618885c96050852 to your computer and use it in GitHub Desktop.
#ifndef MULTIPLER_COAPCLIENY_HPP
#define MULTIPLER_COAPCLIENY_HPP
#include "mongoose.h"
#include <iostream>
#include <string>
#include <functional>
class CoapClient {
struct mg_mgr mgr;
struct mg_connection *nc;
std::string address{"udp://127.0.0.1:5683"};
public:
static int s_time_to_exit;
CoapClient() {
std::cout << "[Client] Using %s as CoAP server" << address << std::endl;
}
void con(void* user_data){
mg_mgr_init(&mgr, user_data);
nc = mg_connect(&mgr, address.c_str(), CoapClient::Wrapper_To_Call);
if (nc == NULL) {
std::cout << "[Client] Unable to connect to " << address << std::endl;
}
mg_set_protocol_coap(nc);
while (!s_time_to_exit) {
mg_mgr_poll(&mgr, 1000000);
}
}
static void Wrapper_To_Call(void* pt2Object, struct mg_connection *nc, int ev, void *p)
{
static_cast<CoapClient*>(pt2Object)->coap_handler(nc, ev, p);
}
~CoapClient() {
mg_mgr_free(&mgr);
}
void coap_handler(struct mg_connection *nc, int ev, void *p) {
std::cout<<"coap_handler " << ev <<std::endl;
switch (ev) {
case MG_EV_CONNECT: {
send();
break;
}
case MG_EV_COAP_ACK:
case MG_EV_COAP_RST: {
struct mg_coap_message *cm = (struct mg_coap_message *) p;
std::cout << "[Client] ACK/RST for message with msg_id =" << cm->msg_id << " received"<<std::endl;
s_time_to_exit = 1;
break;
}
}
}
void send(){
struct mg_coap_message cm;
uint32_t res;
memset(&cm, 0, sizeof(cm));
cm.msg_id = 1;
cm.msg_type = MG_COAP_MSG_CON;
std::cout << "[Client] Sending CON..." << std::endl;
res = mg_coap_send_message(nc, &cm);
if (res == 0) {
std::cout << "[Client] Sent CON with msg_id = " << cm.msg_id << std::endl;
} else {
std::cout << "[Client] Error: " << res << std::endl;
s_time_to_exit = 1;
}
}
};
int CoapClient::s_time_to_exit=0;
#endif //MULTIPLER_COAPCLIENY_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment