-
Notifications
You must be signed in to change notification settings - Fork 87
/
ZclCluster.java
1640 lines (1479 loc) · 70.1 KB
/
ZclCluster.java
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
/**
* Copyright (c) 2016-2019 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.zcl;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zsmartsystems.zigbee.CommandResult;
import com.zsmartsystems.zigbee.IeeeAddress;
import com.zsmartsystems.zigbee.ZigBeeEndpoint;
import com.zsmartsystems.zigbee.ZigBeeEndpointAddress;
import com.zsmartsystems.zigbee.database.ZclAttributeDao;
import com.zsmartsystems.zigbee.database.ZclClusterDao;
import com.zsmartsystems.zigbee.internal.NotificationService;
import com.zsmartsystems.zigbee.zcl.clusters.general.ConfigureReportingCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.ConfigureReportingResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.DefaultResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverAttributesCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverAttributesExtended;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverAttributesExtendedResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverAttributesResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverCommandsGenerated;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverCommandsGeneratedResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverCommandsReceived;
import com.zsmartsystems.zigbee.zcl.clusters.general.DiscoverCommandsReceivedResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadAttributesCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadAttributesResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadAttributesStructuredCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadReportingConfigurationCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReadReportingConfigurationResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.ReportAttributesCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.WriteAttributesCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.WriteAttributesNoResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.WriteAttributesResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.WriteAttributesStructuredCommand;
import com.zsmartsystems.zigbee.zcl.clusters.general.WriteAttributesStructuredResponse;
import com.zsmartsystems.zigbee.zcl.clusters.general.WriteAttributesUndividedCommand;
import com.zsmartsystems.zigbee.zcl.field.AttributeInformation;
import com.zsmartsystems.zigbee.zcl.field.AttributeRecord;
import com.zsmartsystems.zigbee.zcl.field.AttributeReport;
import com.zsmartsystems.zigbee.zcl.field.AttributeReportingConfigurationRecord;
import com.zsmartsystems.zigbee.zcl.field.ReadAttributeStatusRecord;
import com.zsmartsystems.zigbee.zcl.field.WriteAttributeRecord;
import com.zsmartsystems.zigbee.zcl.protocol.ZclCommandDirection;
import com.zsmartsystems.zigbee.zcl.protocol.ZclDataType;
import com.zsmartsystems.zigbee.zdo.command.BindRequest;
import com.zsmartsystems.zigbee.zdo.command.UnbindRequest;
/**
* Base class for the ZCL Cluster
*
* @author Chris Jackson
*
*/
public abstract class ZclCluster {
/**
* The logger
*/
private Logger logger = LoggerFactory.getLogger(ZclCluster.class);
/**
* The {@link ZigBeeEndpoint} to which this cluster belongs
*/
private final ZigBeeEndpoint zigbeeEndpoint;
/**
* The ZCL cluster ID for this cluster
*/
protected int clusterId;
/**
* The name of this cluster
*/
protected final String clusterName;
/**
* Defines if the remote is a client (true) or server (false)
* The definition of the direction is based on the remote being the server. If it is really
* a server, then we need to reverse direction
*/
private boolean isClient = false;
/**
* The list of supported attributes in the remote device for this cluster.
* After initialisation, the list will contain an empty list. Once a successful call to
* {@link #discoverAttributes()} has been made, the list will reflect the attributes supported by the remote device.
*/
private final Set<Integer> supportedAttributes = new TreeSet<>();
/**
* A boolean used to record if the list of supported attributes has been recovered from the remote device. This is
* used to record the validity of {@link #supportedAttributes}
*/
private boolean supportedAttributesKnown = false;
/**
* The list of supported commands that the remote device can generate
*/
private final Set<Integer> supportedCommandsReceived = new HashSet<>();
/**
* The list of supported commands that the remote device can receive
*/
private final Set<Integer> supportedCommandsGenerated = new HashSet<>();
/**
* Set of listeners to receive notifications when an attribute updates its value
*/
private final Set<ZclAttributeListener> attributeListeners = new CopyOnWriteArraySet<>();
/**
* Set of listeners to receive notifications when a command is received
*/
private final Set<ZclCommandListener> commandListeners = new CopyOnWriteArraySet<>();
/**
* Map of client attributes supported by the cluster. This contains all attributes, even if they are not supported
* by the remote device. To check what attributes are supported by the remove device, us the
* {@link #discoverAttributes()} method followed by the {@link #getSupportedAttributes()} method.
*/
protected Map<Integer, ZclAttribute> clientAttributes = initializeClientAttributes();
/**
* Map of server attributes supported by the cluster. This contains all attributes, even if they are not supported
* by the remote device. To check what attributes are supported by the remove device, us the
* {@link #discoverAttributes()} method followed by the {@link #getSupportedAttributes()} method.
*/
protected Map<Integer, ZclAttribute> serverAttributes = initializeServerAttributes();
/**
* Map of server side commands supported by the cluster. This contains all server commands, even if they are not
* supported by the remote device.
*/
protected Map<Integer, Class<? extends ZclCommand>> serverCommands = initializeServerCommands();
/**
* Map of client side commands supported by the cluster. This contains all client commands, even if they are not
* supported by the remote device.
*/
protected Map<Integer, Class<? extends ZclCommand>> clientCommands = initializeClientCommands();
/**
* Map of the generic commands as implemented by all clusters
*/
protected static Map<Integer, Class<? extends ZclCommand>> genericCommands = new HashMap<>();
/**
* The {@link ZclAttributeNormalizer} is used to normalize attribute data types to ensure that data types are
* consistent with the ZCL definition. This ensures that the application can rely on consistent and deterministic
* data type when listening to attribute updates.
*/
private final ZclAttributeNormalizer normalizer;
/**
* If this cluster requires all frames to have APS security applied, then this will be true. Any frames not secured
* with the link key will be rejected and all frames sent will use APS encryption.
*/
private boolean apsSecurityRequired = false;
static {
genericCommands.put(0x0000, ReadAttributesCommand.class);
genericCommands.put(0x0001, ReadAttributesResponse.class);
genericCommands.put(0x0002, WriteAttributesCommand.class);
genericCommands.put(0x0003, WriteAttributesUndividedCommand.class);
genericCommands.put(0x0004, WriteAttributesResponse.class);
genericCommands.put(0x0005, WriteAttributesNoResponse.class);
genericCommands.put(0x0006, ConfigureReportingCommand.class);
genericCommands.put(0x0007, ConfigureReportingResponse.class);
genericCommands.put(0x0008, ReadReportingConfigurationCommand.class);
genericCommands.put(0x0009, ReadReportingConfigurationResponse.class);
genericCommands.put(0x000A, ReportAttributesCommand.class);
genericCommands.put(0x000B, DefaultResponse.class);
genericCommands.put(0x000C, DiscoverAttributesCommand.class);
genericCommands.put(0x000D, DiscoverAttributesResponse.class);
genericCommands.put(0x000E, ReadAttributesStructuredCommand.class);
genericCommands.put(0x000F, WriteAttributesStructuredCommand.class);
genericCommands.put(0x0010, WriteAttributesStructuredResponse.class);
genericCommands.put(0x0011, DiscoverCommandsReceived.class);
genericCommands.put(0x0012, DiscoverCommandsReceivedResponse.class);
genericCommands.put(0x0013, DiscoverCommandsGenerated.class);
genericCommands.put(0x0014, DiscoverCommandsGeneratedResponse.class);
genericCommands.put(0x0015, DiscoverAttributesExtended.class);
genericCommands.put(0x0016, DiscoverAttributesExtendedResponse.class);
}
/**
* Abstract method called when the cluster starts to initialise the list of client attributes defined in this
* cluster by the cluster library
*
* @return a {@link Map} of all attributes this cluster is known to support
*/
protected abstract Map<Integer, ZclAttribute> initializeClientAttributes();
/**
* Abstract method called when the cluster starts to initialise the list of server attributes defined in this
* cluster by the cluster library
*
* @return a {@link Map} of all attributes this cluster is known to support
*/
protected abstract Map<Integer, ZclAttribute> initializeServerAttributes();
/**
* Abstract method called when the cluster starts to initialise the list of server side commands defined in this
* cluster by the cluster library
*
* @return a {@link Map} of all server side commands this cluster is known to support
*/
protected Map<Integer, Class<? extends ZclCommand>> initializeServerCommands() {
return new ConcurrentHashMap<>(0);
}
/**
* Abstract method called when the cluster starts to initialise the list of client side commands defined in this
* cluster by the cluster library
*
* @return a {@link Map} of all client side commands this cluster is known to support
*/
protected Map<Integer, Class<? extends ZclCommand>> initializeClientCommands() {
return new ConcurrentHashMap<>(0);
}
/**
* Creates a cluster
*
* @param zigbeeEndpoint the {@link ZigBeeEndpoint} to which the cluster belongs
* @param clusterId the 16 bit cluster identifier
* @param clusterName the cluster name
*/
protected ZclCluster(ZigBeeEndpoint zigbeeEndpoint, int clusterId, String clusterName) {
this.zigbeeEndpoint = zigbeeEndpoint;
this.clusterId = clusterId;
this.clusterName = clusterName;
this.normalizer = new ZclAttributeNormalizer();
}
/**
* Sends a {@link ZclCommand}
*
* @param command the {@link ZclCommand} to send
* @return the command result future
*/
protected Future<CommandResult> send(ZclCommand command) {
if (isClient()) {
command.setCommandDirection(ZclCommandDirection.SERVER_TO_CLIENT);
}
command.setApsSecurity(apsSecurityRequired);
return zigbeeEndpoint.sendTransaction(command, new ZclTransactionMatcher());
}
/**
* Write an attribute
*
* @param attributeId the attribute ID to write
* @param dataType the {@link ZclDataType} of the object
* @param value the value to set (as {@link Object})
* @return command future {@link CommandResult}
*/
public Future<CommandResult> writeAttribute(final int attributeId, final ZclDataType dataType, final Object value) {
logger.debug("{}: Writing {} cluster {}, attribute {}, value {}, as dataType {}",
zigbeeEndpoint.getIeeeAddress(), (isClient ? "Client" : "Server"), clusterId, attributeId, value,
dataType);
final WriteAttributeRecord attributeIdentifier = new WriteAttributeRecord();
attributeIdentifier.setAttributeIdentifier(attributeId);
attributeIdentifier.setAttributeDataType(dataType);
attributeIdentifier.setAttributeValue(value);
return writeAttributes(Collections.singletonList(attributeIdentifier));
}
/**
* Writes a number of attributes in a single command
*
* @param attributes a List of {@link WriteAttributeRecord}s with the attribute ID, type and value
* @return command future {@link CommandResult}
*/
public Future<CommandResult> writeAttributes(List<WriteAttributeRecord> attributes) {
final WriteAttributesCommand command = new WriteAttributesCommand();
command.setClusterId(clusterId);
command.setRecords(attributes);
command.setDestinationAddress(zigbeeEndpoint.getEndpointAddress());
ZclAttribute manufacturerSpecificAttribute = null;
for (WriteAttributeRecord attributeRecord : attributes) {
ZclAttribute attribute = getAttribute(attributeRecord.getAttributeIdentifier());
if (attribute != null) {
if (attribute.isManufacturerSpecific()) {
manufacturerSpecificAttribute = attribute;
break;
}
}
}
if (isManufacturerSpecific()) {
command.setManufacturerCode(getManufacturerCode());
} else if (manufacturerSpecificAttribute != null) {
command.setManufacturerCode(manufacturerSpecificAttribute.getManufacturerCode());
}
return send(command);
}
/**
* Read an attribute given the attribute ID. This method will always send a {@link ReadAttributesCommand} to the
* remote device.
*
* @param attributeId the integer attribute ID to read
* @return command future
*/
public Future<CommandResult> readAttribute(final int attributeId) {
return readAttributes(Collections.singletonList(attributeId));
}
/**
* Read a number of attributes given a list of attribute IDs. Care must be taken not to request too many attributes
* so as to exceed the allowable frame length
*
* @param attributeIds List of attribute identifiers to read
* @return command future
*/
public Future<CommandResult> readAttributes(final List<Integer> attributeIds) {
final ReadAttributesCommand command = new ReadAttributesCommand();
command.setClusterId(clusterId);
command.setIdentifiers(attributeIds);
command.setDestinationAddress(zigbeeEndpoint.getEndpointAddress());
if (!attributeIds.isEmpty() && isManufacturerSpecific()) {
command.setManufacturerCode(getManufacturerCode());
} else if (areAttributesManufacturerSpecific(attributeIds)) {
command.setManufacturerCode(getAttribute(attributeIds.get(0)).getManufacturerCode());
}
return send(command);
}
/**
* Read an attribute
*
* @param attributeId the attribute id to read
* @return and object containing the value, or null
*/
protected Object readAttributeValue(final int attributeId) {
logger.debug("readSync request: {}", attributeId);
CommandResult result;
try {
result = readAttribute(attributeId).get();
} catch (InterruptedException e) {
logger.debug("readAttributeValue interrupted");
return null;
} catch (ExecutionException e) {
logger.debug("readAttributeValue exception ", e);
return null;
}
if (!result.isSuccess()) {
return null;
}
ReadAttributesResponse response = result.getResponse();
if (response.getRecords().get(0).getStatus() != ZclStatus.SUCCESS) {
return null;
}
// If we don't know this attribute, then just return the received data
if (getAttribute(attributeId) == null) {
return response.getRecords().get(0).getAttributeValue();
}
return normalizer.normalizeZclData(getAttribute(attributeId).getDataType(),
response.getRecords().get(0).getAttributeValue());
}
/**
* Configures the reporting for the specified attribute ID for discrete attributes.
* <p>
* <b>minInterval</b>:
* The minimum reporting interval field is 16 bits in length and shall contain the
* minimum interval, in seconds, between issuing reports of the specified attribute.
* If minInterval is set to 0x0000, then there is no minimum limit, unless one is
* imposed by the specification of the cluster using this reporting mechanism or by
* the applicable profile.
* <p>
* <b>maxInterval</b>:
* The maximum reporting interval field is 16 bits in length and shall contain the
* maximum interval, in seconds, between issuing reports of the specified attribute.
* If maxInterval is set to 0xffff, then the device shall not issue reports for the specified
* attribute, and the configuration information for that attribute need not be
* maintained.
*
* <b>reportableChange</b>:
* The reportable change field shall contain the minimum change to the attribute that
* will result in a report being issued. This field is of variable length. For attributes
* with 'analog' data type the field has the same data type as the attribute. The sign (if any) of the reportable
* change field is ignored.
*
* @param attributeId the attribute ID to configure reporting
* @param minInterval the minimum reporting interval
* @param maxInterval the maximum reporting interval
* @param reportableChange the minimum change required to report an update
* @return command future {@link CommandResult}
*/
public Future<CommandResult> setReporting(final int attributeId, final int minInterval, final int maxInterval,
Object reportableChange) {
return setReporting(getAttribute(attributeId), minInterval, maxInterval, reportableChange);
}
/**
* Configures the reporting for the specified attribute ID for discrete attributes.
* <p>
* <b>minInterval</b>:
* The minimum reporting interval field is 16 bits in length and shall contain the
* minimum interval, in seconds, between issuing reports of the specified attribute.
* If minInterval is set to 0x0000, then there is no minimum limit, unless one is
* imposed by the specification of the cluster using this reporting mechanism or by
* the applicable profile.
* <p>
* <b>maxInterval</b>:
* The maximum reporting interval field is 16 bits in length and shall contain the
* maximum interval, in seconds, between issuing reports of the specified attribute.
* If maxInterval is set to 0xffff, then the device shall not issue reports for the specified
* attribute, and the configuration information for that attribute need not be
* maintained.
*
* @param attributeId the attribute ID to configure reporting
* @param minInterval the minimum reporting interval
* @param maxInterval the maximum reporting interval
* @return command future {@link CommandResult}
*/
public Future<CommandResult> setReporting(final int attributeId, final int minInterval, final int maxInterval) {
return setReporting(getAttribute(attributeId), minInterval, maxInterval, null);
}
/**
* Gets the reporting configuration for an attribute
*
* @param attributeId the attribute on which to get the reporting configuration
* @return command future {@link CommandResult}
*/
public Future<CommandResult> getReporting(final int attributeId) {
final ReadReportingConfigurationCommand command = new ReadReportingConfigurationCommand();
command.setClusterId(clusterId);
AttributeRecord record = new AttributeRecord();
record.setAttributeIdentifier(attributeId);
record.setDirection(0);
command.setRecords(Collections.singletonList(record));
command.setDestinationAddress(zigbeeEndpoint.getEndpointAddress());
if (isManufacturerSpecific()) {
command.setManufacturerCode(getManufacturerCode());
} else if (getAttribute(attributeId).isManufacturerSpecific()) {
command.setManufacturerCode(getAttribute(attributeId).getManufacturerCode());
}
return send(command);
}
/**
* Gets all the attributes supported by this cluster This will return all attributes, even if they are not actually
* supported by the device. The user should check to see if this is implemented.
* <p>
* This will return either the list of client or server attributes, depending on the cluster.
*
* @return {@link Set} containing all {@link ZclAttributes} available in this cluster
*/
public Collection<ZclAttribute> getAttributes() {
if (isClient) {
return Collections.unmodifiableCollection(clientAttributes.values());
} else {
return Collections.unmodifiableCollection(serverAttributes.values());
}
}
/**
* Gets an attribute from the attribute ID
*
* @param attributeId the attribute ID
* @return the {@link ZclAttribute}
*/
public ZclAttribute getAttribute(int attributeId) {
if (isClient) {
return clientAttributes.get(attributeId);
} else {
return serverAttributes.get(attributeId);
}
}
/**
* Gets the cluster ID for this cluster
*
* @return the cluster ID as {@link Integer}
*/
public Integer getClusterId() {
return clusterId;
}
/**
* Gets the cluster name for this cluster
*
* @return the cluster name as {@link String}
*/
public String getClusterName() {
return clusterName;
}
/**
* Returns the ZigBee address of this cluster
*
* @return the {@link ZigBeeEndpointAddress} of the cluster
*/
public ZigBeeEndpointAddress getZigBeeAddress() {
return zigbeeEndpoint.getEndpointAddress();
}
/**
* Sets the server flag for this cluster. This means the cluster is listed in the devices input cluster list
*
*/
public void setServer() {
isClient = false;
}
/**
* Gets the state of the server flag. If the cluster is a server this will return true
*
* @return true if the cluster can act as a server
*/
public boolean isServer() {
return !isClient;
}
/**
* Sets the client flag for this cluster. This means the cluster is listed in the devices output cluster list
*
*/
public void setClient() {
isClient = true;
}
/**
* Gets the state of the client flag. If the cluster is a client this will return true
*
* @return true if the cluster can act as a client
*/
public boolean isClient() {
return isClient;
}
/**
* Sets APS security requirement on or off for this cluster. If APS security is required, all outgoing frames will
* be APS secured, and any incoming frames without APS security will be ignored.
*
* @param requireApsSecurity true if APS security is required for this cluster
*/
public void setApsSecurityRequired(boolean requireApsSecurity) {
this.apsSecurityRequired = requireApsSecurity;
}
/**
* If APS security is required, all outgoing frames will be APS secured, and any incoming frames without APS
* security will be ignored.
*
* @return true if APS security is required for this cluster
*/
public boolean getApsSecurityRequired() {
return apsSecurityRequired;
}
/**
* Adds a binding from the cluster to the destination {@link ZigBeeEndpoint}.
*
* @param address the destination {@link IeeeAddress}
* @param endpointId the destination endpoint ID
* @return Command future
*/
public Future<CommandResult> bind(IeeeAddress address, int endpointId) {
final BindRequest command = new BindRequest();
command.setDestinationAddress(new ZigBeeEndpointAddress(zigbeeEndpoint.getEndpointAddress().getAddress()));
command.setSrcAddress(zigbeeEndpoint.getIeeeAddress());
command.setSrcEndpoint(zigbeeEndpoint.getEndpointId());
command.setBindCluster(clusterId);
command.setDstAddrMode(3); // 64 bit addressing
command.setDstAddress(address);
command.setDstEndpoint(endpointId);
// The transaction is not sent to the Endpoint of this cluster, but to the ZDO endpoint 0 directly.
return zigbeeEndpoint.getParentNode().sendTransaction(command, command);
}
/**
* Removes a binding from the cluster to the destination {@link ZigBeeEndpoint}.
*
* @param address the destination {@link IeeeAddress}
* @param endpointId the destination endpoint ID
* @return Command future
*/
public Future<CommandResult> unbind(IeeeAddress address, int endpointId) {
final UnbindRequest command = new UnbindRequest();
command.setDestinationAddress(new ZigBeeEndpointAddress(zigbeeEndpoint.getEndpointAddress().getAddress()));
command.setSrcAddress(zigbeeEndpoint.getIeeeAddress());
command.setSrcEndpoint(zigbeeEndpoint.getEndpointId());
command.setBindCluster(clusterId);
command.setDstAddrMode(3); // 64 bit addressing
command.setDstAddress(address);
command.setDstEndpoint(endpointId);
// The transaction is not sent to the Endpoint of this cluster, but to the ZDO endpoint 0 directly.
return zigbeeEndpoint.getParentNode().sendTransaction(command, command);
}
/**
* Sends a default response to the client
*
* @param transactionId the transaction ID to use in the response
* @param commandIdentifier the command identifier to which this is a response
* @param status the {@link ZclStatus} to send in the response
* @param manufacturerCode the manufacturer code to set in the response (or null, if the command is not
* manufacturer-specific, or if the cluster is itself manufacturer-specific)
* @deprecated use sendDefaultResponse(ZclCommand command, ZclStatus status)
*/
@Deprecated
public void sendDefaultResponse(Integer transactionId, Integer commandIdentifier, ZclStatus status,
Integer manufacturerCode) {
DefaultResponse defaultResponse = new DefaultResponse();
defaultResponse.setTransactionId(transactionId);
defaultResponse.setCommandIdentifier(commandIdentifier);
defaultResponse.setDestinationAddress(zigbeeEndpoint.getEndpointAddress());
defaultResponse.setClusterId(clusterId);
defaultResponse.setStatusCode(status);
if (isManufacturerSpecific()) {
defaultResponse.setManufacturerCode(getManufacturerCode());
} else if (manufacturerCode != null) {
defaultResponse.setManufacturerCode(manufacturerCode);
}
send(defaultResponse);
}
/**
* Sends a default response to the client
*
* @param transactionId the transaction ID to use in the response
* @param commandIdentifier the command identifier to which this is a response
* @param status the {@link ZclStatus} to send in the response
* @deprecated use sendDefaultResponse(ZclCommand command, ZclStatus status)
*/
@Deprecated
public void sendDefaultResponse(Integer transactionId, Integer commandIdentifier, ZclStatus status) {
sendDefaultResponse(transactionId, commandIdentifier, status, null);
}
/**
* Sends a default response to the client
*
* @param command the {@link ZclCommand} to which we are responding
* @param status the {@link ZclStatus} to send in the response
*/
public void sendDefaultResponse(ZclCommand command, ZclStatus status) {
ZclCommand response = createDefaultResponse(command, status);
if (response == null) {
return;
}
if (isManufacturerSpecific()) {
response.setManufacturerCode(getManufacturerCode());
}
// Default response will not solicit a response
zigbeeEndpoint.sendTransaction(response);
}
/**
* Gets the list of attributes supported by this device.
* After initialisation, the list will contain all standard attributes defined by ZCL, so is not customised to the
* specific device. Once a successful call to {@link #discoverAttributes()} has been made, the list will reflect the
* attributes supported by the remote device.
*
* @return {@link Set} of {@link Integer} containing the list of supported attributes
*/
public Set<Integer> getSupportedAttributes() {
synchronized (supportedAttributes) {
if (!supportedAttributesKnown) {
if (isClient) {
return clientAttributes.keySet();
} else {
return serverAttributes.keySet();
}
}
return supportedAttributes;
}
}
/**
* Checks if the cluster supports a specified attribute ID.
* Note that if {@link #discoverAttributes(boolean)} has not been called, this method will return false.
*
* @param attributeId the attribute to check
* @return true if the attribute is known to be supported, otherwise false
*/
public boolean isAttributeSupported(int attributeId) {
synchronized (supportedAttributes) {
return supportedAttributes.contains(attributeId);
}
}
/**
* Discovers the list of attributes supported by the cluster on the remote device.
* <p>
* If the discovery has already been completed, and rediscover is false, then the future will complete immediately
* and the user can use existing results. Normally there should not be a need to set rediscover to true.
* <p>
* This method returns a future to a boolean. Upon success the caller should call {@link #getSupportedAttributes()}
* to get the list of supported attributes or {@link #isAttributeSupported(int)} to test if a single attribute is
* supported.
*
* @param rediscover true to perform a discovery even if it was previously completed
* @return {@link Future} returning a {@link Boolean}
*/
public Future<Boolean> discoverAttributes(final boolean rediscover) {
return discoverAttributes(rediscover, null);
}
/**
* Discovers the list of attributes supported by the cluster on the remote device.
* <p>
* If the discovery has already been completed, and rediscover is false, then the future will complete immediately
* and the user can use existing results. Normally there should not be a need to set rediscover to true.
* <p>
* This method returns a future to a boolean. Upon success the caller should call {@link #getSupportedAttributes()}
* to get the list of supported attributes.
* <p>
* If the cluster is not manufacturer-specific, discovery of manufacturer-specific attributes for a specific
* manufacturer can be triggered via the method parameter 'manufacturerCode'.
*
* @param rediscover true to perform a discovery even if it was previously completed
* @param manufacturerCode set to non-null value to perform a discovery of manufacturer-specific attributes
* @return {@link Future} returning a {@link Boolean}
*/
public Future<Boolean> discoverAttributes(final boolean rediscover, final Integer manufacturerCode) {
RunnableFuture<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// Synchronise the request to avoid multiple simultaneous requests to this update of the list on this
// cluster which would cause errors consolidating the responses
synchronized (supportedAttributes) {
// If we don't want to rediscover, and we already have the list of attributes, then return
if (!rediscover && supportedAttributesKnown) {
return true;
}
int index = 0;
boolean complete = false;
Set<AttributeInformation> attributes = new HashSet<>();
do {
final DiscoverAttributesCommand command = new DiscoverAttributesCommand();
command.setClusterId(clusterId);
command.setDestinationAddress(zigbeeEndpoint.getEndpointAddress());
command.setStartAttributeIdentifier(index);
command.setMaximumAttributeIdentifiers(10);
if (isManufacturerSpecific()) {
command.setManufacturerCode(getManufacturerCode());
} else if (manufacturerCode != null) {
command.setManufacturerCode(manufacturerCode);
}
CommandResult result = send(command).get();
if (result.isError()) {
return false;
}
DiscoverAttributesResponse response = (DiscoverAttributesResponse) result.getResponse();
complete = response.getDiscoveryComplete();
if (response.getAttributeInformation() != null
&& !response.getAttributeInformation().isEmpty()) {
attributes.addAll(response.getAttributeInformation());
index = Collections.max(attributes).getIdentifier() + 1;
}
} while (!complete);
supportedAttributes.clear();
for (AttributeInformation attribute : attributes) {
supportedAttributes.add(attribute.getIdentifier());
}
}
supportedAttributesKnown = true;
return true;
}
});
// Create the thread to execute it
new Thread(future, "DiscoverAttributes-" + zigbeeEndpoint.getIeeeAddress()).start();
return future;
}
/**
* Returns a list of all the commands the remote device can receive. This will be an empty list if the
* {@link #discoverCommandsReceived()} method has not completed.
*
* @return a {@link Set} of command IDs the device supports
*/
public Set<Integer> getSupportedCommandsReceived() {
synchronized (supportedCommandsReceived) {
return new HashSet<>(supportedCommandsReceived);
}
}
/**
* Checks if the cluster supports a specified received command ID.
* Note that if {@link #discoverCommandsReceived(boolean)} has not been called, this method will return false.
*
* @param commandId the attribute to check
* @return true if the command is known to be supported, otherwise false
*/
public boolean isReceivedCommandSupported(int commandId) {
synchronized (supportedCommandsReceived) {
return supportedCommandsReceived.contains(commandId);
}
}
/**
* Discovers the list of commands received by the cluster on the remote device. If the discovery is successful,
* users should call {@link ZclCluster#getSupportedCommandsReceived()} to get the list of supported commands.
* <p>
* If the discovery has already been completed, and rediscover is false, then the future will complete immediately
* and the user can use existing results. Normally there should not be a need to set rediscover to true.
* <p>
* Will not discover manufacturer-specific commands unless the cluster itself is manufacturer-specific.
*
* @param rediscover true to perform a discovery even if it was previously completed
* @return Command future {@link Boolean} with the success of the discovery
*/
public Future<Boolean> discoverCommandsReceived(final boolean rediscover) {
return discoverCommandsReceived(rediscover, null);
}
/**
* Discovers the list of commands received by the cluster on the remote device. If the discovery is successful,
* users should call {@link ZclCluster#getSupportedCommandsReceived()} to get the list of supported commands.
* <p>
* If the discovery has already been completed, and rediscover is false, then the future will complete immediately
* and the user can use existing results. Normally there should not be a need to set rediscover to true.
* <p>
* If the cluster is not manufacturer-specific, discovery of manufacturer-specific commands for a specific
* manufacturer can be triggered via the method parameter 'manufacturerCode'.
*
* @param rediscover true to perform a discovery even if it was previously completed
* @param manufacturerCode set to non-null value to perform a discovery of manufacturer-specific commands
* @return Command future {@link Boolean} with the success of the discovery
*/
public Future<Boolean> discoverCommandsReceived(final boolean rediscover, final Integer manufacturerCode) {
RunnableFuture<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// Synchronise the request to avoid multiple simultaneous requests to this update the list on this
// cluster which would cause errors consolidating the responses
synchronized (supportedCommandsReceived) {
// If we don't want to rediscover, and we already have the list of attributes, then return
if (!rediscover && !supportedCommandsReceived.isEmpty()) {
return true;
}
int index = 0;
boolean complete = false;
Set<Integer> commands = new HashSet<>();
do {
final DiscoverCommandsReceived command = new DiscoverCommandsReceived();
command.setClusterId(clusterId);
command.setDestinationAddress(zigbeeEndpoint.getEndpointAddress());
command.setStartCommandIdentifier(index);
command.setMaximumCommandIdentifiers(20);
if (isManufacturerSpecific()) {
command.setManufacturerCode(getManufacturerCode());
} else if (manufacturerCode != null) {
command.setManufacturerCode(manufacturerCode);
}
CommandResult result = send(command).get();
if (result.isError()) {
return false;
}
DiscoverCommandsReceivedResponse response = (DiscoverCommandsReceivedResponse) result
.getResponse();
complete = response.getDiscoveryComplete();
if (response.getCommandIdentifiers() != null) {
commands.addAll(response.getCommandIdentifiers());
index = Collections.max(commands) + 1;
}
} while (!complete);
supportedCommandsReceived.clear();
supportedCommandsReceived.addAll(commands);
}
return true;
}
});
// start the thread to execute it
new Thread(future, "DiscoverCommandsReceived-" + zigbeeEndpoint.getIeeeAddress()).start();
return future;
}
/**
* Returns a list of all the commands the remote device can generate. This will be an empty list if the
* {@link #discoverCommandsGenerated()} method has not completed.
*
* @return a {@link Set} of command IDs the device supports
*/
public Set<Integer> getSupportedCommandsGenerated() {
synchronized (supportedCommandsGenerated) {
return new HashSet<>(supportedCommandsGenerated);
}
}
/**
* Checks if the cluster supports a specified generated command ID.
* Note that if {@link #discoverCommandsGenerated(boolean)} has not been called, this method will return false.
*
* @param commandId the attribute to check
* @return true if the command is known to be supported, otherwise false
*/
public boolean isGeneratedCommandSupported(int commandId) {
synchronized (supportedCommandsGenerated) {
return supportedCommandsGenerated.contains(commandId);
}
}
/**
* Discovers the list of commands generated by the cluster on the remote device If the discovery is successful,
* users should call {@link ZclCluster#getSupportedCommandsGenerated()} to get the list of supported commands.
* <p>
* If the discovery has already been completed, and rediscover is false, then the future will complete immediately
* and the user can use existing results. Normally there should not be a need to set rediscover to true.
* <p>
* Will not discover manufacturer-specific commands unless the cluster itself is manufacturer-specific.
*
* @param rediscover true to perform a discovery even if it was previously completed
* @return Command future {@link Boolean} with the success of the discovery
*/
public Future<Boolean> discoverCommandsGenerated(final boolean rediscover) {
return discoverCommandsGenerated(rediscover, null);
}
/**
* Discovers the list of commands generated by the cluster on the remote device If the discovery is successful,
* users should call {@link ZclCluster#getSupportedCommandsGenerated()} to get the list of supported commands.
* <p>
* If the discovery has already been completed, and rediscover is false, then the future will complete immediately
* and the user can use existing results. Normally there should not be a need to set rediscover to true.
* <p>
* If the cluster is not manufacturer-specific, discovery of manufacturer-specific commands for a specific
* manufacturer can be triggered via the method parameter 'manufacturerCode'.
*
* @param rediscover true to perform a discovery even if it was previously completed
* @param manufacturerCode set to non-null value to perform a discovery of manufacturer-specific commands
* @return Command future {@link Boolean} with the success of the discovery
*/
public Future<Boolean> discoverCommandsGenerated(final boolean rediscover, final Integer manufacturerCode) {
RunnableFuture<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// Synchronise the request to avoid multiple simultaneous requests to this update the list on this
// cluster which would cause errors consolidating the responses
synchronized (supportedCommandsGenerated) {
// If we don't want to rediscover, and we already have the list of attributes, then return
if (!rediscover && !supportedCommandsGenerated.isEmpty()) {
return true;
}
int index = 0;
boolean complete = false;
Set<Integer> commands = new HashSet<>();
do {