-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscover.py
1704 lines (1342 loc) · 52.9 KB
/
discover.py
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
#!/usr/bin/python3
"""
Autodiscover
This is an application to assist with the "discovery" process of finding
BACnet routers, devices, objects, and property values. It reads and/or writes
a tab-delimited property values text file of the values that it has received.
"""
import sys
import time
import json
from collections import defaultdict, OrderedDict
from bacpypes.settings import settings as _settings
from bacpypes.debugging import bacpypes_debugging, ModuleLogger, btox
from bacpypes.consolelogging import JSONArgumentParser
from bacpypes.consolecmd import ConsoleCmd
from bacpypes.pdu import Address, LocalBroadcast, GlobalBroadcast
from bacpypes.comm import Client, Server, bind
from bacpypes.core import run, deferred, enable_sleeping
from bacpypes.task import FunctionTask
from bacpypes.iocb import IOCB, IOQController
# application layer
from bacpypes.primitivedata import Unsigned, ObjectIdentifier
from bacpypes.constructeddata import Array, ArrayOf
from bacpypes.basetypes import PropertyIdentifier, ServicesSupported
from bacpypes.object import get_object_class, get_datatype, DeviceObject
from bacpypes.app import ApplicationIOController
from bacpypes.appservice import StateMachineAccessPoint, ApplicationServiceAccessPoint
from bacpypes.apdu import (
WhoIsRequest,
IAmRequest,
ReadPropertyRequest,
ReadPropertyACK,
ReadPropertyMultipleRequest,
PropertyReference,
ReadAccessSpecification,
ReadPropertyMultipleACK,
)
# network layer
from bacpypes.netservice import NetworkServiceAccessPoint, NetworkServiceElement
from bacpypes.npdu import (
WhoIsRouterToNetwork,
IAmRouterToNetwork,
InitializeRoutingTable,
InitializeRoutingTableAck,
WhatIsNetworkNumber,
NetworkNumberIs,
)
# IPv4 virtual link layer
from bacpypes.bvllservice import BIPSimple, BIPForeign, AnnexJCodec, UDPMultiplexer
# basic objects
from bacpypes.local.device import LocalDeviceObject
# basic services
from bacpypes.service.device import WhoIsIAmServices
from bacpypes.service.object import ReadWritePropertyServices
# some debugging
_debug = 0
_log = ModuleLogger(globals())
# globals
args = None
this_device = None
this_application = None
snapshot = None
debug_traffic_file = None
# device information
device_profile = defaultdict(DeviceObject)
# print statements just for interactive
interactive = sys.stdin.isatty()
# lists of things to do
network_path_to_do_list = None
who_is_to_do_list = None
application_to_do_list = None
#
# Debug
#
@bacpypes_debugging
class Debug(Client, Server):
def __init__(self, label=None, cid=None, sid=None):
if _debug:
Debug._debug("__init__ label=%r cid=%r sid=%r", label, cid, sid)
Client.__init__(self, cid)
Server.__init__(self, sid)
# save the label
self.label = label
def _now(self):
now = time.time()
return time.strftime("%H:%M:%S.", time.gmtime(now)) + "{:03d}".format(
int((now - int(now)) * 1000)
)
def confirmation(self, pdu):
if debug_traffic_file:
debug_traffic_file.write(
f"{self._now()}\t{self.label}\t>>>\t{pdu.pduSource}\t{pdu.pduDestination}\t{btox(pdu.pduData)}\n"
)
self.response(pdu)
def indication(self, pdu):
if debug_traffic_file:
debug_traffic_file.write(
f"{self._now()}\t{self.label}\t<<<\t{pdu.pduSource}\t{pdu.pduDestination}\t{btox(pdu.pduData)}\n"
)
self.request(pdu)
#
# Snapshot
#
@bacpypes_debugging
class Snapshot:
def __init__(self):
if _debug:
Snapshot._debug("__init__")
# empty database
self.data = {}
def read_file(self, filename):
if _debug:
Snapshot._debug("read_file %r", filename)
# empty database
self.data = {}
try:
with open(filename) as infile:
lines = infile.readlines()
for line in lines:
devid, objid, propid, version, value = line[:-1].split("\t")
devid = int(devid)
version = int(version)
key = (devid, objid, propid)
self.data[key] = (version, value)
except IOError:
if _debug:
Snapshot._debug(" - file not found")
pass
def write_file(self, filename):
if _debug:
Snapshot._debug("write_file %r", filename)
data = list(k + v for k, v in self.data.items())
if _debug:
Snapshot._debug(" - data: %r", data)
data.sort()
with open(filename, "w") as outfile:
for row in data:
outfile.write("\t".join(str(x) for x in row) + "\n")
def upsert(self, devid, objid, propid, value):
if _debug:
Snapshot._debug("upsert %r %r %r %r", devid, objid, propid, value)
key = (devid, objid, propid)
if key not in self.data:
if _debug:
Snapshot._debug(" - new key")
self.data[key] = (1, value)
else:
version, old_value = self.data[key]
if value != old_value:
if _debug:
Snapshot._debug(" - new value")
self.data[key] = (version + 1, value)
def get_value(self, devid, objid, propid):
if _debug:
Snapshot._debug("get_value %r %r %r", devid, objid, propid)
key = (devid, objid, propid)
if key not in self.data:
return None
else:
return self.data[key][1]
#
# ToDoItem
#
@bacpypes_debugging
class ToDoItem:
def __init__(self, _thread=None, _delay=None):
if _debug:
ToDoItem._debug("__init__")
# basic status information
self._completed = False
# may depend on another item to complete, may have a delay
self._thread = _thread
self._delay = _delay
def prepare(self):
if _debug:
ToDoItem._debug("prepare")
raise NotImplementedError
def complete(self, iocb):
if _debug:
ToDoItem._debug("complete %r", iocb)
self._completed = True
#
# ToDoList
#
@bacpypes_debugging
class ToDoList:
def __init__(self, controller, active_limit=1):
if _debug:
ToDoList._debug("__init__")
# save a reference to the controller for workers
self.controller = controller
# limit to the number of active workers
self.active_limit = active_limit
# no workers, nothing active
self.pending = []
self.active = set()
# launch already deferred
self.launch_deferred = False
def append(self, item):
if _debug:
ToDoList._debug("append %r", item)
# add the item to the list of pending items
self.pending.append(item)
# if an item can be started, schedule to launch it
if len(self.active) < self.active_limit and not self.launch_deferred:
if _debug:
ToDoList._debug(" - will launch")
self.launch_deferred = True
deferred(self.launch)
def launch(self):
if _debug:
ToDoList._debug("launch")
# find some workers and launch them
while self.pending and (len(self.active) < self.active_limit):
# look for the next to_do_item that can be started
for i, item in enumerate(self.pending):
if not item._thread:
break
if item._thread._completed:
break
else:
if _debug:
ToDoList._debug(" - waiting")
break
if _debug:
ToDoList._debug(" - item: %r", item)
# remove it from the pending list, add it to active
del self.pending[i]
self.active.add(item)
# prepare it and capture the IOCB
iocb = item.prepare()
if _debug:
ToDoList._debug(" - iocb: %r", iocb)
# break the reference to the completed to_do_item
item._thread = None
iocb._to_do_item = item
# add our completion routine
iocb.add_callback(self.complete)
# submit it to our controller
self.controller.request_io(iocb)
# clear the deferred flag
self.launch_deferred = False
if _debug:
ToDoList._debug(" - done launching")
# check for idle
if (not self.active) and (not self.pending):
self.idle()
def complete(self, iocb):
if _debug:
ToDoList._debug("complete %r", iocb)
# extract the to_do_item
item = iocb._to_do_item
if _debug:
ToDoList._debug(" - item: %r", item)
# if the item has a delay, schedule to call it later
if item._delay:
task = FunctionTask(self._delay_complete, item, iocb)
task.install_task(delta=item._delay)
if _debug:
ToDoList._debug(" - task: %r", task)
else:
self._delay_complete(item, iocb)
def _delay_complete(self, item, iocb):
if _debug:
ToDoList._debug("_delay_complete %r %r", item, iocb)
# tell the item it completed, remove it from active
item.complete(iocb)
self.active.remove(item)
# find another to_do_item
if not self.launch_deferred:
if _debug:
ToDoList._debug(" - will launch")
self.launch_deferred = True
deferred(self.launch)
def idle(self):
if _debug:
ToDoList._debug("idle")
#
# DiscoverNetworkServiceElement
#
@bacpypes_debugging
class DiscoverNetworkServiceElement(NetworkServiceElement, IOQController):
def __init__(self):
if _debug:
DiscoverNetworkServiceElement._debug("__init__")
NetworkServiceElement.__init__(self)
IOQController.__init__(self)
def process_io(self, iocb):
if _debug:
DiscoverNetworkServiceElement._debug("process_io %r", iocb)
# this request is active
self.active_io(iocb)
# reference the service access point
sap = self.elementService
if _debug:
NetworkServiceElement._debug(" - sap: %r", sap)
# the iocb contains an NPDU, pass it along to the local adapter
self.request(sap.local_adapter, iocb.args[0])
def indication(self, adapter, npdu):
if _debug:
DiscoverNetworkServiceElement._debug("indication %r %r", adapter, npdu)
global network_path_to_do_list
if not self.active_iocb:
pass
elif isinstance(npdu, IAmRouterToNetwork):
if interactive:
print("{} router to {}".format(npdu.pduSource, npdu.iartnNetworkList))
# reference the request
request = self.active_iocb.args[0]
if isinstance(request, WhoIsRouterToNetwork):
if request.wirtnNetwork in npdu.iartnNetworkList:
self.complete_io(self.active_iocb, npdu.pduSource)
elif isinstance(npdu, InitializeRoutingTableAck):
if interactive:
print("{} routing table".format(npdu.pduSource))
for rte in npdu.irtaTable:
print(
" {} {} {}".format(rte.rtDNET, rte.rtPortID, rte.rtPortInfo)
)
# reference the request
request = self.active_iocb.args[0]
if isinstance(request, InitializeRoutingTable):
if npdu.pduSource == request.pduDestination:
self.complete_io(self.active_iocb, npdu.irtaTable)
elif isinstance(npdu, NetworkNumberIs):
if interactive:
print("{} network number is {}".format(npdu.pduSource, npdu.nniNet))
# reference the request
request = self.active_iocb.args[0]
if isinstance(request, WhatIsNetworkNumber):
self.complete_io(self.active_iocb, npdu.nniNet)
# forward it along
NetworkServiceElement.indication(self, adapter, npdu)
#
# DiscoverApplication
#
@bacpypes_debugging
class DiscoverApplication(
ApplicationIOController, WhoIsIAmServices, ReadWritePropertyServices
):
def __init__(
self,
localDevice,
localAddress,
bbmdAddress,
bbmdTTL,
deviceInfoCache=None,
aseID=None,
):
if _debug:
DiscoverApplication._debug(
"__init__ %r %r deviceInfoCache=%r aseID=%r",
localDevice,
localAddress,
deviceInfoCache,
aseID,
)
DiscoverApplication._debug(
" - bbmdAddress: %r, ttl: %r", bbmdAddress, bbmdTTL,
)
ApplicationIOController.__init__(
self, localDevice, localAddress, deviceInfoCache, aseID=aseID
)
# local address might be useful for subclasses
if isinstance(localAddress, Address):
self.localAddress = localAddress
else:
self.localAddress = Address(localAddress)
# include a application decoder
self.asap = ApplicationServiceAccessPoint()
# pass the device object to the state machine access point so it
# can know if it should support segmentation
self.smap = StateMachineAccessPoint(localDevice)
# the segmentation state machines need access to the same device
# information cache as the application
self.smap.deviceInfoCache = self.deviceInfoCache
# a network service access point will be needed
self.nsap = NetworkServiceAccessPoint()
# give the NSAP a generic network layer service element
self.nse = DiscoverNetworkServiceElement()
bind(self.nse, self.nsap)
# bind the top layers
bind(self, self.asap, self.smap, self.nsap)
# create a generic BIP stack, bound to the Annex J server
# on the UDP multiplexer
if not bbmdAddress:
self.bip = BIPSimple()
self.annexj = AnnexJCodec()
self.mux = UDPMultiplexer(self.localAddress)
else:
self.bip = BIPForeign(bbmdAddress, bbmdTTL)
self.annexj = AnnexJCodec()
self.mux = UDPMultiplexer(self.localAddress, noBroadcast=True)
self.debug = Debug("inside")
# bind the bottom layers
bind(self.bip, self.annexj, self.debug, self.mux.annexJ)
# bind the BIP stack to the network, no network number
self.nsap.bind(self.bip, address=self.localAddress)
def close_socket(self):
if _debug:
DiscoverApplication._debug("close_socket")
# pass to the multiplexer, then down to the sockets
self.mux.close_socket()
def do_IAmRequest(self, apdu):
if _debug:
DiscoverApplication._debug("do_IAmRequest %r", apdu)
global who_is_to_do_list
# pass it along to line up with active requests
who_is_to_do_list.received_i_am(apdu)
#
# WhoIsToDo
#
@bacpypes_debugging
class WhoIsToDo(ToDoItem):
def __init__(self, addr, lolimit, hilimit):
if _debug:
WhoIsToDo._debug("__init__ %r %r %r", addr, lolimit, hilimit)
ToDoItem.__init__(self, _delay=3.0)
# save the parameters
self.addr = addr
self.lolimit = lolimit
self.hilimit = hilimit
# hold on to the request and make a placeholder for responses
self.request = None
self.i_am_responses = []
# give it to the list
who_is_to_do_list.append(self)
def prepare(self):
if _debug:
WhoIsToDo._debug("prepare(%r %r %r)", self.addr, self.lolimit, self.hilimit)
# build a request
self.request = WhoIsRequest(
destination=self.addr,
deviceInstanceRangeLowLimit=self.lolimit,
deviceInstanceRangeHighLimit=self.hilimit,
)
if _debug:
WhoIsToDo._debug(" - request: %r", self.request)
# build an IOCB
iocb = IOCB(self.request)
if _debug:
WhoIsToDo._debug(" - iocb: %r", iocb)
return iocb
def complete(self, iocb):
if _debug:
WhoIsToDo._debug("complete %r", iocb)
# process the responses
for apdu in self.i_am_responses:
device_instance = apdu.iAmDeviceIdentifier[1]
# print out something
if interactive:
print("{} @ {}".format(device_instance, apdu.pduSource))
# update the snapshot database
snapshot.upsert(device_instance, "-", "address", str(apdu.pduSource))
snapshot.upsert(
device_instance,
"-",
"maxAPDULengthAccepted",
str(apdu.maxAPDULengthAccepted),
)
snapshot.upsert(
device_instance,
"-",
"segmentationSupported",
apdu.segmentationSupported,
)
# read stuff
ReadServicesSupported(device_instance)
ReadObjectList(device_instance)
# pass along
ToDoItem.complete(self, iocb)
#
# WhoIsToDoList
#
@bacpypes_debugging
class WhoIsToDoList(ToDoList):
def received_i_am(self, apdu):
if _debug:
WhoIsToDoList._debug("received_i_am %r", apdu)
# line it up with an active item
for item in self.active:
if _debug:
WhoIsToDoList._debug(" - item: %r", item)
# check the source against the request
if item.addr.addrType == Address.localBroadcastAddr:
if apdu.pduSource.addrType != Address.localStationAddr:
if _debug:
WhoIsToDoList._debug(" - not a local station")
continue
elif item.addr.addrType == Address.localStationAddr:
if apdu.pduSource != item.addr:
if _debug:
WhoIsToDoList._debug(" - not from station")
continue
elif item.addr.addrType == Address.remoteBroadcastAddr:
if apdu.pduSource.addrType != Address.remoteStationAddr:
if _debug:
WhoIsToDoList._debug(" - not a remote station")
continue
if apdu.pduSource.addrNet != item.addr.addrNet:
if _debug:
WhoIsToDoList._debug(" - not from remote net")
continue
elif item.addr.addrType == Address.remoteStationAddr:
if apdu.pduSource != item.addr:
if _debug:
WhoIsToDoList._debug(" - not correct remote station")
continue
# check the range restriction
device_instance = apdu.iAmDeviceIdentifier[1]
if (item.lolimit is not None) and (device_instance < item.lolimit):
if _debug:
WhoIsToDoList._debug(" - lo limit")
continue
if (item.hilimit is not None) and (device_instance > item.hilimit):
if _debug:
WhoIsToDoList._debug(" - hi limit")
continue
# debug in case something kicked it out
if _debug:
WhoIsToDoList._debug(" - passed")
# save this response
item.i_am_responses.append(apdu)
def idle(self):
if _debug:
WhoIsToDoList._debug("idle")
#
# ApplicationToDoList
#
@bacpypes_debugging
class ApplicationToDoList(ToDoList):
def __init__(self):
if _debug:
ApplicationToDoList._debug("__init__")
global this_application
ToDoList.__init__(self, this_application)
#
# ReadPropertyToDo
#
@bacpypes_debugging
class ReadPropertyToDo(ToDoItem):
def __init__(self, devid, objid, propid, index=None):
if _debug:
ReadPropertyToDo._debug(
"__init__ %r %r %r index=%r", devid, objid, propid, index
)
ToDoItem.__init__(self)
# save the parameters
self.devid = devid
self.objid = objid
self.propid = propid
self.index = index
# give it to the list
application_to_do_list.append(self)
def prepare(self):
if _debug:
ReadPropertyToDo._debug(
"prepare(%r %r %r)", self.devid, self.objid, self.propid
)
# map the devid identifier to an address from the database
addr = snapshot.get_value(self.devid, "-", "address")
if not addr:
raise ValueError("unknown device")
if _debug:
ReadPropertyToDo._debug(" - addr: %r", addr)
# build a request
request = ReadPropertyRequest(
destination=Address(addr),
objectIdentifier=self.objid,
propertyIdentifier=self.propid,
)
if self.index is not None:
request.propertyArrayIndex = self.index
if _debug:
ReadPropertyToDo._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug:
ReadPropertyToDo._debug(" - iocb: %r", iocb)
return iocb
def complete(self, iocb):
if _debug:
ReadPropertyToDo._debug("complete %r", iocb)
# do something for error/reject/abort
if iocb.ioError:
if interactive:
print("{} error: {}".format(self.propid, iocb.ioError))
# do something more
self.returned_error(iocb.ioError)
# do something for success
elif iocb.ioResponse:
apdu = iocb.ioResponse
# should be an ack
if not isinstance(apdu, ReadPropertyACK):
if _debug:
ReadPropertyToDo._debug(" - not an ack")
return
# find the datatype
datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
if _debug:
ReadPropertyToDo._debug(" - datatype: %r", datatype)
if not datatype:
raise TypeError("unknown datatype")
# special case for array parts, others are managed by cast_out
if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):
if apdu.propertyArrayIndex == 0:
datatype = Unsigned
else:
datatype = datatype.subtype
if _debug:
ReadPropertyToDo._debug(" - datatype: %r", datatype)
value = apdu.propertyValue.cast_out(datatype)
if _debug:
ReadPropertyToDo._debug(" - value: %r", value)
# convert the value to a string
if hasattr(value, "dict_contents"):
dict_contents = value.dict_contents(as_class=OrderedDict)
str_value = json.dumps(dict_contents)
else:
str_value = str(value)
if interactive:
print(str_value)
# make a pretty property identifier
str_prop = apdu.propertyIdentifier
if apdu.propertyArrayIndex is not None:
str_prop += "[{}]".format(apdu.propertyArrayIndex)
# save it in the snapshot
snapshot.upsert(
self.devid, "{}:{}".format(*apdu.objectIdentifier), str_prop, str_value
)
# do something more
self.returned_value(value)
# do something with nothing?
else:
if _debug:
ReadPropertyToDo._debug(" - ioError or ioResponse expected")
def returned_error(self, error):
if _debug:
ReadPropertyToDo._debug("returned_error %r", error)
def returned_value(self, value):
if _debug:
ReadPropertyToDo._debug("returned_value %r", value)
#
# ReadServicesSupported
#
@bacpypes_debugging
class ReadServicesSupported(ReadPropertyToDo):
def __init__(self, devid):
if _debug:
ReadServicesSupported._debug("__init__ %r", devid)
ReadPropertyToDo.__init__(
self, devid, ("device", devid), "protocolServicesSupported"
)
def returned_value(self, value):
if _debug:
ReadServicesSupported._debug("returned_value %r", value)
# build a value
services_supported = ServicesSupported(value)
print(
"{} supports rpm: {}".format(
self.devid, services_supported["readPropertyMultiple"]
)
)
# device profile
devobj = device_profile[self.devid]
devobj.protocolServicesSupported = services_supported
#
# ReadObjectList
#
@bacpypes_debugging
class ReadObjectList(ReadPropertyToDo):
def __init__(self, devid):
if _debug:
ReadObjectList._debug("__init__ %r", devid)
ReadPropertyToDo.__init__(self, devid, ("device", devid), "objectList")
def returned_error(self, error):
if _debug:
ReadObjectList._debug("returned_error %r", error)
# try reading the length of the list
ReadObjectListLen(self.devid)
def returned_value(self, value):
if _debug:
ReadObjectList._debug("returned_value %r", value)
# update the device profile
devobj = device_profile[self.devid]
devobj.objectList = ArrayOf(ObjectIdentifier)(value)
# read the properties of the objects
for objid in value:
ReadObjectProperties(self.devid, objid)
#
# ReadPropertyMultipleToDo
#
@bacpypes_debugging
class ReadPropertyMultipleToDo(ToDoItem):
def __init__(self, devid, objid, proplist):
if _debug:
ReadPropertyMultipleToDo._debug("__init__ %r %r %r", devid, objid, proplist)
ToDoItem.__init__(self)
# save the parameters
self.devid = devid
self.objid = objid
self.proplist = proplist
# give it to the list
application_to_do_list.append(self)
def prepare(self):
if _debug:
ReadPropertyMultipleToDo._debug(
"prepare(%r %r %r)", self.devid, self.objid, self.proplist
)
# map the devid identifier to an address from the database
addr = snapshot.get_value(self.devid, "-", "address")
if not addr:
raise ValueError("unknown device")
if _debug:
ReadPropertyMultipleToDo._debug(" - addr: %r", addr)
prop_reference_list = [
PropertyReference(propertyIdentifier=propid) for propid in self.proplist
]
# build a read access specification
read_access_spec = ReadAccessSpecification(
objectIdentifier=self.objid, listOfPropertyReferences=prop_reference_list
)
# build the request
request = ReadPropertyMultipleRequest(
destination=Address(addr), listOfReadAccessSpecs=[read_access_spec]
)
if _debug:
ReadPropertyMultipleToDo._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug:
ReadPropertyMultipleToDo._debug(" - iocb: %r", iocb)
return iocb
def complete(self, iocb):
if _debug:
ReadPropertyMultipleToDo._debug("complete %r", iocb)
# do something for error/reject/abort
if iocb.ioError:
if interactive:
print(str(iocb.ioError))
# do something more
self.returned_error(iocb.ioError)
# do something for success
elif iocb.ioResponse:
apdu = iocb.ioResponse
# should be an ack
if not isinstance(apdu, ReadPropertyMultipleACK):
if _debug:
ReadPropertyMultipleToDo._debug(" - not an ack")
return
# loop through the results
for result in apdu.listOfReadAccessResults:
# here is the object identifier
objectIdentifier = result.objectIdentifier
if _debug:
ReadPropertyMultipleToDo._debug(
" - objectIdentifier: %r", objectIdentifier
)
# now come the property values per object
for element in result.listOfResults:
# get the property and array index
propertyIdentifier = element.propertyIdentifier
if _debug:
ReadPropertyMultipleToDo._debug(
" - propertyIdentifier: %r", propertyIdentifier
)
propertyArrayIndex = element.propertyArrayIndex
if _debug:
ReadPropertyMultipleToDo._debug(
" - propertyArrayIndex: %r", propertyArrayIndex
)
# here is the read result
readResult = element.readResult
property_label = str(propertyIdentifier)
if propertyArrayIndex is not None:
property_label += "[" + str(propertyArrayIndex) + "]"
# check for an error
if readResult.propertyAccessError is not None:
if interactive:
print(
"{} ! {}".format(