xref: /openbmc/phosphor-modbus/rtu/modbus/modbus_message.hpp (revision 9695bd284570b51677c11529103929c8e51da6b6)
1 #pragma once
2 
3 #include <array>
4 #include <cstddef>
5 #include <cstdint>
6 #include <string>
7 #include <vector>
8 
9 namespace phosphor::modbus::rtu
10 {
11 
12 class Message
13 {
14   public:
15     static constexpr auto maxADUSize = 256;
16     std::array<uint8_t, maxADUSize> raw{};
17     size_t len = 0;
18 
19     // Push to the end of raw message
20     Message& operator<<(uint8_t d);
21     Message& operator<<(uint16_t d);
22     Message& operator<<(uint32_t d);
23 
24     // Pop from the end of raw message
25     Message& operator>>(uint8_t& d);
26     Message& operator>>(uint16_t& d);
27     Message& operator>>(uint32_t& d);
28 
29     Message() = default;
30     Message(const Message&) = delete;
31     Message& operator=(const Message&) = delete;
32 
33     uint8_t& address = raw[0];
34     uint8_t& functionCode = raw[1];
35 
36   protected:
37     auto appendCRC() -> void;
38     auto validate() -> void;
39     auto verifyValue(const std::string& name, uint32_t currentValue,
40                      uint32_t expectedValue) -> void;
41 
42     template <typename T>
operator >>(std::vector<T> & d)43     Message& operator>>(std::vector<T>& d)
44     {
45         for (auto it = d.rbegin(); it != d.rend(); it++)
46         {
47             *this >> *it;
48         }
49         return *this;
50     }
51 
52   private:
53     auto generateCRC() -> uint16_t;
54 
begin()55     constexpr auto begin() noexcept
56     {
57         return raw.begin();
58     }
end()59     auto end() noexcept
60     {
61         return raw.begin() + len;
62     }
63 };
64 
65 } // namespace phosphor::modbus::rtu
66