void coap_server(void* para)
{
int fd;
struct sockaddr_in servaddr, cliaddr;
coap_rw_buffer_t scratch_buf = {scratch_raw, sizeof(scratch_raw)};
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
printf("Socket Error\r\n");
return;
}
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
rt_memset(&(servaddr.sin_zero), 0, sizeof(servaddr.sin_zero));
if ((bind(fd, (struct sockaddr *)&servaddr, sizeof(servaddr))) == -1)
{
printf("Bind error\r\n");
return;
}
endpoint_setup();
rt_kprintf("Coap Server Start!\r\n");
while(1)
{
int n, rc;
socklen_t len = sizeof(cliaddr);
coap_packet_t pkt;
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&cliaddr, &len);
#ifdef MICROCOAP_DEBUG
printf("\r\n--------------------\r\n");
printf("Received Buffer: \r\n");
coap_dump(buf, n, true);
printf("\r\n");
#endif
if (0 != (rc = coap_parse(&pkt, buf, n)))
{
printf("Bad packet rc=%d\r\n", rc);
}
else
{
size_t rsplen = sizeof(buf);
coap_packet_t rsppkt;
#ifdef MICROCOAP_DEBUG
printf("Dump Packet: \r\n");
coap_dumpPacket(&pkt);
#endif
coap_handle_req(&scratch_buf, &pkt, &rsppkt);
if (0 != (rc = coap_build(buf, &rsplen, &rsppkt)))
{
printf("coap_build failed rc=%d\n", rc);
}
else
{
#ifdef MICROCOAP_DEBUG
printf("--------------------\r\n");
printf("Sending Buffer: \r\n");
coap_dump(buf, rsplen, true);
printf("\r\n");
#endif
#ifdef MICROCOAP_DEBUG
coap_dumpPacket(&rsppkt);
#endif
sendto(fd, buf, rsplen, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
}
}
}
}const coap_endpoint_t endpoints[] =
{
{COAP_METHOD_GET, handle_get_well_known_core, &path_well_known_core, "ct=40"},
{COAP_METHOD_GET, handle_get_light, &path_light, "ct=0"},
{COAP_METHOD_PUT, handle_put_light, &path_light, NULL},
{COAP_METHOD_GET, handle_get_test_json, &path_test_json, "ct=50"},
{(coap_method_t)0, NULL, NULL, NULL}
};static const coap_endpoint_path_t path_light = {1, {"light"}};
static const coap_endpoint_path_t path_well_known_core = {2, {".well-known", "core"}}; light的URI为 coap://<ip>:5683/lightstatic int handle_get_light(coap_rw_buffer_t *scratch,
const coap_packet_t *inpkt,
coap_packet_t *outpkt,
uint8_t id_hi, uint8_t id_lo)
{
return coap_make_response(scratch,
outpkt,
(const uint8_t *)&light, 1,
id_hi, id_lo,
&inpkt->tok,
COAP_RSPCODE_CONTENT,
COAP_CONTENTTYPE_TEXT_PLAIN);
}


CoAP学习笔记——STM32平台上实现CoAP Server
原文地址:http://blog.csdn.net/xukai871105/article/details/45670033