summaryrefslogtreecommitdiffstats
path: root/src/knx/qknxnpdu.cpp
blob: 35df5d393a6a3940596920def8be7fe2ba049684 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/******************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtKnx module.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
******************************************************************************/

#include "qknxnpdu.h"
#include "qknxutils.h"

QT_BEGIN_NAMESPACE

/*!
    \class QKnxNpdu

    \inmodule QtKnx
    \brief This class represents the part of the \l QKnxCemiFrame to be read by
    the network, transport and application layers.

    To build a valid NPDU it is recommended to use the \l QKnxNpduFactory.
    Reading the bytes from left to right, a NPDU is composed of the following
    information:

    \list
        \li The length of the payload (full size of NPDU - 2)
        \li The transport layer code \l TransportControlField,
        \li The application layer service code \l ApplicationControlField
    \endlist

    If applicable, the T_CONNECT NPDU holds no application layer service for
    example, and the data and other information (if applicable, depending on
    the chosen service).
*/

/*!
    \enum QKnxNpdu::ErrorCode

    This enum describes the possible error codes needing in the building
    of NPDU with service \l QKnxNpdu::FunctionPropertyStateResponse or
    \l QKnxNpdu::Restart

    \value NoError
    \value Error
*/

/*!
    \enum QKnxNpdu::ResetType
    This enum describes the possible reset types needing in the building of
    NPDU with service \l QKnxNpdu::Restart.

    \value BasicRestart
    \value MasterRestart
*/

/*!
    \enum QKnxNpdu::EraseCode
    This enum describes the possible erase codes needing in the building of
    NPDU with service \l QKnxNpdu::Restart.

    \value Reserved
    \value ConfirmedRestart
    \value FactoryReset
    \value ResetIa
    \value ResetAp
    \value ResetParam
    \value ResetLinks
    \value ResetWithoutIa
    \value Invalid
*/

/*!
    \enum QKnxNpdu::LinkWriteFlags
    This enum describes the possible link write flags needing in the building
    of NPDU with service \l QKnxNpdu::LinkWrite.

    \value AddGroupAddress
    \value AddSendingGroupAddress
    \value AddNotSendingGroupAddress
    \value DeleteGroupAddress
*/

/*!
    \enum QKnxNpdu::TransportControlField
    This enum describes the possible message code dedicated to the transport
    layer.

    \value DataGroup
    \value DataBroadcast
    \value DataSystemBroadcast
    \value DataTagGroup
    \value DataIndividual
    \value DataConnected
    \value Connect
    \value Disconnect
    \value Acknowledge
    \value NoAcknowledge
    \value Invalid
*/

/*!
    \enum QKnxNpdu::ApplicationControlField
    This enum describes the message code dedicated to the application and
    representing an application service.

    \value GroupValueRead
    \value GroupValueResponse
    \value GroupValueWrite
    \value IndividualAddressWrite
    \value IndividualAddressRead
    \value IndividualAddressResponse
    \value AdcRead
    \value AdcResponse
    \value SystemNetworkParameterRead
    \value SystemNetworkParameterResponse
    \value SystemNetworkParameterWrite
    \value MemoryRead
    \value MemoryResponse
    \value MemoryWrite
    \value UserMemoryRead
    \value UserMemoryResponse
    \value UserMemoryWrite
    \value UserManufacturerInfoRead
    \value UserManufacturerInfoResponse
    \value FunctionPropertyCommand
    \value FunctionPropertyStateRead
    \value FunctionPropertyStateResponse
    \value DeviceDescriptorRead
    \value DeviceDescriptorResponse
    \value Restart
    \value AuthorizeRequest
    \value AuthorizeResponse
    \value KeyWrite
    \value KeyResponse
    \value PropertyValueRead
    \value PropertyValueResponse
    \value PropertyValueWrite
    \value PropertyDescriptionRead
    \value PropertyDescriptionResponse
    \value NetworkParameterRead
    \value NetworkParameterResponse
    \value IndividualAddressSerialNumberRead
    \value IndividualAddressSerialNumberResponse
    \value IndividualAddressSerialNumberWrite
    \value DomainAddressWrite
    \value DomainAddressRead
    \value DomainAddressResponse
    \value DomainAddressSelectiveRead
    \value NetworkParameterWrite
    \value NetworkParameterInfoReport
    \value LinkRead
    \value LinkResponse
    \value LinkWrite
    \value GroupPropValueRead
    \value GroupPropValueResponse
    \value GroupPropValueWrite
    \value GroupPropValueInfoReport
    \value DomainAddressSerialNumberRead
    \value DomainAddressSerialNumberResponse
    \value DomainAddressSerialNumberWrite
    \value FileStreamInfoReport
    \value Invalid
*/


