packetise.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. support for sending UDP packets on MAVLink packet boundaries.
  3. */
  4. #include <AP_HAL/AP_HAL.h>
  5. #ifndef HAL_BOOTLOADER_BUILD
  6. #include <GCS_MAVLink/GCS.h>
  7. #include "packetise.h"
  8. /*
  9. return the number of bytes to send for a packetised connection
  10. */
  11. uint16_t mavlink_packetise(ByteBuffer &writebuf, uint16_t n)
  12. {
  13. int16_t b = writebuf.peek(0);
  14. if (b != MAVLINK_STX_MAVLINK1 && b != MAVLINK_STX) {
  15. /*
  16. we have a non-mavlink packet at the start of the
  17. buffer. Look ahead for a MAVLink start byte, up to 256 bytes
  18. ahead
  19. */
  20. uint16_t limit = n>256?256:n;
  21. uint16_t i;
  22. for (i=0; i<limit; i++) {
  23. b = writebuf.peek(i);
  24. if (b == MAVLINK_STX_MAVLINK1 || b == MAVLINK_STX) {
  25. n = i;
  26. break;
  27. }
  28. }
  29. // if we didn't find a MAVLink marker then limit the send size to 256
  30. if (i == limit) {
  31. n = limit;
  32. }
  33. return n;
  34. }
  35. // cope with both MAVLink1 and MAVLink2 packets
  36. uint8_t min_length = (b == MAVLINK_STX_MAVLINK1)?8:12;
  37. // this looks like a MAVLink packet - try to write on
  38. // packet boundaries when possible
  39. if (n < min_length) {
  40. // we need to wait for more data to arrive
  41. return 0;
  42. }
  43. // the length of the packet is the 2nd byte
  44. int16_t len = writebuf.peek(1);
  45. if (b == MAVLINK_STX) {
  46. // This is Mavlink2. Check for signed packet with extra 13 bytes
  47. int16_t incompat_flags = writebuf.peek(2);
  48. if (incompat_flags & MAVLINK_IFLAG_SIGNED) {
  49. min_length += MAVLINK_SIGNATURE_BLOCK_LEN;
  50. }
  51. }
  52. if (n < len+min_length) {
  53. // we don't have a full packet yet
  54. return 0;
  55. }
  56. if (n > len+min_length) {
  57. // send just 1 packet at a time (so MAVLink packets
  58. // are aligned on UDP boundaries)
  59. n = len+min_length;
  60. }
  61. return n;
  62. }
  63. #endif // HAL_BOOTLOADER_BUILD