DELL
2024-01-10 554f43497fca806ef44491c7833e1b7ad7c7b285
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
/*
 * Copyright 2011-17 Fraunhofer ISE, energy & meteo Systems GmbH and other contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.openmuc.openiec61850;
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
 
import org.openmuc.jasn1.ber.ReverseByteArrayOutputStream;
import org.openmuc.jasn1.ber.types.BerBoolean;
import org.openmuc.jasn1.ber.types.BerInteger;
import org.openmuc.jasn1.ber.types.BerNull;
import org.openmuc.jasn1.ber.types.string.BerVisibleString;
import org.openmuc.josistack.AcseAssociation;
import org.openmuc.josistack.ByteBufferInputStream;
import org.openmuc.josistack.ClientAcseSap;
import org.openmuc.josistack.DecodingException;
import org.openmuc.openiec61850.internal.mms.asn1.AccessResult;
import org.openmuc.openiec61850.internal.mms.asn1.ConfirmedRequestPDU;
import org.openmuc.openiec61850.internal.mms.asn1.ConfirmedResponsePDU;
import org.openmuc.openiec61850.internal.mms.asn1.ConfirmedServiceRequest;
import org.openmuc.openiec61850.internal.mms.asn1.ConfirmedServiceResponse;
import org.openmuc.openiec61850.internal.mms.asn1.Data;
import org.openmuc.openiec61850.internal.mms.asn1.DefineNamedVariableListRequest;
import org.openmuc.openiec61850.internal.mms.asn1.DeleteNamedVariableListRequest;
import org.openmuc.openiec61850.internal.mms.asn1.DeleteNamedVariableListRequest.ListOfVariableListName;
import org.openmuc.openiec61850.internal.mms.asn1.DeleteNamedVariableListResponse;
import org.openmuc.openiec61850.internal.mms.asn1.GetNameListRequest;
import org.openmuc.openiec61850.internal.mms.asn1.GetNameListRequest.ObjectScope;
import org.openmuc.openiec61850.internal.mms.asn1.GetNameListResponse;
import org.openmuc.openiec61850.internal.mms.asn1.GetNamedVariableListAttributesRequest;
import org.openmuc.openiec61850.internal.mms.asn1.GetNamedVariableListAttributesResponse;
import org.openmuc.openiec61850.internal.mms.asn1.GetVariableAccessAttributesRequest;
import org.openmuc.openiec61850.internal.mms.asn1.Identifier;
import org.openmuc.openiec61850.internal.mms.asn1.InitiateRequestPDU;
import org.openmuc.openiec61850.internal.mms.asn1.InitiateResponsePDU;
import org.openmuc.openiec61850.internal.mms.asn1.Integer16;
import org.openmuc.openiec61850.internal.mms.asn1.Integer32;
import org.openmuc.openiec61850.internal.mms.asn1.Integer8;
import org.openmuc.openiec61850.internal.mms.asn1.MMSpdu;
import org.openmuc.openiec61850.internal.mms.asn1.ObjectClass;
import org.openmuc.openiec61850.internal.mms.asn1.ObjectName;
import org.openmuc.openiec61850.internal.mms.asn1.ParameterSupportOptions;
import org.openmuc.openiec61850.internal.mms.asn1.ReadRequest;
import org.openmuc.openiec61850.internal.mms.asn1.ReadResponse;
import org.openmuc.openiec61850.internal.mms.asn1.RejectPDU.RejectReason;
import org.openmuc.openiec61850.internal.mms.asn1.ServiceError.ErrorClass;
import org.openmuc.openiec61850.internal.mms.asn1.ServiceSupportOptions;
import org.openmuc.openiec61850.internal.mms.asn1.UnconfirmedPDU;
import org.openmuc.openiec61850.internal.mms.asn1.UnconfirmedService;
import org.openmuc.openiec61850.internal.mms.asn1.Unsigned32;
import org.openmuc.openiec61850.internal.mms.asn1.VariableAccessSpecification;
import org.openmuc.openiec61850.internal.mms.asn1.VariableDefs;
import org.openmuc.openiec61850.internal.mms.asn1.WriteRequest;
import org.openmuc.openiec61850.internal.mms.asn1.WriteRequest.ListOfData;
import org.openmuc.openiec61850.internal.mms.asn1.WriteResponse;
 
/**
 * Represents an association/connection to an IEC 61850 MMS server. An instance of <code>ClientAssociation</code> is
 * obtained using <code>ClientSap</code>. An association object can be used to execute the IEC 61850 ACSI services. Note
 * that not all ACSI services have a corresponding function in this API. For example all GetDirectory and GetDefinition
 * services are covered by <code>retrieveModel()</code>. The control services can be executed by using getDataValues and
 * setDataValues on the control objects in the data model.
 *
 */
public final class ClientAssociation {
 
    private static final Integer16 version = new Integer16(new byte[] { (byte) 0x01, (byte) 0x01 });
    private static final ParameterSupportOptions proposedParameterCbbBitString = new ParameterSupportOptions(
            new byte[] { 0x03, 0x05, (byte) 0xf1, 0x00 });
 
    private AcseAssociation acseAssociation = null;
    private final ClientReceiver clientReceiver;
 
    private final BlockingQueue<MMSpdu> incomingResponses = new LinkedBlockingQueue<>();
 
    private final ReverseByteArrayOutputStream reverseOStream = new ReverseByteArrayOutputStream(500, true);
 
    ServerModel serverModel;
 
    private int responseTimeout;
 
    private int invokeId = 0;
 
    private int negotiatedMaxPduSize;
    private ClientEventListener reportListener = null;
 
    private boolean closed = false;
 
    final class ClientReceiver extends Thread {
 
        private Integer expectedResponseId;
        private final ByteBuffer pduBuffer;
 
        private IOException lastIOException = null;
 
        public ClientReceiver(int maxMmsPduSize) {
            pduBuffer = ByteBuffer.allocate(maxMmsPduSize + 400);
        }
 