static bool isBitSet(quint8 byteToTest, quint8 bit)
{
    return (byteToTest & (quint8(1) << bit)) != 0;
};

/*!
    Returns the Transport layer control field of the \c QKnxNpdu.
*/
QKnxNpdu::TransportControlField QKnxNpdu::transportControlField() const
{
    if (size() < 2)
        return TransportControlField::Invalid;

    if (isBitSet(byte(1), 7) && isBitSet(byte(1), 6))      // T_ACK/ T_NACK
        return TransportControlField(byte(1) & 0xc3); // no APCI, mask out sequence number

    if (isBitSet(byte(1), 7) && (!isBitSet(byte(1), 6))) // T_CONNECT/ T_DISCONNECT
        return TransportControlField(byte(1)); // no APCI, no sequence number

    if (isBitSet(byte(1), 6))                                // T_DATA_CONNECTED, mask out the APCI
        return TransportControlField((byte(1) & 0xfc) & 0xc3); // and the sequence number

    return TransportControlField(byte(1) & 0xfc); // mask out the APCI
}

/*!
    Sets the Transport layer control field to \a tpci.
*/
void QKnxNpdu::setTransportControlField(TransportControlField tpci)
{
    if (size() < 2)
        resize(2);
    setByte(1, (byte(1) & 0x03) | quint8(tpci));
    setByte(0, quint8(qMax<quint16>(0u, size() - 2)));
}

/*!
    Returns the Application layer control field of the \c QKnxNpdu.
*/
QKnxNpdu::ApplicationControlField QKnxNpdu::applicationControlField() const
{
    if (size() < 3)
        return ApplicationControlField::Invalid;

    std::bitset<8> apciHigh = byte(1) & 0x03; // mask out all bits except the first two
    std::bitset<8> apciLow = byte(2) & 0xc0;  // mask out all bits except the last two

    const auto fourBitsApci = [&apciHigh, &apciLow]() {
        QVector<quint8> apciBytes = { { quint8(apciHigh.to_ulong()), quint8(apciLow.to_ulong()) } };
        return ApplicationControlField(QKnxUtils::QUint16::fromBytes(apciBytes));
    };
    const auto tenBitsApci = [apciHigh](quint8 octet7) {
        QVector<quint8> apciBytes = { { quint8(apciHigh.to_ulong()), octet7 } };
        return ApplicationControlField(QKnxUtils::QUint16::fromBytes(apciBytes));
    };

    if ((apciHigh[0] == 0 && apciHigh[1] == 0) || (apciHigh[0] == 1 && apciHigh[1] == 1)) {
        std::bitset<8> octet7 = byte(2);
        if (octet7[7] == 1 && octet7[6] == 1)
            return tenBitsApci(byte(2));
        return fourBitsApci();
    }

    if (apciHigh[1] == 0 && apciHigh[0] == 1) {
        // connection oriented, it's one of the A_ADC service
        if (quint8(transportControlField()) > 0)
            return fourBitsApci();
        return tenBitsApci(byte(2));
    }

    // it's one of the A_Memory Service (only the 2 last bits of octet 6 are needed for the apci)
    if (apciLow[7] == 0 || apciLow[6] == 0)
        return fourBitsApci();
    return tenBitsApci(byte(2));
}

/*!
    Sets the Application layer control field to \a apci.
*/
void QKnxNpdu::setApplicationControlField(ApplicationControlField apci)
{
    if (size() < 3)
        resize(3);

    auto tmp = QKnxUtils::QUint16::bytes(quint16(apci));
    setByte(0, qMax<quint16>(1u, size() - 2));
    setByte(1, (byte(1) & 0xfc) | tmp[0]);
    setByte(2, (byte(2) & 0x3f) | tmp[1]);
}

QKnxNpdu::QKnxNpdu(TransportControlField tpci)
{
    setTransportControlField(tpci);
}

QKnxNpdu::QKnxNpdu(TransportControlField tpci, ApplicationControlField apci)
{
    setTransportControlField(tpci);
    setApplicationControlField(apci);
}

QKnxNpdu::QKnxNpdu(TransportControlField tpci, ApplicationControlField apci, const QByteArray &data)
    : QKnxNpdu(tpci, apci, 0, data)
{}

QKnxNpdu::QKnxNpdu(TransportControlField tpci, ApplicationControlField apci, quint8 seqNumber,
        const QByteArray &data)
    : QKnxNpdu(tpci, apci)
{
    setSequenceNumber(seqNumber);
    setData(data);
}

