Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
3.1 KiB

  1. /*
  2. TUYA MODULE
  3. Copyright (C) 2019 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
  4. */
  5. #pragma once
  6. #include <vector>
  7. #include "tuya_types.h"
  8. #include "tuya_transport.h"
  9. namespace Tuya {
  10. class DataFrame {
  11. public:
  12. using container = std::vector<uint8_t>;
  13. using const_iterator = container::const_iterator;
  14. DataFrame(DataFrame& rhs) = delete;
  15. ~DataFrame() = default;
  16. DataFrame(DataFrame&& rhs) = default;
  17. DataFrame(uint8_t command) :
  18. command(command),
  19. length(0)
  20. {}
  21. DataFrame(Command command) :
  22. DataFrame(static_cast<uint8_t>(command))
  23. {}
  24. DataFrame(Command command, uint16_t length,
  25. const const_iterator begin,
  26. const const_iterator end) :
  27. command(static_cast<uint8_t>(command)),
  28. length(length),
  29. _begin(begin),
  30. _end(end)
  31. {}
  32. DataFrame(uint8_t version, uint8_t command, uint16_t length,
  33. const const_iterator begin,
  34. const const_iterator end) :
  35. version(version),
  36. command(command),
  37. length(length),
  38. _begin(begin),
  39. _end(end)
  40. {}
  41. DataFrame(Command command, std::initializer_list<uint8_t> data) :
  42. command(static_cast<uint8_t>(command)),
  43. length(data.size()),
  44. _data(data),
  45. _begin(_data.cbegin()),
  46. _end(_data.cend())
  47. {}
  48. DataFrame(Command command, std::vector<uint8_t>&& data) :
  49. command(static_cast<uint8_t>(command)),
  50. length(data.size()),
  51. _data(std::move(data)),
  52. _begin(_data.cbegin()),
  53. _end(_data.cend())
  54. {}
  55. DataFrame(const_iterator iter) :
  56. version(iter[2]),
  57. command(iter[3]),
  58. length((iter[4] << 8) + iter[5]),
  59. _begin(iter + 6),
  60. _end(iter + 6 + length)
  61. {}
  62. DataFrame(const Transport& input) :
  63. DataFrame(input.cbegin())
  64. {}
  65. bool commandEquals(Command command) const {
  66. return (static_cast<uint8_t>(command) == this->command);
  67. }
  68. const_iterator cbegin() const {
  69. return _begin;
  70. };
  71. const_iterator cend() const {
  72. return _end;
  73. };
  74. uint8_t operator[](size_t i) const {
  75. if (!length) return 0;
  76. return _begin[i];
  77. }
  78. container serialize() const {
  79. container result;
  80. result.reserve(6 + length);
  81. result.assign({
  82. version, command,
  83. uint8_t(length >> 8),
  84. uint8_t(length & 0xff)
  85. });
  86. if (length && (_begin != _end)) {
  87. result.insert(result.end(), _begin, _end);
  88. }
  89. return result;
  90. }
  91. uint8_t version = 0;
  92. uint8_t command = 0;
  93. uint16_t length = 0;
  94. protected:
  95. container _data;
  96. const_iterator _begin;
  97. const_iterator _end;
  98. };
  99. }