1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QMODBUSDATAUNIT_H
5#define QMODBUSDATAUNIT_H
6
7#include <QtCore/qlist.h>
8#include <QtCore/qmap.h>
9#include <QtCore/qmetatype.h>
10
11QT_BEGIN_NAMESPACE
12
13class QModbusDataUnit
14{
15public:
16 enum RegisterType {
17 Invalid,
18 DiscreteInputs,
19 Coils,
20 InputRegisters,
21 HoldingRegisters
22 };
23
24 QModbusDataUnit() = default;
25
26 constexpr explicit QModbusDataUnit(RegisterType type) noexcept
27 : m_type(type)
28 , m_startAddress(0)
29 {}
30
31 QModbusDataUnit(RegisterType type, int newStartAddress, quint16 newValueCount)
32 : QModbusDataUnit(type, newStartAddress, QList<quint16>(newValueCount))
33 {}
34
35 QModbusDataUnit(RegisterType type, int newStartAddress, const QList<quint16> &newValues)
36 : m_type(type)
37 , m_startAddress(newStartAddress)
38 , m_values(newValues)
39 , m_valueCount(newValues.size())
40 {}
41
42 RegisterType registerType() const { return m_type; }
43 void setRegisterType(RegisterType type) { m_type = type; }
44
45 inline int startAddress() const { return m_startAddress; }
46 inline void setStartAddress(int newAddress) { m_startAddress = newAddress; }
47
48 inline QList<quint16> values() const { return m_values; }
49 inline void setValues(const QList<quint16> &newValues)
50 {
51 m_values = newValues;
52 m_valueCount = newValues.size();
53 }
54
55 inline qsizetype valueCount() const { return m_valueCount; }
56 inline void setValueCount(qsizetype newCount) { m_valueCount = newCount; }
57
58 inline void setValue(qsizetype index, quint16 newValue)
59 {
60 if (m_values.isEmpty() || index >= m_values.size())
61 return;
62 m_values[index] = newValue;
63 }
64 inline quint16 value(qsizetype index) const { return m_values.value(i: index); }
65
66 bool isValid() const { return m_type != Invalid && m_startAddress != -1; }
67
68private:
69 RegisterType m_type = Invalid;
70 int m_startAddress = -1;
71 QList<quint16> m_values;
72 qsizetype m_valueCount = 0;
73};
74typedef QMap<QModbusDataUnit::RegisterType, QModbusDataUnit> QModbusDataUnitMap;
75
76Q_DECLARE_TYPEINFO(QModbusDataUnit, Q_RELOCATABLE_TYPE);
77Q_DECLARE_TYPEINFO(QModbusDataUnit::RegisterType, Q_PRIMITIVE_TYPE);
78
79QT_END_NAMESPACE
80
81Q_DECLARE_METATYPE(QModbusDataUnit::RegisterType)
82
83#endif // QMODBUSDATAUNIT_H
84

source code of qtserialbus/src/serialbus/qmodbusdataunit.h