/*!
    Returns true if the current NPDU is valid.

    \note This function is not implemented for every services.
    To make sure your NPDU is correct, use the \l QKnxNpduFactory.
 */
bool QKnxNpdu::isValid() const
{
    switch (transportControlField()) {
    case TransportControlField::Invalid:
        return false;
    case TransportControlField::Connect:
    case TransportControlField::Disconnect:
    case TransportControlField::Acknowledge:
    case TransportControlField::NoAcknowledge:
        return size() == 2;
    default:
        break;
    }

#define HEADER_SIZE 3 // [size][TCPI|APCI][APCI] 3 bytes
#define L_DATA_PAYLOAD 14 // 3_02_02 Communication Medium TP1, Paragraph 2.2.4.1
#define L_DATA_EXTENDED_PAYLOAD 253 // 3_02_02 Communication Medium TP1, Paragraph 2.2.5.1

    switch (applicationControlField()) {
    case ApplicationControlField::GroupValueRead:
    case ApplicationControlField::GroupPropValueRead:
    case ApplicationControlField::IndividualAddressRead:
    case ApplicationControlField::IndividualAddressResponse:
    case ApplicationControlField::DomainAddressRead:
        return size() == HEADER_SIZE;

    case ApplicationControlField::IndividualAddressWrite:
        return size() == HEADER_SIZE + 2; // 2 bytes individual address

    case ApplicationControlField::GroupValueResponse:
    case ApplicationControlField::GroupValueWrite:
        return (size() >= HEADER_SIZE) && (size() <= HEADER_SIZE + L_DATA_PAYLOAD);

    case ApplicationControlField::GroupPropValueResponse:
    case ApplicationControlField::GroupPropValueWrite:
    case ApplicationControlField::GroupPropValueInfoReport:
    case ApplicationControlField::NetworkParameterRead:
    case ApplicationControlField::NetworkParameterWrite:
    case ApplicationControlField::SystemNetworkParameterRead:
    case ApplicationControlField::SystemNetworkParameterResponse:
    case ApplicationControlField::SystemNetworkParameterWrite:
        // 3_02_02 Paragraph 2.2.5.1: L_Data_Extended -> max 254 bytes
        return (size() >= HEADER_SIZE) && (size() <= HEADER_SIZE + L_DATA_EXTENDED_PAYLOAD);

     // To properly judge that next two one needs to know the type of cEMI frame.
    case ApplicationControlField::NetworkParameterResponse: // L_Data
        //return (size() >= HEADER_SIZE) && (size() <= HEADER_SIZE + L_DATA_PAYLOAD);
    // case ApplicationLayerControlField::NetworkParameterInfoReport: // L_Data_Extended
        return (size() >= HEADER_SIZE) && (size() <= HEADER_SIZE + L_DATA_EXTENDED_PAYLOAD);

    case ApplicationControlField::IndividualAddressSerialNumberRead:
    case ApplicationControlField::DomainAddressSerialNumberRead:
        return (size() >= HEADER_SIZE) && (size() <= HEADER_SIZE + 6); // 6 bytes serial number
    case ApplicationControlField::IndividualAddressSerialNumberResponse:
         // 6 bytes serial number, 2 bytes new address, 2 reserved bytes
        return (size() >= HEADER_SIZE) && (size() <= HEADER_SIZE + 10);
    case ApplicationControlField::IndividualAddressSerialNumberWrite:
         // 6 bytes serial number, 2 bytes new address, 4 reserved bytes
        return (size() >= HEADER_SIZE) && (size() <= HEADER_SIZE + 12);

    case ApplicationControlField::DomainAddressWrite:
    case ApplicationControlField::DomainAddressResponse:
       return (size() == HEADER_SIZE + 2) || (size() == HEADER_SIZE + 6); // 2 or 6 byteToTest domain address
    case ApplicationControlField::DomainAddressSelectiveRead:
        if (size() >= HEADER_SIZE) // 03_05_02 Management Procedures
            return size() == (byte(3) == 0x00 ? 8 : 14); // Paragraph: 2.12.1.1/2.12.1.2
        return false;

    case ApplicationControlField::DomainAddressSerialNumberResponse:
    case ApplicationControlField::DomainAddressSerialNumberWrite: // 6 byteToTest serial number
        return (size() == HEADER_SIZE + 8) || (size() == HEADER_SIZE + 12); // 2 or 6 byteToTest domain address

    case ApplicationControlField::AdcRead:
    case ApplicationControlField::AdcResponse:
    case ApplicationControlField::MemoryRead:
    case ApplicationControlField::MemoryResponse:
    case ApplicationControlField::MemoryWrite:
    case ApplicationControlField::UserMemoryRead:
    case ApplicationControlField::UserMemoryResponse:
    case ApplicationControlField::UserMemoryWrite:
    case ApplicationControlField::UserManufacturerInfoRead:
    case ApplicationControlField::UserManufacturerInfoResponse:
    case ApplicationControlField::FunctionPropertyCommand:
    case ApplicationControlField::FunctionPropertyStateRead:
    case ApplicationControlField::FunctionPropertyStateResponse:
    case ApplicationControlField::DeviceDescriptorRead:
    case ApplicationControlField::DeviceDescriptorResponse:
    case ApplicationControlField::Restart:
    case ApplicationControlField::AuthorizeRequest:
    case ApplicationControlField::AuthorizeResponse:
    case ApplicationControlField::KeyWrite:
    case ApplicationControlField::KeyResponse:
    case ApplicationControlField::PropertyValueRead:
    case ApplicationControlField::PropertyValueResponse:
    case ApplicationControlField::PropertyValueWrite:
    case ApplicationControlField::PropertyDescriptionRead:
    case ApplicationControlField::PropertyDescriptionResponse:
    case ApplicationControlField::LinkRead:
    case ApplicationControlField::LinkResponse:
    case ApplicationControlField::LinkWrite:
    case ApplicationControlField::FileStreamInfoReport:
    case ApplicationControlField::Invalid:
        break;  // TODO: implement
    }
    return false;

#undef HEADER_SIZE
#undef L_DATA_PAYLOAD
#undef L_DATA_EXTENDED_PAYLOAD
}