        @Override
        public void run() {
            try {
                while (true) {
 
                    pduBuffer.clear();
                    byte[] buffer;
                    try {
                        buffer = acseAssociation.receive(pduBuffer);
                    } catch (TimeoutException e) {
                        // Illegal state: A timeout exception was thrown.
                        throw new IllegalStateException();
                    } catch (DecodingException e) {
                        // Error decoding the OSI headers of the received packet
                        continue;
                    }
 
                    MMSpdu decodedResponsePdu = new MMSpdu();
                    try {
                        decodedResponsePdu.decode(new ByteArrayInputStream(buffer), null);
                    } catch (IOException e) {
                        // Error decoding the received MMS PDU
                        continue;
                    }
 
                    if (decodedResponsePdu.getUnconfirmedPDU() != null) {
                        if (decodedResponsePdu.getUnconfirmedPDU()
                                .getService()
                                .getInformationReport()
                                .getVariableAccessSpecification()
                                .getListOfVariable() != null) {
                            // Discarding LastApplError Report
                        }
                        else {
                            if (reportListener != null) {
                                final Report report = processReport(decodedResponsePdu);
 
                                Thread t1 = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        reportListener.newReport(report);
                                    }
                                });
                                t1.start();
                            }
                            else {
                                // discarding report because no ReportListener was registered.
                            }
                        }
                    }
                    else if (decodedResponsePdu.getRejectPDU() != null) {
                        synchronized (incomingResponses) {
                            if (expectedResponseId == null) {
                                // Discarding Reject MMS PDU because no listener for request was found.
                                continue;
                            }
                            else if (decodedResponsePdu.getRejectPDU().getOriginalInvokeID().value
                                    .intValue() != expectedResponseId) {
                                // Discarding Reject MMS PDU because no listener with fitting invokeID was found.
                                continue;
                            }
                            else {
                                try {
                                    incomingResponses.put(decodedResponsePdu);
                                } catch (InterruptedException e) {
                                }
                            }
                        }
                    }
                    else if (decodedResponsePdu.getConfirmedErrorPDU() != null) {
                        synchronized (incomingResponses) {
                            if (expectedResponseId == null) {
                                // Discarding ConfirmedError MMS PDU because no listener for request was found.
                                continue;
                            }
                            else if (decodedResponsePdu.getConfirmedErrorPDU().getInvokeID().value
                                    .intValue() != expectedResponseId) {
                                // Discarding ConfirmedError MMS PDU because no listener with fitting invokeID was
                                // found.
                                continue;
                            }
                            else {
                                try {
                                    incomingResponses.put(decodedResponsePdu);
                                } catch (InterruptedException e) {
                                }
                            }
                        }
                    }
                    else {
                        synchronized (incomingResponses) {
                            if (expectedResponseId == null) {
                                // Discarding ConfirmedResponse MMS PDU because no listener for request was found.
                                continue;
                            }
                            else if (decodedResponsePdu.getConfirmedResponsePDU().getInvokeID().value
                                    .intValue() != expectedResponseId) {
                                // Discarding ConfirmedResponse MMS PDU because no listener with fitting invokeID was
                                // found.
                                continue;
                            }
                            else {
                                try {
                                    incomingResponses.put(decodedResponsePdu);
                                } catch (InterruptedException e) {
                                }
                            }
                        }
 
                    }
                }
            } catch (IOException e) {
                close(e);
            } catch (Exception e) {
                close(new IOException("unexpected exception while receiving", e));
            }
        }
 
        public void setResponseExpected(int invokeId) {
            expectedResponseId = invokeId;
        }
 
        private void disconnect() {
            synchronized (this) {
                if (closed == false) {
                    closed = true;
                    acseAssociation.disconnect();
                    lastIOException = new IOException("Connection disconnected by client");
                    if (reportListener != null) {
                        Thread t1 = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                reportListener.associationClosed(lastIOException);
                            }
                        });
                        t1.start();
                    }
 
                    MMSpdu mmsPdu = new MMSpdu();
                    mmsPdu.setConfirmedRequestPDU(new ConfirmedRequestPDU());
                    try {
                        incomingResponses.put(mmsPdu);
                    } catch (InterruptedException e1) {
                    }
                }
            }
        }
 
        private void close(IOException e) {
            synchronized (this) {
                if (closed == false) {
                    closed = true;
                    acseAssociation.close();
                    lastIOException = e;
                    Thread t1 = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            reportListener.associationClosed(lastIOException);
                        }
                    });
                    t1.start();
 
                    MMSpdu mmsPdu = new MMSpdu();
                    mmsPdu.setConfirmedRequestPDU(new ConfirmedRequestPDU());
                    try {
                        incomingResponses.put(mmsPdu);
                    } catch (InterruptedException e1) {
                    }
                }
            }
        }
 
        IOException getLastIOException() {
            return lastIOException;
        }
 
        MMSpdu removeExpectedResponse() {
            synchronized (incomingResponses) {
                expectedResponseId = null;
                return incomingResponses.poll();
            }
        }
 
    }
 
    ClientAssociation(InetAddress address, int port, InetAddress localAddr, int localPort,
            String authenticationParameter, ClientAcseSap acseSap, int proposedMaxMmsPduSize,
            int proposedMaxServOutstandingCalling, int proposedMaxServOutstandingCalled,
            int proposedDataStructureNestingLevel, byte[] servicesSupportedCalling, int responseTimeout,
            int messageFragmentTimeout, ClientEventListener reportListener) throws IOException {
 
        this.responseTimeout = responseTimeout;
 
        acseSap.tSap.setMessageFragmentTimeout(messageFragmentTimeout);
        acseSap.tSap.setMessageTimeout(responseTimeout);
 
        negotiatedMaxPduSize = proposedMaxMmsPduSize;
 
        this.reportListener = reportListener;
 
        associate(address, port, localAddr, localPort, authenticationParameter, acseSap, proposedMaxMmsPduSize,
                proposedMaxServOutstandingCalling, proposedMaxServOutstandingCalled, proposedDataStructureNestingLevel,
                servicesSupportedCalling);
 
        acseAssociation.setMessageTimeout(0);
 
        clientReceiver = new ClientReceiver(negotiatedMaxPduSize);
        clientReceiver.start();
    }
 
    /**
     * Sets the response timeout. The response timeout is used whenever a request is sent to the server. The client will
     * wait for this amount of time for the server's response before throwing a ServiceError.TIMEOUT. Responses received
     * after the timeout will be automatically discarded.
     *
     * @param timeout
     *            the response timeout in milliseconds.
     */
    public void setResponseTimeout(int timeout) {
        responseTimeout = timeout;
    }
 
    /**
     * Gets the response timeout. The response timeout is used whenever a request is sent to the server. The client will
     * wait for this amount of time for the server's response before throwing a ServiceError.TIMEOUT. Responses received
     * after the timeout will be automatically discarded.
     *
     * @return the response timeout in milliseconds.
     */
    public int getResponseTimeout() {
        return responseTimeout;
    }
 
    private int getInvokeId() {
        invokeId = (invokeId + 1) % 2147483647;
        return invokeId;
    }
 
    private static ServiceError mmsDataAccessErrorToServiceError(BerInteger dataAccessError) {
 
        switch (dataAccessError.value.intValue()) {
        case 1:
            return new ServiceError(ServiceError.FAILED_DUE_TO_SERVER_CONSTRAINT,
                    "MMS DataAccessError: hardware-fault");
        case 2:
            return new ServiceError(ServiceError.INSTANCE_LOCKED_BY_OTHER_CLIENT,
                    "MMS DataAccessError: temporarily-unavailable");
        case 3:
            return new ServiceError(ServiceError.ACCESS_VIOLATION, "MMS DataAccessError: object-access-denied");
        case 5:
            return new ServiceError(ServiceError.PARAMETER_VALUE_INCONSISTENT, "MMS DataAccessError: invalid-address");
        case 7:
            return new ServiceError(ServiceError.TYPE_CONFLICT, "MMS DataAccessError: type-inconsistent");
        case 10:
            return new ServiceError(ServiceError.INSTANCE_NOT_AVAILABLE, "MMS DataAccessError: object-non-existent");
        case 11:
            return new ServiceError(ServiceError.PARAMETER_VALUE_INCONSISTENT,
                    "MMS DataAccessError: object-value-invalid");
        default:
            return new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "MMS DataAccessError: " + dataAccessError.value);
        }
 
    }
 
    private static void testForErrorResponse(MMSpdu mmsResponsePdu) throws ServiceError {
        if (mmsResponsePdu.getConfirmedErrorPDU() == null) {
            return;
        }
 
        ErrorClass errClass = mmsResponsePdu.getConfirmedErrorPDU().getServiceError().getErrorClass();
        if (errClass != null) {
            if (errClass.getAccess() != null) {
                if (errClass.getAccess().value.intValue() == 3) {
                    throw new ServiceError(ServiceError.ACCESS_VIOLATION,
                            "MMS confirmed error: class: \"access\", error code: \"object-access-denied\"");
                }
                else if (errClass.getAccess().value.intValue() == 2) {
 
                    throw new ServiceError(ServiceError.INSTANCE_NOT_AVAILABLE,
                            "MMS confirmed error: class: \"access\", error code: \"object-non-existent\"");
                }
            }
        }
 
        if (mmsResponsePdu.getConfirmedErrorPDU().getServiceError().getAdditionalDescription() != null) {
            throw new ServiceError(ServiceError.UNKNOWN, "MMS confirmed error. Description: "
                    + mmsResponsePdu.getConfirmedErrorPDU().getServiceError().getAdditionalDescription().toString());
        }
        throw new ServiceError(ServiceError.UNKNOWN, "MMS confirmed error.");
    }
 
    private static void testForRejectResponse(MMSpdu mmsResponsePdu) throws ServiceError {
        if (mmsResponsePdu.getRejectPDU() == null) {
            return;
        }
 
        RejectReason rejectReason = mmsResponsePdu.getRejectPDU().getRejectReason();
        if (rejectReason != null) {
            if (rejectReason.getPduError() != null) {
                if (rejectReason.getPduError().value.intValue() == 1) {
                    throw new ServiceError(ServiceError.PARAMETER_VALUE_INCONSISTENT,
                            "MMS reject: type: \"pdu-error\", reject code: \"invalid-pdu\"");
                }
            }
        }
        throw new ServiceError(ServiceError.UNKNOWN, "MMS confirmed error.");
    }
 
    private static void testForInitiateErrorResponse(MMSpdu mmsResponsePdu) throws ServiceError {
        if (mmsResponsePdu.getInitiateErrorPDU() != null) {
 
            ErrorClass errClass = mmsResponsePdu.getInitiateErrorPDU().getErrorClass();
            if (errClass != null) {
                if (errClass.getVmdState() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"vmd_state\" with val: " + errClass.getVmdState().value);
                }
                if (errClass.getApplicationReference() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"application_reference\" with val: "
                                    + errClass.getApplicationReference().value);
                }
                if (errClass.getDefinition() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"definition\" with val: " + errClass.getDefinition().value);
                }
                if (errClass.getResource() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"resource\" with val: " + errClass.getResource().value);
                }
                if (errClass.getService() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"service\" with val: " + errClass.getService().value);
                }
                if (errClass.getServicePreempt() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"service_preempt\" with val: " + errClass.getServicePreempt().value);
                }
                if (errClass.getTimeResolution() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"time_resolution\" with val: " + errClass.getTimeResolution().value);
                }
                if (errClass.getAccess() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"access\" with val: " + errClass.getAccess().value);
                }
                if (errClass.getInitiate() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"initiate\" with val: " + errClass.getInitiate().value);
                }
                if (errClass.getConclude() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"conclude\" with val: " + errClass.getConclude());
                }
                if (errClass.getCancel() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"cancel\" with val: " + errClass.getCancel().value);
                }
                if (errClass.getFile() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"file\" with val: " + errClass.getFile().value);
                }
                if (errClass.getOthers() != null) {
                    throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                            "error class \"others\" with val: " + errClass.getOthers().value);
                }
            }
 
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT, "unknown error class");
        }
    }
 
    private ConfirmedServiceResponse encodeWriteReadDecode(ConfirmedServiceRequest serviceRequest)
            throws ServiceError, IOException {
 
        int currentInvokeId = getInvokeId();
 
        ConfirmedRequestPDU confirmedRequestPdu = new ConfirmedRequestPDU();
        confirmedRequestPdu.setInvokeID(new Unsigned32(currentInvokeId));
        confirmedRequestPdu.setService(serviceRequest);
 
        MMSpdu requestPdu = new MMSpdu();
        requestPdu.setConfirmedRequestPDU(confirmedRequestPdu);
 
        reverseOStream.reset();
 
        try {
            requestPdu.encode(reverseOStream);
        } catch (Exception e) {
            IOException e2 = new IOException("Error encoding MmsPdu.", e);
            clientReceiver.close(e2);
            throw e2;
        }
 
        clientReceiver.setResponseExpected(currentInvokeId);
        try {
            acseAssociation.send(reverseOStream.getByteBuffer());
        } catch (IOException e) {
            IOException e2 = new IOException("Error sending packet.", e);
            clientReceiver.close(e2);
            throw e2;
        }
 
        MMSpdu decodedResponsePdu = null;
 
        try {
            if (responseTimeout == 0) {
                decodedResponsePdu = incomingResponses.take();
            }
            else {
                decodedResponsePdu = incomingResponses.poll(responseTimeout, TimeUnit.MILLISECONDS);
            }
        } catch (InterruptedException e) {
        }
 
        if (decodedResponsePdu == null) {
            decodedResponsePdu = clientReceiver.removeExpectedResponse();
            if (decodedResponsePdu == null) {
                throw new ServiceError(ServiceError.TIMEOUT);
            }
        }
 
        if (decodedResponsePdu.getConfirmedRequestPDU() != null) {
            incomingResponses.add(decodedResponsePdu);
            throw clientReceiver.getLastIOException();
        }
 
        testForInitiateErrorResponse(decodedResponsePdu);
        testForErrorResponse(decodedResponsePdu);
        testForRejectResponse(decodedResponsePdu);
 
        ConfirmedResponsePDU confirmedResponsePdu = decodedResponsePdu.getConfirmedResponsePDU();
        if (confirmedResponsePdu == null) {
            throw new IllegalStateException("Response PDU is not a confirmed response pdu");
        }
 
        return confirmedResponsePdu.getService();
 
    }
 
    private void associate(InetAddress address, int port, InetAddress localAddr, int localPort,
            String authenticationParameter, ClientAcseSap acseSap, int proposedMaxPduSize,
            int proposedMaxServOutstandingCalling, int proposedMaxServOutstandingCalled,
            int proposedDataStructureNestingLevel, byte[] servicesSupportedCalling) throws IOException {
 
        MMSpdu initiateRequestMMSpdu = constructInitRequestPdu(proposedMaxPduSize, proposedMaxServOutstandingCalling,
                proposedMaxServOutstandingCalled, proposedDataStructureNestingLevel, servicesSupportedCalling);
 
        ReverseByteArrayOutputStream reverseOStream = new ReverseByteArrayOutputStream(500, true);
        initiateRequestMMSpdu.encode(reverseOStream);
 
        try {
            acseAssociation = acseSap.associate(address, port, localAddr, localPort, authenticationParameter,
                    reverseOStream.getByteBuffer());
 
            ByteBuffer initResponse = acseAssociation.getAssociateResponseAPdu();
 
            MMSpdu initiateResponseMmsPdu = new MMSpdu();
 
            initiateResponseMmsPdu.decode(new ByteBufferInputStream(initResponse), null);
 
            handleInitiateResponse(initiateResponseMmsPdu, proposedMaxPduSize, proposedMaxServOutstandingCalling,
                    proposedMaxServOutstandingCalled, proposedDataStructureNestingLevel);
        } catch (IOException e) {
            if (acseAssociation != null) {
                acseAssociation.close();
            }
            throw e;
        }
    }
 
    private static MMSpdu constructInitRequestPdu(int proposedMaxPduSize, int proposedMaxServOutstandingCalling,
            int proposedMaxServOutstandingCalled, int proposedDataStructureNestingLevel,
            byte[] servicesSupportedCalling) {
 
        InitiateRequestPDU.InitRequestDetail initRequestDetail = new InitiateRequestPDU.InitRequestDetail();
        initRequestDetail.setProposedVersionNumber(version);
        initRequestDetail.setProposedParameterCBB(proposedParameterCbbBitString);
        initRequestDetail.setServicesSupportedCalling(new ServiceSupportOptions(servicesSupportedCalling, 85));
 
        InitiateRequestPDU initiateRequestPdu = new InitiateRequestPDU();
        initiateRequestPdu.setLocalDetailCalling(new Integer32(proposedMaxPduSize));
        initiateRequestPdu.setProposedMaxServOutstandingCalling(new Integer16(proposedMaxServOutstandingCalling));
        initiateRequestPdu.setProposedMaxServOutstandingCalled(new Integer16(proposedMaxServOutstandingCalled));
        initiateRequestPdu.setProposedDataStructureNestingLevel(new Integer8(proposedDataStructureNestingLevel));
        initiateRequestPdu.setInitRequestDetail(initRequestDetail);
 
        MMSpdu initiateRequestMMSpdu = new MMSpdu();
        initiateRequestMMSpdu.setInitiateRequestPDU(initiateRequestPdu);
 
        return initiateRequestMMSpdu;
    }
 
    private void handleInitiateResponse(MMSpdu responsePdu, int proposedMaxPduSize,
            int proposedMaxServOutstandingCalling, int proposedMaxServOutstandingCalled,
            int proposedDataStructureNestingLevel) throws IOException {
 
        if (responsePdu.getInitiateErrorPDU() != null) {
            throw new IOException("Got response error of class: " + responsePdu.getInitiateErrorPDU().getErrorClass());
        }
 
        if (responsePdu.getInitiateResponsePDU() == null) {
            acseAssociation.disconnect();
            throw new IOException("Error decoding InitiateResponse Pdu");
        }
 
        InitiateResponsePDU initiateResponsePdu = responsePdu.getInitiateResponsePDU();
 
        if (initiateResponsePdu.getLocalDetailCalled() != null) {
            negotiatedMaxPduSize = initiateResponsePdu.getLocalDetailCalled().intValue();
        }
 
        int negotiatedMaxServOutstandingCalling = initiateResponsePdu.getNegotiatedMaxServOutstandingCalling()
                .intValue();
        int negotiatedMaxServOutstandingCalled = initiateResponsePdu.getNegotiatedMaxServOutstandingCalled().intValue();
 
        int negotiatedDataStructureNestingLevel;
        if (initiateResponsePdu.getNegotiatedDataStructureNestingLevel() != null) {
            negotiatedDataStructureNestingLevel = initiateResponsePdu.getNegotiatedDataStructureNestingLevel()
                    .intValue();
        }
        else {
            negotiatedDataStructureNestingLevel = proposedDataStructureNestingLevel;
        }
 
        if (negotiatedMaxPduSize < ClientSap.MINIMUM_MMS_PDU_SIZE || negotiatedMaxPduSize > proposedMaxPduSize
                || negotiatedMaxServOutstandingCalling > proposedMaxServOutstandingCalling
                || negotiatedMaxServOutstandingCalling < 0
                || negotiatedMaxServOutstandingCalled > proposedMaxServOutstandingCalled
                || negotiatedMaxServOutstandingCalled < 0
                || negotiatedDataStructureNestingLevel > proposedDataStructureNestingLevel
                || negotiatedDataStructureNestingLevel < 0) {
            acseAssociation.disconnect();
            throw new IOException("Error negotiating parameters");
        }
 
        int version = initiateResponsePdu.getInitResponseDetail().getNegotiatedVersionNumber().intValue();
        if (version != 1) {
            throw new IOException("Unsupported version number was negotiated.");
        }
 
        byte[] servicesSupported = initiateResponsePdu.getInitResponseDetail().getServicesSupportedCalled().value;
        if ((servicesSupported[0] & 0x40) != 0x40) {
            throw new IOException("Obligatory services are not supported by the server.");
        }
    }
 
    /**
     * Parses the given SCL File and returns the server model that is described by it. This function can be used instead
     * of <code>retrieveModel</code> in order to get the server model that is needed to call the other ACSI services.
     *
     * @param sclFilePath
     *            the path to the SCL file that is to be parsed.
     * @return The ServerNode that is the root node of the complete server model.
     * @throws SclParseException
     *             if any kind of fatal error occurs in the parsing process.
     */
    public ServerModel getModelFromSclFile(String sclFilePath) throws SclParseException {
        List<ServerSap> serverSaps = ServerSap.getSapsFromSclFile(sclFilePath);
        if (serverSaps == null || serverSaps.size() == 0) {
            throw new SclParseException("No AccessPoint found in SCL file.");
        }
        serverModel = serverSaps.get(0).serverModel;
        return serverModel;
    }
 
    /**
     * Triggers all GetDirectory and GetDefinition ACSI services needed to get the complete server model. Because in MMS
     * SubDataObjects cannot be distinguished from Constructed Data Attributes they will always be represented as
     * Constructed Data Attributes in the returned model.
     *
     * @return the ServerModel that is the root node of the complete server model.
     * @throws ServiceError
     *             if a ServiceError occurs while calling any of the ASCI services.
     * @throws IOException
     *             if a fatal association error occurs. The association object will be closed and can no longer be used
     *             after this exception is thrown.
     */
    public ServerModel retrieveModel() throws ServiceError, IOException {
 
        List<String> ldNames = retrieveLogicalDevices();
        List<List<String>> lnNames = new ArrayList<>(ldNames.size());
        //System.out.println("List<String> ldNames = retrieveLogicalDevices();");
        for (int i = 0; i < ldNames.size(); i++) {
            lnNames.add(retrieveLogicalNodeNames(ldNames.get(i)));
            //System.out.println(ldNames.get(i));
        }
        List<LogicalDevice> lds = new ArrayList<>();
        for (int i = 0; i < ldNames.size(); i++) {
            List<LogicalNode> lns = new ArrayList<>();
            for (int j = 0; j < lnNames.get(i).size(); j++) {
                lns.add(retrieveDataDefinitions(new ObjectReference(ldNames.get(i) + "/" + lnNames.get(i).get(j))));
            }
            lds.add(new LogicalDevice(new ObjectReference(ldNames.get(i)), lns));
        }
 
        serverModel = new ServerModel(lds, null);
 
        updateDataSets();
 
        return serverModel;
    }
 
    private List<String> retrieveLogicalDevices() throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructGetServerDirectoryRequest();
        ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        return decodeGetServerDirectoryResponse(confirmedServiceResponse);
    }
 
    private ConfirmedServiceRequest constructGetServerDirectoryRequest() {
        ObjectClass objectClass = new ObjectClass();
        objectClass.setBasicObjectClass(new BerInteger(9));
 
        GetNameListRequest.ObjectScope objectScope = new GetNameListRequest.ObjectScope();
        objectScope.setVmdSpecific(new BerNull());
 
        GetNameListRequest getNameListRequest = new GetNameListRequest();
        getNameListRequest.setObjectClass(objectClass);
        getNameListRequest.setObjectScope(objectScope);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setGetNameList(getNameListRequest);
 
        return confirmedServiceRequest;
    }
 
    private List<String> decodeGetServerDirectoryResponse(ConfirmedServiceResponse confirmedServiceResponse)
            throws ServiceError {
 
        if (confirmedServiceResponse.getGetNameList() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "Error decoding Get Server Directory Response Pdu");
        }
 
        List<Identifier> identifiers = confirmedServiceResponse.getGetNameList().getListOfIdentifier().getIdentifier();
        ArrayList<String> objectRefs = new ArrayList<>(); // ObjectReference[identifiers.size()];
 
        for (BerVisibleString identifier : identifiers) {
            objectRefs.add(identifier.toString());
        }
 
        return objectRefs;
    }
 
    private List<String> retrieveLogicalNodeNames(String ld) throws ServiceError, IOException {
        List<String> lns = new LinkedList<>();
        String continueAfterRef = "";
        do {
            ConfirmedServiceRequest serviceRequest = constructGetDirectoryRequest(ld, continueAfterRef, true);
            ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
            continueAfterRef = decodeGetDirectoryResponse(confirmedServiceResponse, lns);
 
        } while (continueAfterRef != "");
        return lns;
    }
 
    private ConfirmedServiceRequest constructGetDirectoryRequest(String ldRef, String continueAfter,
            boolean logicalDevice) {
 
        ObjectClass objectClass = new ObjectClass();
 
        if (logicalDevice) {
            objectClass.setBasicObjectClass(new BerInteger(0));
        }
        else { // for data sets
            objectClass.setBasicObjectClass(new BerInteger(2));
        }
 
        GetNameListRequest getNameListRequest = null;
 
        ObjectScope objectScopeChoiceType = new ObjectScope();
        objectScopeChoiceType.setDomainSpecific(new Identifier(ldRef.getBytes()));
 
        getNameListRequest = new GetNameListRequest();
        getNameListRequest.setObjectClass(objectClass);
        getNameListRequest.setObjectScope(objectScopeChoiceType);
        if (continueAfter != "") {
            getNameListRequest.setContinueAfter(new Identifier(continueAfter.getBytes()));
        }
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setGetNameList(getNameListRequest);
        return confirmedServiceRequest;
 
    }
 
    /**
     * Decodes an MMS response which contains the structure of a LD and its LNs including names of DOs.
     */
    private String decodeGetDirectoryResponse(ConfirmedServiceResponse confirmedServiceResponse, List<String> lns)
            throws ServiceError {
 
        if (confirmedServiceResponse.getGetNameList() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "decodeGetLDDirectoryResponse: Error decoding server response");
        }
 
        GetNameListResponse getNameListResponse = confirmedServiceResponse.getGetNameList();
 
        List<Identifier> identifiers = getNameListResponse.getListOfIdentifier().getIdentifier();
 
        if (identifiers.size() == 0) {
            throw new ServiceError(ServiceError.INSTANCE_NOT_AVAILABLE,
                    "decodeGetLDDirectoryResponse: Instance not available");
        }
 
        BerVisibleString identifier = null;
        Iterator<Identifier> it = identifiers.iterator();
 
        String idString;
 
        while (it.hasNext()) {
            identifier = it.next();
            idString = identifier.toString();
 
            if (idString.indexOf('$') == -1) {
                lns.add(idString);
            }
        }
 
        if (getNameListResponse.getMoreFollows() != null && getNameListResponse.getMoreFollows().value == false) {
            return "";
        }
        else {
            return identifier.toString();
        }
    }
 
    private LogicalNode retrieveDataDefinitions(ObjectReference lnRef) throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructGetDataDefinitionRequest(lnRef);
        ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        return decodeGetDataDefinitionResponse(confirmedServiceResponse, lnRef);
    }
 
    private ConfirmedServiceRequest constructGetDataDefinitionRequest(ObjectReference lnRef) {
 
        ObjectName.DomainSpecific domainSpec = new ObjectName.DomainSpecific();
        domainSpec.setDomainID(new Identifier(lnRef.get(0).getBytes()));
        domainSpec.setItemID(new Identifier(lnRef.get(1).getBytes()));
 
        ObjectName objectName = new ObjectName();
        objectName.setDomainSpecific(domainSpec);
 
        GetVariableAccessAttributesRequest getVariableAccessAttributesRequest = new GetVariableAccessAttributesRequest();
        getVariableAccessAttributesRequest.setName(objectName);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setGetVariableAccessAttributes(getVariableAccessAttributesRequest);
 
        return confirmedServiceRequest;
    }
 
    private LogicalNode decodeGetDataDefinitionResponse(ConfirmedServiceResponse confirmedServiceResponse,
            ObjectReference lnRef) throws ServiceError {
 
        return DataDefinitionResParser.parseGetDataDefinitionResponse(confirmedServiceResponse, lnRef);
    }
 
    /**
     * The implementation of the GetDataValues ACSI service. Will send an MMS read request for the given model node.
     * After a successful return, the Basic Data Attributes of the passed model node will contain the values read. If
     * one of the Basic Data Attributes cannot be read then none of the values will be read and a
     * <code>ServiceError</code> will be thrown.
     *
     * @param modelNode
     *            the functionally constrained model node that is to be read.
     * @throws ServiceError
     *             if a ServiceError is returned by the server.
     * @throws IOException
     *             if a fatal association error occurs. The association object will be closed and can no longer be used
     *             after this exception is thrown.
     */
    public void getDataValues(FcModelNode modelNode) throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructGetDataValuesRequest(modelNode);
        ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        decodeGetDataValuesResponse(confirmedServiceResponse, modelNode);
    }
 
    /**
     * Will update all data inside the model except for control variables (those that have FC=CO). Control variables are
     * not meant to be read. Update is done by calling getDataValues on the FCDOs below the Logical Nodes.
     *
     * @throws ServiceError
     *             if a ServiceError is returned by the server.
     * @throws IOException
     *             if a fatal association error occurs. The association object will be closed and can no longer be used
     *             after this exception is thrown.
     */
    public void getAllDataValues() throws ServiceError, IOException {
        for (ModelNode logicalDevice : serverModel.getChildren()) {
            for (ModelNode logicalNode : logicalDevice.getChildren()) {
                for (ModelNode dataObject : logicalNode.getChildren()) {
                    FcModelNode fcdo = (FcModelNode) dataObject;
                    if (fcdo.getFc() != Fc.CO && fcdo.getFc() != Fc.SE) {
                        try {
                            getDataValues(fcdo);
                        } catch (ServiceError e) {
                            throw new ServiceError(e.getErrorCode(), "service error retrieving " + fcdo.getReference()
                                    + "[" + fcdo.getFc() + "]" + ", " + e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }
 
    private ConfirmedServiceRequest constructGetDataValuesRequest(FcModelNode modelNode) {
        VariableAccessSpecification varAccessSpec = constructVariableAccessSpecification(modelNode);
 
        ReadRequest readRequest = new ReadRequest();
        readRequest.setVariableAccessSpecification(varAccessSpec);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setRead(readRequest);
 
        return confirmedServiceRequest;
    }
 
    private void decodeGetDataValuesResponse(ConfirmedServiceResponse confirmedServiceResponse, ModelNode modelNode)
            throws ServiceError {
 
        if (confirmedServiceResponse.getRead() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "Error decoding GetDataValuesReponsePdu");
        }
 
        List<AccessResult> listOfAccessResults = confirmedServiceResponse.getRead()
                .getListOfAccessResult()
                .getAccessResult();
 
        if (listOfAccessResults.size() != 1) {
            throw new ServiceError(ServiceError.PARAMETER_VALUE_INAPPROPRIATE, "Multiple results received.");
        }
 
        AccessResult accRes = listOfAccessResults.get(0);
 
        if (accRes.getFailure() != null) {
            throw mmsDataAccessErrorToServiceError(accRes.getFailure());
        }
        /*
        BdaFloat32 b_32 = new BdaFloat32(modelNode.getReference(), Fc.SP, null, false, false);
        b_32.setValue(accRes.getSuccess().getFloatingPoint().value);
        System.out.println(modelNode.getReference().toString() + " = " + b_32.getFloat());
        */
        modelNode.setValueFromMmsDataObj(accRes.getSuccess());
    }
 
    /**
     * The implementation of the SetDataValues ACSI service. Will send an MMS write request with the values of all Basic
     * Data Attributes of the given model node. Will simply return if all values have been successfully written. If one
     * of the Basic Data Attributes could not be written then a <code>ServiceError</code> will be thrown. In this case
     * it is not possible to find out which of several Basic Data Attributes could not be written.
     *
     * @param modelNode
     *            the functionally constrained model node that is to be written.
     * @throws ServiceError
     *             if a ServiceError is returned by the server.
     * @throws IOException
     *             if a fatal association error occurs. The association object will be closed and can no longer be used
     *             after this exception is thrown.
     */
    public void setDataValues(FcModelNode modelNode) throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructSetDataValuesRequest(modelNode);
        ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        decodeSetDataValuesResponse(confirmedServiceResponse);
    }
 
    private ConfirmedServiceRequest constructSetDataValuesRequest(FcModelNode modelNode) throws ServiceError {
 
        VariableAccessSpecification variableAccessSpecification = constructVariableAccessSpecification(modelNode);
 
        ListOfData listOfData = new ListOfData();
        List<Data> dataList = listOfData.getData();
        dataList.add(modelNode.getMmsDataObj());
 
        WriteRequest writeRequest = new WriteRequest();
        writeRequest.setListOfData(listOfData);
        writeRequest.setVariableAccessSpecification(variableAccessSpecification);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setWrite(writeRequest);
 
        return confirmedServiceRequest;
    }
 
    private VariableAccessSpecification constructVariableAccessSpecification(FcModelNode modelNode) {
        VariableDefs listOfVariable = new VariableDefs();
 
        List<VariableDefs.SEQUENCE> variableDefsSeqOf = listOfVariable.getSEQUENCE();
        variableDefsSeqOf.add(modelNode.getMmsVariableDef());
 
        VariableAccessSpecification variableAccessSpecification = new VariableAccessSpecification();
        variableAccessSpecification.setListOfVariable(listOfVariable);
 
        return variableAccessSpecification;
    }
 
    private void decodeSetDataValuesResponse(ConfirmedServiceResponse confirmedServiceResponse) throws ServiceError {
 
        WriteResponse writeResponse = confirmedServiceResponse.getWrite();
 
        if (writeResponse == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "SetDataValuesResponse: improper response");
        }
 
        WriteResponse.CHOICE subChoice = writeResponse.getCHOICE().get(0);
 
        if (subChoice.getFailure() != null) {
            throw mmsDataAccessErrorToServiceError(subChoice.getFailure());
        }
    }
 
    /**
     * This function will get the definition of all persistent DataSets from the server and update the DataSets in the
     * ServerModel that were returned by the retrieveModel() or getModelFromSclFile() functions. It will delete DataSets
     * that have been deleted since the last update and add any new DataSets
     *
     * @throws ServiceError
     *             if a ServiceError is returned by the server.
     * @throws IOException
     *             if a fatal association error occurs. The association object will be closed and can no longer be used
     *             after this exception is thrown.
     */
    public void updateDataSets() throws ServiceError, IOException {
 
        if (serverModel == null) {
            throw new IllegalStateException(
                    "Before calling this function you have to get the ServerModel using the retrieveModel() function");
        }
 
        Collection<ModelNode> lds = serverModel.getChildren();
 
        for (ModelNode ld : lds) {
            ConfirmedServiceRequest serviceRequest = constructGetDirectoryRequest(ld.getName(), "", false);
            ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
            decodeAndRetrieveDsNamesAndDefinitions(confirmedServiceResponse, (LogicalDevice) ld);
        }
    }
 
    private void decodeAndRetrieveDsNamesAndDefinitions(ConfirmedServiceResponse confirmedServiceResponse,
            LogicalDevice ld) throws ServiceError, IOException {
 
        if (confirmedServiceResponse.getGetNameList() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "decodeGetDataSetResponse: Error decoding server response");
        }
 
        GetNameListResponse getNameListResponse = confirmedServiceResponse.getGetNameList();
 
        List<Identifier> identifiers = getNameListResponse.getListOfIdentifier().getIdentifier();
 
        if (identifiers.size() == 0) {
            return;
        }
 
        for (Identifier identifier : identifiers) {
            // TODO delete DataSets that no longer exist
            getDataSetDirectory(identifier, ld);
        }
 
        if (getNameListResponse.getMoreFollows() != null && getNameListResponse.getMoreFollows().value == true) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT);
        }
    }
 
    private void getDataSetDirectory(Identifier dsId, LogicalDevice ld) throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructGetDataSetDirectoryRequest(dsId, ld);
        ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        decodeGetDataSetDirectoryResponse(confirmedServiceResponse, dsId, ld);
    }
 
    private ConfirmedServiceRequest constructGetDataSetDirectoryRequest(Identifier dsId, LogicalDevice ld)
            throws ServiceError {
        ObjectName.DomainSpecific domainSpecificObjectName = new ObjectName.DomainSpecific();
        domainSpecificObjectName.setDomainID(new Identifier(ld.getName().getBytes()));
        domainSpecificObjectName.setItemID(dsId);
 
        GetNamedVariableListAttributesRequest dataSetObj = new GetNamedVariableListAttributesRequest();
        dataSetObj.setDomainSpecific(domainSpecificObjectName);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setGetNamedVariableListAttributes(dataSetObj);
 
        return confirmedServiceRequest;
    }
 
    private void decodeGetDataSetDirectoryResponse(ConfirmedServiceResponse confirmedServiceResponse,
            BerVisibleString dsId, LogicalDevice ld) throws ServiceError {
 
        if (confirmedServiceResponse.getGetNamedVariableListAttributes() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "decodeGetDataSetDirectoryResponse: Error decoding server response");
        }
 
        GetNamedVariableListAttributesResponse getNamedVariableListAttResponse = confirmedServiceResponse
                .getGetNamedVariableListAttributes();
        boolean deletable = getNamedVariableListAttResponse.getMmsDeletable().value;
        List<VariableDefs.SEQUENCE> variables = getNamedVariableListAttResponse.getListOfVariable().getSEQUENCE();
 
        if (variables.size() == 0) {
            throw new ServiceError(ServiceError.INSTANCE_NOT_AVAILABLE,
                    "decodeGetDataSetDirectoryResponse: Instance not available");
        }
 
        List<FcModelNode> dsMems = new ArrayList<>();
 
        for (VariableDefs.SEQUENCE variableDef : variables) {
 
            FcModelNode member;
            // TODO remove this try catch statement once all possible FCs are
            // supported
            // it is only there so that Functional Constraints such as GS will
            // be ignored and DataSet cotaining elements with these FCs are
            // ignored and not created.
            try {
                member = serverModel.getNodeFromVariableDef(variableDef);
            } catch (ServiceError e) {
                return;
            }
            if (member == null) {
                throw new ServiceError(ServiceError.INSTANCE_NOT_AVAILABLE,
                        "decodeGetDataSetDirectoryResponse: data set memeber does not exist, you might have to call retrieveModel first");
            }
            dsMems.add(member);
        }
 
        String dsObjRef = ld.getName() + "/" + dsId.toString().replace('$', '.');
 
        DataSet dataSet = new DataSet(dsObjRef, dsMems, deletable);
 
        if (ld.getChild(dsId.toString().substring(0, dsId.toString().indexOf('$'))) == null) {
            throw new ServiceError(ServiceError.INSTANCE_NOT_AVAILABLE,
                    "decodeGetDataSetDirectoryResponse: LN for returned DataSet is not available");
        }
 
        DataSet existingDs = serverModel.getDataSet(dsObjRef);
        if (existingDs == null) {
            serverModel.addDataSet(dataSet);
        }
        else if (!existingDs.isDeletable()) {
            return;
        }
        else {
            serverModel.removeDataSet(dsObjRef.toString());
            serverModel.addDataSet(dataSet);
        }
 
    }
 
    /**
     * The client should create the data set first and add it to either the non-persistent list or to the model. Then it
     * should call this method for creation on the server side
     *
     * @param dataSet
     *            the data set to be created on the server side
     * @throws ServiceError
     *             if a ServiceError is returned by the server.
     * @throws IOException
     *             if a fatal IO error occurs. The association object will be closed and can no longer be used after
     *             this exception is thrown.
     */
    public void createDataSet(DataSet dataSet) throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructCreateDataSetRequest(dataSet);
        encodeWriteReadDecode(serviceRequest);
        handleCreateDataSetResponse(dataSet);
    }
 
    /**
     * dsRef = either LD/LN.DataSetName (persistent) or @DataSetname (non-persistent) Names in dsMemberRef should be in
     * the form: LD/LNName.DoName or LD/LNName.DoName.DaName
     */
    private ConfirmedServiceRequest constructCreateDataSetRequest(DataSet dataSet) throws ServiceError {
 
        VariableDefs listOfVariable = new VariableDefs();
 
        List<VariableDefs.SEQUENCE> variableDefs = listOfVariable.getSEQUENCE();
        for (FcModelNode dsMember : dataSet) {
            variableDefs.add(dsMember.getMmsVariableDef());
        }
 
        DefineNamedVariableListRequest createDSRequest = new DefineNamedVariableListRequest();
        createDSRequest.setVariableListName(dataSet.getMmsObjectName());
        createDSRequest.setListOfVariable(listOfVariable);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setDefineNamedVariableList(createDSRequest);
 
        return confirmedServiceRequest;
    }
 
    private void handleCreateDataSetResponse(DataSet dataSet) throws ServiceError {
        serverModel.addDataSet(dataSet);
    }
 
    public void deleteDataSet(DataSet dataSet) throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructDeleteDataSetRequest(dataSet);
        ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        decodeDeleteDataSetResponse(confirmedServiceResponse, dataSet);
    }
 
    private ConfirmedServiceRequest constructDeleteDataSetRequest(DataSet dataSet) throws ServiceError {
 
        ListOfVariableListName listOfVariableListName = new ListOfVariableListName();
 
        List<ObjectName> objectList = listOfVariableListName.getObjectName();
        objectList.add(dataSet.getMmsObjectName());
 
        DeleteNamedVariableListRequest requestDeleteDS = new DeleteNamedVariableListRequest();
        requestDeleteDS.setListOfVariableListName(listOfVariableListName);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setDeleteNamedVariableList(requestDeleteDS);
 
        return confirmedServiceRequest;
    }
 
    private void decodeDeleteDataSetResponse(ConfirmedServiceResponse confirmedServiceResponse, DataSet dataSet)
            throws ServiceError {
 
        if (confirmedServiceResponse.getDeleteNamedVariableList() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "decodeDeleteDataSetResponse: Error decoding server response");
        }
 
        DeleteNamedVariableListResponse deleteNamedVariableListResponse = confirmedServiceResponse
                .getDeleteNamedVariableList();
 
        if (deleteNamedVariableListResponse.getNumberDeleted().intValue() != 1) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT, "number deleted not 1");
        }
 
        if (serverModel.removeDataSet(dataSet.getReferenceStr()) == null) {
            throw new ServiceError(ServiceError.UNKNOWN, "unable to delete dataset locally");
        }
 
    }
 
    /**
     * The implementation of the GetDataSetValues ACSI service. After a successful return, the Basic Data Attributes of
     * the data set members will contain the values read. If one of the data set members could not be read, this will be
     * indicated in the returned list. The returned list will have the same size as the member list of the data set. For
     * each member it will contain <code>null</code> if reading was successful and a ServiceError if reading of this
     * member failed.
     *
     * @param dataSet
     *            the DataSet that is to be read.
     * @return a list indicating ServiceErrors that may have occurred.
     * @throws IOException
     *             if a fatal IO error occurs. The association object will be closed and can no longer be used after
     *             this exception is thrown.
     */
    public List<ServiceError> getDataSetValues(DataSet dataSet) throws IOException {
 
        ConfirmedServiceResponse confirmedServiceResponse;
        try {
            ConfirmedServiceRequest serviceRequest = constructGetDataSetValuesRequest(dataSet);
            confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        } catch (ServiceError e) {
            int dataSetSize = dataSet.getMembers().size();
            List<ServiceError> serviceErrors = new ArrayList<>(dataSetSize);
            for (int i = 0; i < dataSetSize; i++) {
                serviceErrors.add(e);
            }
            return serviceErrors;
        }
        return decodeGetDataSetValuesResponse(confirmedServiceResponse, dataSet);
    }
 
    private ConfirmedServiceRequest constructGetDataSetValuesRequest(DataSet dataSet) throws ServiceError {
 
        VariableAccessSpecification varAccSpec = new VariableAccessSpecification();
        varAccSpec.setVariableListName(dataSet.getMmsObjectName());
 
        ReadRequest getDataSetValuesRequest = new ReadRequest();
        getDataSetValuesRequest.setSpecificationWithResult(new BerBoolean(true));
        getDataSetValuesRequest.setVariableAccessSpecification(varAccSpec);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setRead(getDataSetValuesRequest);
 
        return confirmedServiceRequest;
    }
 
    private List<ServiceError> decodeGetDataSetValuesResponse(ConfirmedServiceResponse confirmedServiceResponse,
            DataSet ds) {
 
        int dataSetSize = ds.getMembers().size();
        List<ServiceError> serviceErrors = new ArrayList<>(dataSetSize);
 
        if (confirmedServiceResponse.getRead() == null) {
            ServiceError serviceError = new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "Error decoding GetDataValuesReponsePdu");
            for (int i = 0; i < dataSetSize; i++) {
                serviceErrors.add(serviceError);
            }
            return serviceErrors;
        }
 
        ReadResponse readResponse = confirmedServiceResponse.getRead();
        List<AccessResult> listOfAccessResults = readResponse.getListOfAccessResult().getAccessResult();
 
        if (listOfAccessResults.size() != ds.getMembers().size()) {
            ServiceError serviceError = new ServiceError(ServiceError.PARAMETER_VALUE_INAPPROPRIATE,
                    "Number of AccessResults does not match the number of DataSet members.");
            for (int i = 0; i < dataSetSize; i++) {
                serviceErrors.add(serviceError);
            }
            return serviceErrors;
        }
 
        Iterator<AccessResult> accessResultIterator = listOfAccessResults.iterator();
 
        for (FcModelNode dsMember : ds) {
            AccessResult accessResult = accessResultIterator.next();
            if (accessResult.getSuccess() != null) {
                try {
                    dsMember.setValueFromMmsDataObj(accessResult.getSuccess());
                } catch (ServiceError e) {
                    serviceErrors.add(e);
                }
                serviceErrors.add(null);
            }
            else {
                serviceErrors.add(mmsDataAccessErrorToServiceError(accessResult.getFailure()));
            }
        }
 
        return serviceErrors;
    }
 
    public List<ServiceError> setDataSetValues(DataSet dataSet) throws ServiceError, IOException {
        ConfirmedServiceRequest serviceRequest = constructSetDataSetValues(dataSet);
        ConfirmedServiceResponse confirmedServiceResponse = encodeWriteReadDecode(serviceRequest);
        return decodeSetDataSetValuesResponse(confirmedServiceResponse);
    }
 
    private ConfirmedServiceRequest constructSetDataSetValues(DataSet dataSet) throws ServiceError {
        VariableAccessSpecification varAccessSpec = new VariableAccessSpecification();
        varAccessSpec.setVariableListName(dataSet.getMmsObjectName());
 
        ListOfData listOfData = new ListOfData();
        List<Data> dataList = listOfData.getData();
 
        for (ModelNode member : dataSet) {
            dataList.add(member.getMmsDataObj());
        }
 
        WriteRequest writeRequest = new WriteRequest();
        writeRequest.setVariableAccessSpecification(varAccessSpec);
        writeRequest.setListOfData(listOfData);
 
        ConfirmedServiceRequest confirmedServiceRequest = new ConfirmedServiceRequest();
        confirmedServiceRequest.setWrite(writeRequest);
 
        return confirmedServiceRequest;
    }
 
    private List<ServiceError> decodeSetDataSetValuesResponse(ConfirmedServiceResponse confirmedServiceResponse)
            throws ServiceError {
 
        if (confirmedServiceResponse.getWrite() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "Error decoding SetDataSetValuesReponsePdu");
        }
 
        WriteResponse writeResponse = confirmedServiceResponse.getWrite();
        List<WriteResponse.CHOICE> writeResChoiceType = writeResponse.getCHOICE();
        List<ServiceError> serviceErrors = new ArrayList<>(writeResChoiceType.size());
 
        for (WriteResponse.CHOICE accessResult : writeResChoiceType) {
            if (accessResult.getSuccess() != null) {
                serviceErrors.add(null);
            }
            else {
                serviceErrors.add(mmsDataAccessErrorToServiceError(accessResult.getFailure()));
            }
        }
        return serviceErrors;
 
    }
 
    public void getRcbValues(Rcb rcb) throws ServiceError, IOException {
        getDataValues(rcb);
    }
 
    public void reserveUrcb(Urcb urcb) throws ServiceError, IOException {
        BdaBoolean resvBda = urcb.getResv();
        resvBda.setValue(true);
        setDataValues(resvBda);
    }
 
    public void reserveBrcb(Brcb brcb, short resvTime) throws ServiceError, IOException {
        BdaInt16 resvTmsBda = brcb.getResvTms();
        resvTmsBda.setValue(resvTime);
        setDataValues(resvTmsBda);
    }
 
    public void cancelUrcbReservation(Urcb urcb) throws ServiceError, IOException {
        BdaBoolean resvBda = urcb.getResv();
        resvBda.setValue(false);
        setDataValues(resvBda);
    }
 
    public void enableReporting(Rcb rcb) throws ServiceError, IOException {
        BdaBoolean rptEnaBda = rcb.getRptEna();
        rptEnaBda.setValue(true);
        setDataValues(rptEnaBda);
    }
 
    public void disableReporting(Rcb rcb) throws ServiceError, IOException {
        BdaBoolean rptEnaBda = rcb.getRptEna();
        rptEnaBda.setValue(false);
        setDataValues(rptEnaBda);
    }
 
    public void startGi(Rcb rcb) throws ServiceError, IOException {
        BdaBoolean rptGiBda = (BdaBoolean) rcb.getChild("GI");
        rptGiBda.setValue(true);
        setDataValues(rptGiBda);
    }
 
    /**
     * Sets the selected values of the given report control block. Note that all these parameters may only be set if the
     * RCB has been reserved but reporting has not been enabled yet.
     * <p>
     * The data set reference as it is set in an RCB must contain a dollar sign instead of a dot to separate the logical
     * node from the data set name, e.g.: 'LDevice1/LNode$DataSetName'. Therefore his method will check the reference
     * for a dot and if necessary convert it to a '$' sign before sending the request to the server.
     * <p>
     * The parameters PurgeBuf, EntryId are only applicable if the given rcb is of type BRCB.
     * 
     *
     * @param rcb
     *            the report control block
     * @param setRptId
     *            whether to set the report ID
     * @param setDatSet
     *            whether to set the data set
     * @param setOptFlds
     *            whether to set the optional fields
     * @param setBufTm
     *            whether to set the buffer time
     * @param setTrgOps
     *            whether to set the trigger options
     * @param setIntgPd
     *            whether to set the integrity period
     * @param setPurgeBuf
     *            whether to set purge buffer
     * @param setEntryId
     *            whether to set the entry ID
     * @return a list indicating ServiceErrors that may have occurred.
     * @throws IOException
     *             if a fatal IO error occurs. The association object will be closed and can no longer be used after
     *             this exception is thrown.
     */
    public List<ServiceError> setRcbValues(Rcb rcb, boolean setRptId, boolean setDatSet, boolean setOptFlds,
            boolean setBufTm, boolean setTrgOps, boolean setIntgPd, boolean setPurgeBuf, boolean setEntryId)
            throws IOException {
 
        List<FcModelNode> parametersToSet = new ArrayList<>(6);
 
        if (setRptId == true) {
            parametersToSet.add(rcb.getRptId());
        }
        if (setDatSet == true) {
            rcb.getDatSet().setValue(rcb.getDatSet().getStringValue().replace('.', '$'));
            parametersToSet.add(rcb.getDatSet());
        }
        if (setOptFlds == true) {
            parametersToSet.add(rcb.getOptFlds());
        }
        if (setBufTm == true) {
            parametersToSet.add(rcb.getBufTm());
        }
        if (setTrgOps == true) {
            parametersToSet.add(rcb.getTrgOps());
        }
        if (setIntgPd == true) {
            parametersToSet.add(rcb.getIntgPd());
        }
        if (rcb instanceof Brcb) {
            Brcb brcb = (Brcb) rcb;
            if (setPurgeBuf == true) {
                parametersToSet.add(brcb.getPurgeBuf());
            }
            if (setEntryId == true) {
                parametersToSet.add(brcb.getEntryId());
            }
        }
 
        List<ServiceError> serviceErrors = new ArrayList<>(parametersToSet.size());
 
        for (FcModelNode child : parametersToSet) {
            try {
                setDataValues(child);
                serviceErrors.add(null);
            } catch (ServiceError e) {
                serviceErrors.add(e);
            }
        }
 
        return serviceErrors;
    }
 
    private Report processReport(MMSpdu mmsPdu) throws ServiceError {
 
        if (mmsPdu.getUnconfirmedPDU() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "getReport: Error decoding server response");
        }
 
        UnconfirmedPDU unconfirmedRes = mmsPdu.getUnconfirmedPDU();
 
        if (unconfirmedRes.getService() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "getReport: Error decoding server response");
        }
 
        UnconfirmedService unconfirmedServ = unconfirmedRes.getService();
 
        if (unconfirmedServ.getInformationReport() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "getReport: Error decoding server response");
        }
 
        List<AccessResult> listRes = unconfirmedServ.getInformationReport().getListOfAccessResult().getAccessResult();
 
        int index = 0;
 
        if (listRes.get(index).getSuccess().getVisibleString() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "processReport: report does not contain RptID");
        }
 
        String rptId = listRes.get(index++).getSuccess().getVisibleString().toString();
 
        if (listRes.get(index).getSuccess().getBitString() == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "processReport: report does not contain OptFlds");
        }
 
        BdaOptFlds optFlds = new BdaOptFlds(new ObjectReference("none"), null);
        optFlds.setValue(listRes.get(index++).getSuccess().getBitString().value);
 
        Integer sqNum = null;
        if (optFlds.isSequenceNumber()) {
            sqNum = listRes.get(index++).getSuccess().getUnsigned().intValue();
        }
 
        BdaEntryTime timeOfEntry = null;
        if (optFlds.isReportTimestamp()) {
            timeOfEntry = new BdaEntryTime(new ObjectReference("none"), null, "", false, false);
            timeOfEntry.setValueFromMmsDataObj(listRes.get(index++).getSuccess());
        }
 
        String dataSetRef = null;
        if (optFlds.isDataSetName()) {
            dataSetRef = (listRes.get(index++).getSuccess().getVisibleString().toString());
        }
        else {
            for (Urcb urcb : serverModel.getUrcbs()) {
                if ((urcb.getRptId() != null && urcb.getRptId().getStringValue().equals(rptId))
                        || urcb.getReference().toString().equals(rptId)) {
                    dataSetRef = urcb.getDatSet().getStringValue();
                    break;
                }
            }
            if (dataSetRef == null) {
                for (Brcb brcb : serverModel.getBrcbs()) {
                    if ((brcb.getRptId() != null && brcb.getRptId().getStringValue().equals(rptId))
                            || brcb.getReference().toString().equals(rptId)) {
                        dataSetRef = brcb.getDatSet().getStringValue();
                        break;
                    }
                }
            }
        }
        if (dataSetRef == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "unable to find RCB that matches the given RptID in the report.");
        }
        dataSetRef = dataSetRef.replace('$', '.');
 
        DataSet dataSet = serverModel.getDataSet(dataSetRef);
        if (dataSet == null) {
            throw new ServiceError(ServiceError.FAILED_DUE_TO_COMMUNICATIONS_CONSTRAINT,
                    "unable to find data set that matches the given data set reference of the report.");
        }
 
        Boolean bufOvfl = null;
        if (optFlds.isBufferOverflow()) {
            bufOvfl = (listRes.get(index++).getSuccess().getBool().value);
        }
 
        BdaOctetString entryId = null;
        if (optFlds.isEntryId()) {
            entryId = new BdaOctetString(new ObjectReference("none"), null, "", 8, false, false);
            entryId.setValue(listRes.get(index++).getSuccess().getOctetString().value);
        }
 
        Long confRev = null;
        if (optFlds.isConfigRevision()) {
            confRev = listRes.get(index++).getSuccess().getUnsigned().longValue();
        }
 
        Integer subSqNum = null;
        boolean moreSegmentsFollow = false;
        if (optFlds.isSegmentation()) {
            subSqNum = listRes.get(index++).getSuccess().getUnsigned().intValue();
            moreSegmentsFollow = listRes.get(index++).getSuccess().getBool().value;
        }
 
        boolean[] inclusionBitString = listRes.get(index++).getSuccess().getBitString().getValueAsBooleans();
        int numMembersReported = 0;
        for (boolean bit : inclusionBitString) {
            if (bit) {
                numMembersReported++;
            }
        }
 
        if (optFlds.isDataReference()) {
            // this is just to move the index to the right place
            // The next part will process the changes to the values
            // without the dataRefs
            index += numMembersReported;
        }
 
        List<FcModelNode> reportedDataSetMembers = new ArrayList<>(numMembersReported);
        int dataSetIndex = 0;
        for (FcModelNode dataSetMember : dataSet.getMembers()) {
            if (inclusionBitString[dataSetIndex]) {
                AccessResult accessRes = listRes.get(index++);
                FcModelNode dataSetMemberCopy = (FcModelNode) dataSetMember.copy();
                dataSetMemberCopy.setValueFromMmsDataObj(accessRes.getSuccess());
                reportedDataSetMembers.add(dataSetMemberCopy);
            }
            dataSetIndex++;
        }
 
        List<BdaReasonForInclusion> reasonCodes = null;
        if (optFlds.isReasonForInclusion()) {
            reasonCodes = new ArrayList<>(dataSet.getMembers().size());
            for (int i = 0; i < dataSet.getMembers().size(); i++) {
                if (inclusionBitString[i]) {
                    BdaReasonForInclusion reasonForInclusion = new BdaReasonForInclusion(null);
                    reasonCodes.add(reasonForInclusion);
                    byte[] reason = listRes.get(index++).getSuccess().getBitString().value;
                    reasonForInclusion.setValue(reason);
                }
 
            }
        }
 
        return new Report(rptId, sqNum, subSqNum, moreSegmentsFollow, dataSetRef, bufOvfl, confRev, timeOfEntry,
                entryId, inclusionBitString, reportedDataSetMembers, reasonCodes);
 
    }
 
    /**
     * Performs the Select ACSI Service of the control model on the given controllable Data Object (DO). By selecting a
     * controllable DO you can reserve it for exclusive control/operation. This service is only applicable if the
     * ctlModel Data Attribute is set to "sbo-with-normal-security" (2).
     *
     * The selection is canceled in one of the following events:
     * <ul>
     * <li>The "Cancel" ACSI service is issued.</li>
     * <li>The sboTimemout (select before operate timeout) runs out. If the given controlDataObject contains a
     * sboTimeout Data Attribute it is possible to change the timeout after which the selection/reservation is
     * automatically canceled by the server. Otherwise the timeout is a local issue of the server.</li>
     * <li>The connection to the server is closed.</li>
     * <li>An operate service failed because of some error</li>
     * <li>The sboClass is set to "operate-once" then the selection is also canceled after a successful operate service.
     * </li>
     * </ul>
     *
     * @param controlDataObject
     *            needs to be a controllable Data Object that contains a Data Attribute named "SBO".
     * @return false if the selection/reservation was not successful (because it is already selected by another client).
     *         Otherwise true is returned.
     * @throws ServiceError
     *             if a ServiceError is returned by the server.
     * @throws IOException
     *             if a fatal IO error occurs. The association object will be closed and can no longer be used after
     *             this exception is thrown.
     */
    public boolean select(FcModelNode controlDataObject) throws ServiceError, IOException {
        BdaVisibleString sbo;
        try {
            sbo = (BdaVisibleString) controlDataObject.getChild("SBO");
        } catch (Exception e) {
            throw new IllegalArgumentException("ModelNode needs to conain a child node named SBO in order to select");
        }
 
        getDataValues(sbo);
 
        if (sbo.getValue().length == 0) {
            return false;
        }
        return true;
 
    }
 
    /**
     * Executes the Operate ACSI Service on the given controllable Data Object (DO). The following subnodes of the given
     * control DO should be set according your needs before calling this function. (Note that you can probably leave
     * most attributes with their default value):
     * <ul>
     * <li>Oper.ctlVal - has to be set to actual control value that is to be written using the operate service.</li>
     * <li>Oper.operTm (type: BdaTimestamp) - is an optional sub data attribute of Oper (thus it may not exist). If it
     * exists it can be used to set the timestamp when the operation shall be performed by the server. Thus the server
     * will delay execution of the operate command until the given date is reached. Can be set to an empty byte array
     * (new byte[0]) or null so that the server executes the operate command immediately. This is also the default.</li>
     * <li>Oper.check (type: BdaCheck) is used to tell the server whether to perform the synchrocheck and
     * interlockcheck. By default they are turned off.</li>
     * <li>Oper.orign - contains the two data attributes orCat (origin category, type: BdaInt8) and orIdent (origin
     * identifier, type BdaOctetString). Origin is optionally reflected in the status Data Attribute controlDO.origin.
     * By reading this data attribute other clients can see who executed the last operate command. The default value for
     * orCat is 0 ("not-supported") and the default value for orIdent is ""(the empty string).</li>
     * <li>Oper.Test (BdaBoolean) - if true this operate command is sent for test purposes only. Default is false.</li>
     * </ul>
     *
     * All other operate parameters are automatically handled by this function.
     *
     * @param controlDataObject
     *            needs to be a controllable Data Object that contains a Data Attribute named "Oper".
     * @throws ServiceError
     *             if a ServiceError is returned by the server
     * @throws IOException
     *             if a fatal IO error occurs. The association object will be closed and can no longer be used after
     *             this exception is thrown.
     */
    public void operate(FcModelNode controlDataObject) throws ServiceError, IOException {
        ConstructedDataAttribute oper;
        try {
            oper = (ConstructedDataAttribute) controlDataObject.getChild("Oper");
        } catch (Exception e) {
            throw new IllegalArgumentException("ModelNode needs to conain a child node named \"Oper\".");
        }
 
        ((BdaInt8U) oper.getChild("ctlNum")).setValue((short) 1);
        ((BdaTimestamp) oper.getChild("T")).setDate(new Date(System.currentTimeMillis()));
 
        setDataValues(oper);
    }
 
    /**
     * Will close the connection simply by closing the TCP socket.
     */
    public void close() {
        clientReceiver.close(new IOException("Connection closed by client"));
    }
 
    /**
     * Will send a disconnect request first and then close the TCP socket.
     */
    public void disconnect() {
        clientReceiver.disconnect();
    }
 
}