-
Notifications
You must be signed in to change notification settings - Fork 0
/
console_client.py
executable file
·746 lines (609 loc) · 24.9 KB
/
console_client.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
#!/usr/bin/env python
"""
This application presents a 'console' prompt to the user asking for Who-Is,
I-Am, or Read-Property commands.
"""
import sys
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import ConfigArgumentParser
from bacpypes.consolecmd import ConsoleCmd
from bacpypes.comm import bind
from bacpypes.core import run, deferred, enable_sleeping
from bacpypes.iocb import IOCB
from bacpypes.pdu import Address, GlobalBroadcast
from bacpypes.primitivedata import (
Null,
Atomic,
Boolean,
Unsigned,
Integer,
Real,
Double,
OctetString,
CharacterString,
BitString,
Date,
Time,
ObjectIdentifier,
)
from bacpypes.basetypes import PropertyIdentifier, PropertyReference
from bacpypes.apdu import (
WhoIsRequest,
IAmRequest,
ReadPropertyRequest,
ReadPropertyACK,
ReadPropertyMultipleRequest,
ReadAccessSpecification,
ReadPropertyMultipleACK,
WritePropertyRequest,
SimpleAckPDU,
)
from bacpypes.constructeddata import Array, Any, AnyAtomic
from bacpypes.app import ApplicationIOController
from bacpypes.appservice import StateMachineAccessPoint, ApplicationServiceAccessPoint
from bacpypes.netservice import NetworkServiceAccessPoint, NetworkServiceElement
from bacpypes.object import get_datatype
from bacpypes.local.device import LocalDeviceObject
# basic services
from bacpypes.service.device import WhoIsIAmServices
from bacpypes.service.object import ReadWritePropertyServices
import bacpypes_mqtt
# some debugging
_debug = 0
_log = ModuleLogger(globals())
# globals
args = None
this_device = None
this_application = None
#
# MQTTApplication
#
@bacpypes_debugging
class MQTTApplication(
ApplicationIOController, WhoIsIAmServices, ReadWritePropertyServices
):
def __init__(
self, localDevice, lan, localAddress, deviceInfoCache=None, aseID=None
):
if _debug:
MQTTApplication._debug(
"__init__ %r %r %r deviceInfoCache=%r aseID=%r",
localDevice,
lan,
localAddress,
deviceInfoCache,
aseID,
)
ApplicationIOController.__init__(
self, localDevice, localAddress, deviceInfoCache, aseID=aseID
)
global args
# local address might be useful for subclasses
if isinstance(localAddress, str):
localAddress = Address(localAddress)
if len(localAddress.addrAddr) != bacpypes_mqtt.ADDRESS_LENGTH:
raise ValueError(
"local address must be %d octets" % (bacpypes_mqtt.ADDRESS_LENGTH,)
)
self.localAddress = 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 = NetworkServiceElement()
bind(self.nse, self.nsap)
# bind the top layers
bind(self, self.asap, self.smap, self.nsap)
# create an MQTT client
self.msap = bacpypes_mqtt.MQTTClient(
lan,
localAddress,
args.host,
port=args.port,
username=args.username,
password=args.password,
keepalive=args.keepalive,
cafile=args.cafile,
)
# create a service element for the client
self.mse = bacpypes_mqtt.MQTTServiceElement()
bind(self.mse, self.msap)
# bind the stack to the virtual network, no network number
self.nsap.bind(self.msap)
# keep track of requests to line up responses
self._request = None
def request(self, apdu):
if _debug:
MQTTApplication._debug("request %r", apdu)
# save a copy of the request
self._request = apdu
# forward it along
super(MQTTApplication, self).request(apdu)
def indication(self, apdu):
if _debug:
MQTTApplication._debug("indication %r", apdu)
if (isinstance(self._request, WhoIsRequest)) and (isinstance(apdu, IAmRequest)):
device_type, device_instance = apdu.iAmDeviceIdentifier
if (self._request.deviceInstanceRangeLowLimit is not None) and (
device_instance < self._request.deviceInstanceRangeLowLimit
):
pass
elif (self._request.deviceInstanceRangeHighLimit is not None) and (
device_instance > self._request.deviceInstanceRangeHighLimit
):
pass
else:
# print out the contents
sys.stdout.write("pduSource = " + repr(apdu.pduSource) + "\n")
sys.stdout.write(
"iAmDeviceIdentifier = " + str(apdu.iAmDeviceIdentifier) + "\n"
)
sys.stdout.write(
"maxAPDULengthAccepted = " + str(apdu.maxAPDULengthAccepted) + "\n"
)
sys.stdout.write(
"segmentationSupported = " + str(apdu.segmentationSupported) + "\n"
)
sys.stdout.write("vendorID = " + str(apdu.vendorID) + "\n")
sys.stdout.flush()
# forward it along
super(MQTTApplication, self).indication(apdu)
def response(self, apdu):
if _debug:
MQTTApplication._debug("response %r", apdu)
# forward it along
super(MQTTApplication, self).response(apdu)
def confirmation(self, apdu):
if _debug:
MQTTApplication._debug("confirmation %r", apdu)
# forward it along
super(MQTTApplication, self).confirmation(apdu)
#
# ClientConsoleCmd
#
@bacpypes_debugging
class ClientConsoleCmd(ConsoleCmd):
def do_whois(self, args):
"""whois [ <addr>] [ <lolimit> <hilimit> ]"""
args = args.split()
if _debug:
ClientConsoleCmd._debug("do_whois %r", args)
try:
# build a request
request = WhoIsRequest()
if (len(args) == 1) or (len(args) == 3):
request.pduDestination = Address(args[0])
del args[0]
else:
request.pduDestination = GlobalBroadcast()
if len(args) == 2:
request.deviceInstanceRangeLowLimit = int(args[0])
request.deviceInstanceRangeHighLimit = int(args[1])
if _debug:
ClientConsoleCmd._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug:
ClientConsoleCmd._debug(" - iocb: %r", iocb)
# give it to the application
this_application.request_io(iocb)
except Exception as err:
ClientConsoleCmd._exception("exception: %r", err)
def do_iam(self, args):
"""iam [ addr ]"""
args = args.split()
if _debug:
ClientConsoleCmd._debug("do_iam %r", args)
global this_device
try:
# build a request
request = IAmRequest()
if len(args) == 1:
request.pduDestination = Address(args[0])
else:
request.pduDestination = GlobalBroadcast()
# set the parameters from the device object
request.iAmDeviceIdentifier = this_device.objectIdentifier
request.maxAPDULengthAccepted = this_device.maxApduLengthAccepted
request.segmentationSupported = this_device.segmentationSupported
request.vendorID = this_device.vendorIdentifier
if _debug:
ClientConsoleCmd._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug:
ClientConsoleCmd._debug(" - iocb: %r", iocb)
# give it to the application
this_application.request_io(iocb)
except Exception as err:
ClientConsoleCmd._exception("exception: %r", err)
def do_read(self, args):
"""read <addr> <type> <inst> <prop> [ <indx> ]"""
args = args.split()
if _debug:
ClientConsoleCmd._debug("do_read %r", args)
try:
addr, obj_id, prop_id = args[:3]
obj_id = ObjectIdentifier(obj_id).value
datatype = get_datatype(obj_id[0], prop_id)
if not datatype:
raise ValueError("invalid property for object type")
# build a request
request = ReadPropertyRequest(
objectIdentifier=obj_id, propertyIdentifier=prop_id
)
request.pduDestination = Address(addr)
if len(args) == 5:
request.propertyArrayIndex = int(args[4])
if _debug:
ClientConsoleCmd._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug:
ClientConsoleCmd._debug(" - iocb: %r", iocb)
# give it to the application
deferred(this_application.request_io, iocb)
# wait for it to complete
iocb.wait()
# do something for error/reject/abort
if iocb.ioError:
sys.stdout.write(str(iocb.ioError) + "\n")
# do something for success
elif iocb.ioResponse:
apdu = iocb.ioResponse
# should be an ack
if not isinstance(apdu, ReadPropertyACK):
if _debug:
ClientConsoleCmd._debug(" - not an ack")
return
# find the datatype
datatype = get_datatype(
apdu.objectIdentifier[0], apdu.propertyIdentifier
)
if _debug:
ClientConsoleCmd._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:
value = apdu.propertyValue.cast_out(Unsigned)
else:
value = apdu.propertyValue.cast_out(datatype.subtype)
else:
value = apdu.propertyValue.cast_out(datatype)
if _debug:
ClientConsoleCmd._debug(" - value: %r", value)
sys.stdout.write(str(value) + "\n")
if hasattr(value, "debug_contents"):
value.debug_contents(file=sys.stdout)
sys.stdout.flush()
# do something with nothing?
else:
if _debug:
ClientConsoleCmd._debug(" - ioError or ioResponse expected")
except Exception as error:
ClientConsoleCmd._exception("exception: %r", error)
def do_write(self, args):
"""write <addr> <objid> <prop> <value> [ <indx> ] [ <priority> ]"""
args = args.split()
ClientConsoleCmd._debug("do_write %r", args)
try:
addr, obj_id, prop_id = args[:3]
obj_id = ObjectIdentifier(obj_id).value
value = args[3]
indx = None
if len(args) >= 5:
if args[4] != "-":
indx = int(args[4])
if _debug:
ClientConsoleCmd._debug(" - indx: %r", indx)
priority = None
if len(args) >= 6:
priority = int(args[5])
if _debug:
ClientConsoleCmd._debug(" - priority: %r", priority)
# get the datatype
datatype = get_datatype(obj_id[0], prop_id)
if _debug:
ClientConsoleCmd._debug(" - datatype: %r", datatype)
# change atomic values into something encodeable, null is a special case
if value == "null":
value = Null()
elif issubclass(datatype, AnyAtomic):
dtype, dvalue = value.split(":", 1)
if _debug:
ClientConsoleCmd._debug(
" - dtype, dvalue: %r, %r", dtype, dvalue
)
datatype = {
"b": Boolean,
"u": lambda x: Unsigned(int(x)),
"i": lambda x: Integer(int(x)),
"r": lambda x: Real(float(x)),
"d": lambda x: Double(float(x)),
"o": OctetString,
"c": CharacterString,
"bs": BitString,
"date": Date,
"time": Time,
"id": ObjectIdentifier,
}[dtype]
if _debug:
ClientConsoleCmd._debug(" - datatype: %r", datatype)
value = datatype(dvalue)
if _debug:
ClientConsoleCmd._debug(" - value: %r", value)
elif issubclass(datatype, Atomic):
if datatype is Integer:
value = int(value)
elif datatype is Real:
value = float(value)
elif datatype is Unsigned:
value = int(value)
value = datatype(value)
elif issubclass(datatype, Array) and (indx is not None):
if indx == 0:
value = Integer(value)
elif issubclass(datatype.subtype, Atomic):
value = datatype.subtype(value)
elif not isinstance(value, datatype.subtype):
raise TypeError(
"invalid result datatype, expecting %s"
% (datatype.subtype.__name__,)
)
elif not isinstance(value, datatype):
raise TypeError(
"invalid result datatype, expecting %s" % (datatype.__name__,)
)
if _debug:
ClientConsoleCmd._debug(
" - encodeable value: %r %s", value, type(value)
)
# build a request
request = WritePropertyRequest(
objectIdentifier=obj_id, propertyIdentifier=prop_id
)
request.pduDestination = Address(addr)
# save the value
request.propertyValue = Any()
try:
request.propertyValue.cast_in(value)
except Exception as error:
ClientConsoleCmd._exception("WriteProperty cast error: %r", error)
# optional array index
if indx is not None:
request.propertyArrayIndex = indx
# optional priority
if priority is not None:
request.priority = priority
if _debug:
ClientConsoleCmd._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug:
ClientConsoleCmd._debug(" - iocb: %r", iocb)
# give it to the application
deferred(this_application.request_io, iocb)
# wait for it to complete
iocb.wait()
# do something for success
if iocb.ioResponse:
# should be an ack
if not isinstance(iocb.ioResponse, SimpleAckPDU):
if _debug:
ClientConsoleCmd._debug(" - not an ack")
return
sys.stdout.write("ack\n")
# do something for error/reject/abort
if iocb.ioError:
sys.stdout.write(str(iocb.ioError) + "\n")
except Exception as error:
ClientConsoleCmd._exception("exception: %r", error)
def do_rpm(self, args):
"""rpm <addr> ( <objid> ( <prop> [ <indx> ] )... )..."""
args = args.split()
if _debug:
ClientConsoleCmd._debug("do_rpm %r", args)
try:
i = 0
addr = args[i]
i += 1
read_access_spec_list = []
while i < len(args):
obj_id = ObjectIdentifier(args[i]).value
i += 1
prop_reference_list = []
while i < len(args):
prop_id = args[i]
if prop_id not in PropertyIdentifier.enumerations:
break
i += 1
if prop_id in ("all", "required", "optional"):
pass
else:
datatype = get_datatype(obj_id[0], prop_id)
if not datatype:
raise ValueError("invalid property for object type")
# build a property reference
prop_reference = PropertyReference(propertyIdentifier=prop_id)
# check for an array index
if (i < len(args)) and args[i].isdigit():
prop_reference.propertyArrayIndex = int(args[i])
i += 1
# add it to the list
prop_reference_list.append(prop_reference)
# check for at least one property
if not prop_reference_list:
raise ValueError("provide at least one property")
# build a read access specification
read_access_spec = ReadAccessSpecification(
objectIdentifier=obj_id,
listOfPropertyReferences=prop_reference_list,
)
# add it to the list
read_access_spec_list.append(read_access_spec)
# check for at least one
if not read_access_spec_list:
raise RuntimeError("at least one read access specification required")
# build the request
request = ReadPropertyMultipleRequest(
listOfReadAccessSpecs=read_access_spec_list
)
request.pduDestination = Address(addr)
if _debug:
ClientConsoleCmd._debug(" - request: %r", request)
# make an IOCB
iocb = IOCB(request)
if _debug:
ClientConsoleCmd._debug(" - iocb: %r", iocb)
# give it to the application
deferred(this_application.request_io, iocb)
# wait for it to complete
iocb.wait()
# do something for success
if iocb.ioResponse:
apdu = iocb.ioResponse
# should be an ack
if not isinstance(apdu, ReadPropertyMultipleACK):
if _debug:
ClientConsoleCmd._debug(" - not an ack")
return
# loop through the results
for result in apdu.listOfReadAccessResults:
# here is the object identifier
objectIdentifier = result.objectIdentifier
if _debug:
ClientConsoleCmd._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:
ClientConsoleCmd._debug(
" - propertyIdentifier: %r", propertyIdentifier
)
propertyArrayIndex = element.propertyArrayIndex
if _debug:
ClientConsoleCmd._debug(
" - propertyArrayIndex: %r", propertyArrayIndex
)
# here is the read result
readResult = element.readResult
sys.stdout.write(str(propertyIdentifier))
if propertyArrayIndex is not None:
sys.stdout.write("[" + str(propertyArrayIndex) + "]")
# check for an error
if readResult.propertyAccessError is not None:
sys.stdout.write(
" ! " + str(readResult.propertyAccessError) + "\n"
)
else:
# here is the value
propertyValue = readResult.propertyValue
# find the datatype
datatype = get_datatype(
objectIdentifier[0], propertyIdentifier
)
if _debug:
ClientConsoleCmd._debug(" - datatype: %r", datatype)
if not datatype:
value = "?"
else:
# special case for array parts, others are managed by cast_out
if issubclass(datatype, Array) and (
propertyArrayIndex is not None
):
if propertyArrayIndex == 0:
value = propertyValue.cast_out(Unsigned)
else:
value = propertyValue.cast_out(datatype.subtype)
else:
value = propertyValue.cast_out(datatype)
if _debug:
ClientConsoleCmd._debug(" - value: %r", value)
sys.stdout.write(" = " + str(value) + "\n")
sys.stdout.flush()
# do something for error/reject/abort
if iocb.ioError:
sys.stdout.write(str(iocb.ioError) + "\n")
except Exception as error:
ClientConsoleCmd._exception("exception: %r", error)
def do_rtn(self, args):
"""rtn <addr> <net> ... """
args = args.split()
if _debug:
ClientConsoleCmd._debug("do_rtn %r", args)
# provide the address and a list of network numbers
router_address = Address(args[0])
network_list = [int(arg) for arg in args[1:]]
# pass along to the service access point
this_application.nsap.add_router_references(None, router_address, network_list)
#
# __main__
#
def main():
global args, this_device, this_application
# build a parser, add some options
parser = ConfigArgumentParser(description=__doc__)
parser.add_argument(
"--lan", type=str, default=bacpypes_mqtt.default_lan_name, help="lan name"
)
parser.add_argument(
"--host",
type=str,
default=bacpypes_mqtt.default_broker_host,
help="broker host address",
)
parser.add_argument(
"--port",
type=int,
default=bacpypes_mqtt.default_broker_port,
help="broker port",
)
parser.add_argument("--username", type=str, default=None, help="broker username")
parser.add_argument("--password", type=str, default=None, help="broker password")
parser.add_argument(
"--keepalive",
type=int,
default=bacpypes_mqtt.default_broker_keepalive,
help="maximum period in seconds allowed between communications with the broker",
)
parser.add_argument("--cafile", type=str, default=None, help="server certificate")
# parse the command line arguments
args = parser.parse_args()
if _debug:
_log.debug("initialization")
_log.debug(" - args: %r", args)
# make a device object
this_device = LocalDeviceObject(ini=args.ini)
if _debug:
_log.debug(" - this_device: %r", this_device)
# make a simple application
this_application = MQTTApplication(this_device, args.lan, args.ini.address)
# make a console
this_console = ClientConsoleCmd()
if _debug:
_log.debug(" - this_console: %r", this_console)
# enable sleeping will help with threads
enable_sleeping()
# start up the client
this_application.mse.startup()
_log.debug("running")
run()
# shutdown the client
this_application.mse.shutdown()
_log.debug("fini")
if __name__ == "__main__":
main()