quint8 QKnxNpdu::dataSize() const
{
    return byte(0);
}

quint8 QKnxNpdu::sequenceNumber() const
{
    if (isBitSet(byte(1), 6))
        return quint8((byte(1) & 0x3c) >> 2);
    return 0;
}

void QKnxNpdu::setSequenceNumber(quint8 seqNumber)
{
    if ((seqNumber > 15) || (!isBitSet(byte(1), 6)))
        return;
    setByte(1, (byte(1) & 0xc3) | quint8(seqNumber << 2));
}

QByteArray QKnxNpdu::data() const
{
    if (size() < 3)
        return {};

    QByteArray bytes;
    switch (applicationControlField()) {
    case ApplicationControlField::GroupValueResponse:
    case ApplicationControlField::GroupValueWrite:
        if (size() > 3)
            break;

    case ApplicationControlField::AdcRead:
    case ApplicationControlField::AdcResponse:
    case ApplicationControlField::MemoryRead:
    case ApplicationControlField::MemoryResponse:
    case ApplicationControlField::MemoryWrite:
    case ApplicationControlField::DeviceDescriptorRead:
    case ApplicationControlField::DeviceDescriptorResponse:
    case ApplicationControlField::Restart:
        bytes = QKnxUtils::QUint8::bytes(quint8(byte(2) & 0x3f)); // 6 bits from an optimized NPDU

    default:
        break;
    }

    const auto &tmp = ref(3);
    return bytes + tmp.bytes<QByteArray>(0, tmp.size());
}

void QKnxNpdu::setData(const QByteArray &data)
{
    auto apci = applicationControlField();
    auto apciBytes = QKnxUtils::QUint16::bytes<QVector<quint8>>(quint16(apci));

    resize(3); // always resize to minimum size
    setByte(2, apciBytes[1]); // and clear the possible 6 bits of the upper APCI byteToTest

    if (data.isEmpty()) {
        setByte(0, quint8(size() - 2));
        return; // no data, bytes got cleared before
    }

    auto remainingData = data;
    switch (apci) {
    case ApplicationControlField::GroupValueResponse:
    case ApplicationControlField::GroupValueWrite:
        if (data.size() > 1 || quint8(data[0]) > 0x3f)
            break;

    case ApplicationControlField::AdcRead:
    case ApplicationControlField::AdcResponse:
    case ApplicationControlField::MemoryRead:
    case ApplicationControlField::MemoryResponse:
    case ApplicationControlField::MemoryWrite:
    case ApplicationControlField::DeviceDescriptorRead:
    case ApplicationControlField::DeviceDescriptorResponse:
    case ApplicationControlField::Restart:
        setByte(2, apciBytes[1] | quint8(data[0]));
        remainingData = data.mid(1); Q_FALLTHROUGH();

    default:
        break;
    }

    appendBytes(remainingData);
    setByte(0, quint8(size() - 2));
}

QT_END_NAMESPACE