coap_io.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "c_string.h"
  2. #include "coap_io.h"
  3. #include "node.h"
  4. #include "espconn.h"
  5. #include "coap_timer.h"
  6. extern coap_queue_t *gQueue;
  7. /* releases space allocated by PDU if free_pdu is set */
  8. coap_tid_t coap_send(struct espconn *pesp_conn, coap_pdu_t *pdu) {
  9. coap_tid_t id = COAP_INVALID_TID;
  10. uint32_t ip = 0, port = 0;
  11. if ( !pesp_conn || !pdu )
  12. return id;
  13. espconn_sent(pesp_conn, (unsigned char *)(pdu->msg.p), pdu->msg.len);
  14. if(pesp_conn->type == ESPCONN_TCP){
  15. c_memcpy(&ip, pesp_conn->proto.tcp->remote_ip, sizeof(ip));
  16. port = pesp_conn->proto.tcp->remote_port;
  17. }else{
  18. c_memcpy(&ip, pesp_conn->proto.udp->remote_ip, sizeof(ip));
  19. port = pesp_conn->proto.udp->remote_port;
  20. }
  21. coap_transaction_id(ip, port, pdu->pkt, &id);
  22. return id;
  23. }
  24. coap_tid_t coap_send_confirmed(struct espconn *pesp_conn, coap_pdu_t *pdu) {
  25. coap_queue_t *node;
  26. coap_tick_t diff;
  27. uint32_t r;
  28. node = coap_new_node();
  29. if (!node) {
  30. NODE_DBG("coap_send_confirmed: insufficient memory\n");
  31. return COAP_INVALID_TID;
  32. }
  33. node->retransmit_cnt = 0;
  34. node->id = coap_send(pesp_conn, pdu);
  35. if (COAP_INVALID_TID == node->id) {
  36. NODE_DBG("coap_send_confirmed: error sending pdu\n");
  37. coap_free_node(node);
  38. return COAP_INVALID_TID;
  39. }
  40. r = rand();
  41. /* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
  42. node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND +
  43. (COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) *
  44. ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
  45. node->pconn = pesp_conn;
  46. node->pdu = pdu;
  47. /* Set timer for pdu retransmission. If this is the first element in
  48. * the retransmission queue, the base time is set to the current
  49. * time and the retransmission time is node->timeout. If there is
  50. * already an entry in the sendqueue, we must check if this node is
  51. * to be retransmitted earlier. Therefore, node->timeout is first
  52. * normalized to the timeout and then inserted into the queue with
  53. * an adjusted relative time.
  54. */
  55. coap_timer_stop();
  56. coap_timer_update(&gQueue);
  57. node->t = node->timeout;
  58. coap_insert_node(&gQueue, node);
  59. coap_timer_start(&gQueue);
  60. return node->id;
  61. }