00001
00002
00003
00004 #ifndef NMC_MSG_BUILDER_H
00005 #define NMC_MSG_BUILDER_H
00006
00007
00008 #include "endian.H"
00009
00010
00011 #include <cassert>
00012 #include <cstring>
00013
00014
00015 namespace nmc
00016 {
00017 using namespace endian;
00018
00019 class msg_builder_t
00020 {
00021 public:
00022 msg_builder_t ();
00023 virtual ~msg_builder_t () {};
00024
00025 static unsigned const MAX_MSG_SIZE = 20;
00026
00027 unsigned build (u8_t address, u8_t *data, unsigned max_size);
00028
00029 protected:
00030 static unsigned const ENVELOPE_SIZE = 4;
00031 static unsigned const HEADER_SIZE = 3;
00032 static unsigned const FOOTER_SIZE = 1;
00033
00034 static unsigned const ADDRESS_OFFSET = 1;
00035 static unsigned const COMMAND_OFFSET = 2;
00036
00037 static u8_t const STX = 0xAA;
00038
00039 static u8_t calc_crc (u8_t const *data, unsigned size);
00040
00041 unsigned m_offset;
00042
00043 u8_t *m_data;
00044 unsigned m_max_size;
00045
00046 template <typename T>
00047 void encode (T const &v)
00048 {
00049 assert ((m_offset + sizeof (v)) <= m_max_size);
00050 htole (v, m_data + m_offset);
00051 m_offset += sizeof (v);
00052 }
00053
00054 void encode (void *data, unsigned size)
00055 {
00056 assert ((m_offset + size) <= m_max_size);
00057 memcpy (m_data + m_offset, data, size);
00058 m_offset += size;
00059 }
00060
00061 virtual u8_t _build (void) = 0;
00062 };
00063
00064 class set_address_builder_t : public msg_builder_t
00065 {
00066 public:
00067 set_address_builder_t () :
00068 m_module_address (0), m_group_address (0) {}
00069
00070 void module_address (u8_t address)
00071 { m_module_address = address; }
00072 void group_address (u8_t address)
00073 { m_group_address = address; }
00074
00075 protected:
00076 u8_t _build (void);
00077
00078 u8_t m_module_address;
00079 u8_t m_group_address;
00080 };
00081
00082 class set_baud_rate_builder_t : public msg_builder_t
00083 {
00084 public:
00085 enum baud_t
00086 {
00087 BAUD_9600 = 129,
00088 BAUD_19200 = 63,
00089 BAUD_57600 = 20,
00090 BAUD_115200 = 10,
00091 };
00092
00093 set_baud_rate_builder_t () : m_baud (BAUD_19200) {}
00094
00095 void baud_rate (baud_t baud) { m_baud = baud; }
00096
00097 protected:
00098 u8_t _build (void);
00099
00100 baud_t m_baud;
00101 };
00102
00103 class no_op_builder_t : public msg_builder_t
00104 {
00105 protected:
00106 u8_t _build (void);
00107 };
00108
00109 class hard_reset_builder_t : public msg_builder_t
00110 {
00111 protected:
00112 u8_t _build (void);
00113 };
00114 };
00115
00116
00117 #endif