Example #1
0
 def __init__(self, *args):
     BIPSimpleApplication.__init__(Mock())
     self.elementService = Mock()
     self.ResponseQueue = Mock()
     self.ResponseQueue.get.return_value = (None, Event())
     self.request = Mock()
     self.value = None
Example #2
0
    def indication(self, apdu):
        """Given an I-Am request, cache it.
        Indication will treat unconfirmed messages on the stack
        
        :param apdu: apdu
        """
        if _debug: ScriptApplication._debug("do_IAmRequest %r", apdu)
        if isinstance(apdu, IAmRequest):
            # build a key from the source, just use the instance number
            key = (
                str(apdu.pduSource),
                apdu.iAmDeviceIdentifier[1],
            )
            # count the times this has been received
            self.i_am_counter[key] += 1

        if isinstance(apdu, WhoIsRequest):
            # build a key from the source and parameters
            key = (
                str(apdu.pduSource),
                apdu.deviceInstanceRangeLowLimit,
                apdu.deviceInstanceRangeHighLimit,
            )

            # count the times this has been received
            self.who_is_counter[key] += 1
            BIPSimpleApplication.do_WhoIsRequest(self, apdu)
        # pass back to the default implementation
        BIPSimpleApplication.indication(self, apdu)
def Init(pAddress):
    global this_application, this_ServerAdress

    this_ServerAdress = pAddress
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a simple application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value
Example #4
0
    def __init__(self, *args):
        BIPSimpleApplication.__init__(Mock())
        self.elementService = Mock()
        #self.ResponseQueue = Mock()
        #self.ResponseQueue.get.return_value = ([21, 'degreesCelcius'], Event())
        iocb = IOCB()
        apdu = ReadPropertyMultipleACK(listOfReadAccessResults=[
            ReadAccessResult(
                objectIdentifier=('analogValue', 1),
                listOfResults=[
                    ReadAccessResultElement(
                        propertyIdentifier='presentValue',
                        readResult=ReadAccessResultElementChoice(
                            propertyValue=Any(Real(21.0)), )),
                    ReadAccessResultElement(
                        propertyIdentifier='units',
                        readResult=ReadAccessResultElementChoice(
                            propertyValue=Any(Enumerated(62)), )),
                ],
            )
        ])

        iocb.complete(apdu)
        self.request = Mock()
        self.request.return_value = iocb
Example #5
0
    def indication(self, apdu):
        if _debug: WhoIsIAmApplication._debug("indication %r", apdu)

        if (isinstance(self._request, WhoIsRequest)) and (isinstance(apdu, IAmRequest)):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                raise DecodingError("invalid object type")

            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('\n')
                sys.stdout.write('Device Address        = ' + repr(apdu.pduSource) + '\n')
                sys.stdout.write('Device Id             = ' + str(device_instance) + '\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()
                if this_csv_file is not None:
                    row = {"address":apdu.pduSource,
                           "device_id": device_instance,
                           "max_apdu_length": apdu.maxAPDULengthAccepted,
                           "segmentation_supported": apdu.segmentationSupported,
                           "vendor_id": apdu.vendorID}
                    this_csv_file.writerow(row)

        # forward it along
        BIPSimpleApplication.indication(self, apdu)
Example #6
0
    def indication(self, apdu):
        if _debug: WhoIsIAmApplication._debug("indication %r", apdu)

        if (isinstance(self._request, WhoIsRequest)) and (isinstance(apdu, IAmRequest)):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                raise DecodingError("invalid object type")

            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('\n')
                sys.stdout.write('Device Address        = ' + 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
        BIPSimpleApplication.indication(self, apdu)
Example #7
0
    def indication(self, apdu):
        if _debug: WhoIsIAmApplication._debug("indication %r", apdu)

        if (isinstance(self._request, WhoIsRequest)) and (isinstance(apdu, IAmRequest)):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                raise DecodingError, "invalid object type"

            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
        BIPSimpleApplication.indication(self, apdu)
Example #8
0
def main():
    global vendor_id

    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _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 sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # make some objects
    ravo1 = VendorAVObject(objectIdentifier=(513, 1), objectName='Random1')
    if _debug: _log.debug("    - ravo1: %r", ravo1)

    ravo2 = VendorAVObject(objectIdentifier=(513, 2), objectName='Random2')
    if _debug: _log.debug("    - ravo2: %r", ravo2)

    # add it to the device
    this_application.add_object(ravo1)
    this_application.add_object(ravo2)
    if _debug: _log.debug("    - object list: %r", this_device.objectList)

    if _debug: _log.debug("running")

    run()

    if _debug: _log.debug("fini")
Example #9
0
    def __init__(
        self,
        bacpypes_inifile,
        brickbacnet_config,
        sqlite_db,
    ):
        self.logger = logging.getLogger('bacnet_discovery')
        self.logger.setLevel(logging.WARNING)
        config = configparser.ConfigParser()
        config.read(bacpypes_inifile)
        config = config["BACpypes"]
        self.address_mask = config["address"]  # TODO: What does this do?
        self.this_device = LocalDeviceObject(
            objectName=config["objectName"],
            objectIdentifier=int(config["objectIdentifier"]),
            maxApduLengthAccepted=int(config["maxApduLengthAccepted"]),
            segmentationSupported=config["segmentationSupported"],
            vendorIdentifier=int(config["vendorIdentifier"]),
            vendorName="brick-community",
        )
        self.sqlite_db = sqlite_db

        BIPSimpleApplication.__init__(self, self.this_device,
                                      config["address"])
        self.taskman = TaskManager()
        self.object_custom_fields = brickbacnet_config['object_custom_fields']
Example #10
0
    def __init__(self, *args):
        if _debug:
            WhoIsIAmApplication._debug("__init__ %r", args)
        BIPSimpleApplication.__init__(self, *args)

        # keep track of requests to line up responses
        self._request = None
Example #11
0
    def indication(self, apdu):
        if _debug: WhoIsIAmApplication._debug("indication %r", apdu)

        if (isinstance(self._request, WhoIsRequest)) and (isinstance(
                apdu, IAmRequest)):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                raise DecodingError("invalid object type")

            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:
                # Received I-am from target's Device instance
                dev_ObjID = apdu.iAmDeviceIdentifier
                dev_pdusource = apdu.pduSource

                point_list[0][0] = str(dev_pdusource)
                point_list[1][0] = str(dev_pdusource)
                point_list[0][2] = dev_ObjID[1]
                point_list[1][2] = dev_ObjID[1]

                #fire off request. read device properties model name and software version
                deferred(self.next_request)

        # forward it along
        BIPSimpleApplication.indication(self, apdu)
Example #12
0
    def next_request(self):
        if _debug: PrairieDog._debug("next_request")

        # check to see if we're done
        if not self.point_queue:
            if _debug: PrairieDog._debug("    - done")

            # dump out the results
            for request, response in zip(point_list, self.response_values):
                print request, response

            # no longer busy
            self.is_busy = False

            return

        # get the next request
        addr, obj_type, obj_inst, prop_id = self.point_queue.popleft()

        # build a request
        self._request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
            )
        self._request.pduDestination = Address(addr)
        if _debug: PrairieDog._debug("    - request: %r", self._request)

        # forward it along
        BIPSimpleApplication.request(self, self._request)
Example #13
0
    def __init__(self, *args):
        if _debug:
            ReadRangeApplication._debug("__init__ %r", args)
        BIPSimpleApplication.__init__(self, *args)

        # keep track of requests to line up responses
        self._request = None
 def __init__(self, *args):
     BIPSimpleApplication.__init__(Mock())
     self.elementService = Mock()
     self.ResponseQueue = Mock()
     self.ResponseQueue.get.return_value = ([21, 'degreesCelcius'], Event())
     self.request = Mock()
     self.value = None
Example #15
0
    def __init__(self, point_list, *args):
        if _debug:
            ReadPointListApplication._debug("__init__ %r, %r", point_list, args)
        BIPSimpleApplication.__init__(self, *args)

        # turn the point list into a queue
        self.point_queue = deque(point_list)
Example #16
0
	def indication(self, apdu):
		#
		# IAmRequest の 解析
		#
		if isinstance(apdu, IAmRequest):
			#
			# デバイスID, IPアドレスの取得
			#
			ipaddr = apdu.pduSource
			device_type, device_instance = apdu.iAmDeviceIdentifier

			#
			# デバイスID と IPアドレスのマッピング管理
			#
			self.device_map[device_instance] = ipaddr

			#
			# IAmRequest を 取得したことを通知する
			#
			self.responseQueue.put(device_instance)

		#
		# forward it along
		#
		BIPSimpleApplication.indication(self, apdu)
Example #17
0
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _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 sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # make a multistate value object
    msvo = MultiStateValueObject(
        objectIdentifier=('multiStateValue', 1),
        objectName='My Special Object',
        presentValue=1,
        numberOfStates=3,
        stateText=['red', 'green', 'blue'],
    )
    _log.debug("    - msvo: %r", msvo)

    # add it to the device
    this_application.add_object(msvo)
    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")
Example #18
0
    def __init__(self, *args):
        """
        Creation of the application. Adding properties to basic B/IP App.

        :param *args: local object device, local IP address
        See BAC0.scripts.BasicScript for more details.
        """
        logging.getLogger("comtypes").setLevel(logging.INFO)
        log_debug("__init__ %r", args)
        self.localAddress = None

        BIPSimpleApplication.__init__(self, *args)
        
        # _lock will be used by read/write operation to wait for answer before 
        # making another request
        self._lock = Lock()
        
        self._request = None
        self.value = None
        self.error = None
        self.values = []
        self.i_am_counter = defaultdict(int)
        self.who_is_counter = defaultdict(int)
        self.ResponseQueue = Queue()

        if isinstance(self.localAddress, Address):
            self.local_unicast_tuple = self.localAddress.addrTuple
            self.local_broadcast_tuple = self.localAddress.addrBroadcastTuple
        else:
            self.local_unicast_tuple = ('', 47808)
            self.local_broadcast_tuple = ('255.255.255.255', 47808)
Example #19
0
    def indication(self, apdu):
        """Given an I-Am request, cache it.
        Indication will treat unconfirmed messages on the stack
        
        :param apdu: apdu
        """
        if _debug: ScriptApplication._debug("do_IAmRequest %r", apdu)
        if isinstance(apdu, IAmRequest):
            # build a key from the source, just use the instance number
            key = (str(apdu.pduSource),
                   apdu.iAmDeviceIdentifier[1],
            )
            # count the times this has been received
            self.i_am_counter[key] += 1
        
        if isinstance(apdu, WhoIsRequest):        
        # build a key from the source and parameters
            key = (str(apdu.pduSource),
                apdu.deviceInstanceRangeLowLimit,
                apdu.deviceInstanceRangeHighLimit,
                )

        # count the times this has been received
            self.who_is_counter[key] += 1
            BIPSimpleApplication.do_WhoIsRequest(self, apdu)
        # pass back to the default implementation
        BIPSimpleApplication.indication(self, apdu)
Example #20
0
    def __init__(self, *args):
        """
        Creation of the application. Adding properties to basic B/IP App.

        :param *args: local object device, local IP address
        See BAC0.scripts.BasicScript for more details.
        """
        logging.getLogger("comtypes").setLevel(logging.INFO)
        log_debug("__init__ %r", args)
        self.localAddress = None

        BIPSimpleApplication.__init__(self, *args)

        # _lock will be used by read/write operation to wait for answer before
        # making another request
        self._lock = Lock()

        self._request = None
        self.value = None
        self.error = None
        self.values = []
        self.i_am_counter = defaultdict(int)
        self.who_is_counter = defaultdict(int)
        self.ResponseQueue = Queue()

        if isinstance(self.localAddress, Address):
            self.local_unicast_tuple = self.localAddress.addrTuple
            self.local_broadcast_tuple = self.localAddress.addrBroadcastTuple
        else:
            self.local_unicast_tuple = ('', 47808)
            self.local_broadcast_tuple = ('255.255.255.255', 47808)
    def __init__(self, ini_file, overriding_port: int = None):
        self.args = ConfigArgumentParser().parse_args(["--ini", ini_file])
        #addr = Address(self.args.ini.address)
        #if overriding_port:
        #    addr.addrPort = overriding_port
        #print('Address: {0}'.format(addr.addrPort))
        if overriding_port:
            ip, port = self.args.ini['address'].split(':')
            self.args.ini['address'] = ip + ':' + str(overriding_port)
        self.this_device = LocalDeviceObject(ini=self.args.ini)
        BIPSimpleApplication.__init__(self, self.this_device,
                                      self.args.ini['address'])
        self.taskman = TaskManager()
        self.datatype_map = {
            '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,
        }

        thread_handle = threading.Thread(target=self.run_thread)
        thread_handle.daemon = True
        thread_handle.start()
Example #22
0
 def __init__(self,*args,**kwarg):
     self.userdata=None
     device=LocalDeviceObject(vendorIdentifier=47808,objectIdentifier=47808)
     print('BacnetAppInit',*args,**kwarg)
     BIPSimpleApplication.__init__(self,device,*args,**kwarg)
     #time.sleep(0.8)#等待bac run
     self.whoisback=None
     self.who_is({})
Example #23
0
    def request(self, apdu):
        if _debug: SubscribeCOVApplication._debug("request %r", apdu)

        # save a copy of the request
        self._request = apdu

        # forward it along
        BIPSimpleApplication.request(self, apdu)
Example #24
0
    def request(self, apdu):
        """Sniff for Who-Is requests going downstream."""
        # save a copy of just the Who-Is request
        if isinstance(apdu, WhoIsRequest):
            self.who_is_request = apdu

        # forward it along
        BIPSimpleApplication.request(self, apdu)
Example #25
0
    def process_io(self, iocb):
        if _debug: WhoIsIAmApplication._debug("process_io %r", iocb)

        # save a copy of the request
        self._request = iocb.args[0]

        # forward it along
        BIPSimpleApplication.process_io(self, iocb)
Example #26
0
    def request(self, apdu):
        if _debug: BACnetAggregator._debug("request %r", apdu)

        # save a copy of the request
        self._request = apdu

        # forward it along
        BIPSimpleApplication.request(self, apdu)
    def request(self, apdu):
        if _debug: ReadPropertyApplication._debug("request %r", apdu)

        # save a copy of the request
        self._request = apdu

        # forward it along
        BIPSimpleApplication.request(self, apdu)
Example #28
0
    def request(self, apdu):
        if _debug: WhoIsIAmApplication._debug("request %r", apdu)

        # save a copy of the request
        self._request = apdu

        # forward it along
        BIPSimpleApplication.request(self, apdu)
Example #29
0
	def __init__(self, hmi, *args):
		self._debug = True
		self._hmi = hmi
		if self._debug: print("__init__ %r", args)
		BIPSimpleApplication.__init__(self, *args)
		if self._debug: print("super called")
		# keep track of requests to line up responses
		self._request = None
Example #30
0
    def __init__(self, *args):
        BIPSimpleApplication.__init__(self, *args)

        # assigning invoke identifiers
        self.nextInvokeID = 1

        # keep track of requests to line up responses
        self.iocb = {}
Example #31
0
    def __init__(self, *args):
        BIPSimpleApplication.__init__(self, *args)

        # assigning invoke identifiers
        self.nextInvokeID = 1

        # keep track of requests to line up responses
        self.iocb = {}
Example #32
0
File: api.py Project: hdqlife/blink
 def who_is(self,config):
     function.log('whoIs',config)
     self.userdata=[]
     BIPSimpleApplication.who_is(self,
         low_limit=config['lowlimits'],
         high_limit=config['highlimits']
     )
     return self.userdata
Example #33
0
    def request(self, apdu):
        #        if _debug: ReadPropertyApplication._debug("request %r", apdu)

        # save a copy of the request
        self._request = apdu

        # forward it along
        BIPSimpleApplication.request(self, apdu)
def main():
    global this_application, context

    # parse the command line arguments
    parser = ConfigArgumentParser(description=__doc__)
    parser.add_argument(
        "address",
        help="address of server",
    )
    parser.add_argument(
        "objtype",
        help="object type",
    )
    parser.add_argument(
        "objinst",
        type=int,
        help="object instance",
    )
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # set the context, the collection of the above parameters
    context = args.address, args.objtype, args.objinst
    if _debug: _log.debug("    - context: %r", context)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a simple application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value

    # make a console
    this_console = ReadWritePropertyConsoleCmd()
    if _debug: _log.debug("    - this_console: %r", this_console)

    # enable sleeping will help with threads
    enable_sleeping()

    _log.debug("running")

    run()

    _log.debug("fini")
Example #35
0
	def request(self, apdu):
		if self._debug: print("request %r", apdu)

		# save a copy of the request
		self._request = apdu

		# forward it along
		BIPSimpleApplication.request(self, apdu)
		if self._debug: print "ok"
    def __init__(self, point_list, *args):
        if _debug: ReadPointListApplication._debug("__init__ %r, %r", point_list, args)
        BIPSimpleApplication.__init__(self, *args)

        # turn the point list into a queue
        self.point_queue = deque(point_list)

        # make a list of the response values
        self.response_values = []
    def __init__(self, *args):
        if _debug: WebServerApplication._debug("__init__ %r", args)
        BIPSimpleApplication.__init__(self, *args)

        # assigning invoke identifiers
        self.nextInvokeID = 1

        # keep track of requests to line up responses
        self.iocb = {}
Example #38
0
 def do_request(self, apdu, iocb):
     # assign an invoke identifier
     apdu.apduInvokeID = self.get_next_invoke_id(apdu.pduDestination)
     # build a key to reference the IOCB when the response comes back
     invoke_key = (apdu.pduDestination, apdu.apduInvokeID)
     # keep track of the request
     self.iocb[invoke_key] = iocb
     # forward it along, apduInvokeID set by stack
     BIPSimpleApplication.request(self, apdu)
Example #39
0
    def response(self, apdu):
        if _debug: TestApplication._debug("response %r", apdu)

        # check for loopback
        if apdu.pduDestination == self.localAddress:
            if _debug: TestApplication._debug("    - loopback")
            deferred(self.confirmation, apdu)
        else:
            BIPSimpleApplication.response(self, apdu)
def main():
    global args

    # parse the command line arguments
    parser = ConfigArgumentParser(description=__doc__)

    # add an option to override the sleep time
    parser.add_argument(
        '--sleep',
        type=float,
        help="sleep before returning the value",
        default=SLEEP_TIME,
    )

    # parse the command line arguments
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=('device', int(args.ini.objectidentifier)),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value

    # make some random input objects
    for i in range(1, RANDOM_OBJECT_COUNT + 1):
        ravo = RandomAnalogValueObject(
            objectIdentifier=('analogValue', i),
            objectName='Random-%d' % (i, ),
        )
        _log.debug("    - ravo: %r", ravo)
        this_application.add_object(ravo)

    # make sure they are all there
    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")
Example #41
0
    def do_IAmRequest(self, apdu):
        """Given an I-Am request, cache it."""
        self.log(("do_IAmRequest {!r}".format(apdu)))

        # build a key from the source, just use the instance number
        key = (str(apdu.pduSource), apdu.iAmDeviceIdentifier[1])
        self.i_am_counter[key] += 1

        # continue with the default implementation
        BIPSimpleApplication.do_IAmRequest(self, apdu)
Example #42
0
 def who_is(self,config,back=None):
     #self.i_am()
     print('whoIs',config)
     self.userdata=[]
     self.whoisback=back
     BIPSimpleApplication.who_is(self,
         low_limit=config.get('lowlimits',0),
         high_limit=config.get('highlimits',10000)
     )
     return self.userdata
Example #43
0
    def __init__(self, interval, *args):
        if _debug: PrairieDog._debug("__init__ %r %r", interval, args)
        BIPSimpleApplication.__init__(self, *args)
        RecurringTask.__init__(self, interval * 1000)

        # no longer busy
        self.is_busy = False

        # install the task
        self.install_task()
    def __init__(self, point_list, *args):
        if _debug: ReadPointListApplication._debug("__init__ %r, %r", point_list, args)
        BIPSimpleApplication.__init__(self, *args)

        # keep track of requests to line up responses
        self._request = None

        # make a list of the response values
        self.response_values = []

        # turn the point list into a queue
        self.point_queue = deque(point_list)
Example #45
0
def main():
    if _debug: main._debug("initialization")

    try:
        # parse the command line arguments
        args = ConfigArgumentParser(description=__doc__).parse_args()

        if _debug: main._debug("initialization")
        if _debug: main._debug("    - args: %r", args)

        # make a device object
        this_device = LocalDeviceObject(
            objectName=args.ini.objectname,
            objectIdentifier=int(args.ini.objectidentifier),
            maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
            segmentationSupported=args.ini.segmentationsupported,
            vendorIdentifier=vendor_id,
            )

        # make a sample application
        this_application = BIPSimpleApplication(this_device, args.ini.address)

        # get the services supported
        services_supported = this_application.get_services_supported()
        if _debug: _log.debug("    - services_supported: %r", services_supported)

        # let the device object know
        this_device.protocolServicesSupported = services_supported.value

        # make some objects
        ravo1 = VendorAVObject(
            objectIdentifier=(513, 1), objectName='Random1'
            )
        if _debug: main._debug("    - ravo1: %r", ravo1)

        ravo2 = VendorAVObject(
            objectIdentifier=(513, 2), objectName='Random2'
            )
        if _debug: main._debug("    - ravo2: %r", ravo2)

        # add it to the device
        this_application.add_object(ravo1)
        this_application.add_object(ravo2)
        if _debug: main._debug("    - object list: %r", this_device.objectList)

        if _debug: main._debug("running")

        run()

    except Exception as error:
        main._exception("an error has occurred: %s", error)
    finally:
        if _debug: main._debug("finally")
Example #46
0
    def __init__(self, *args):
        BIPSimpleApplication.__init__(self, *args)
        RecurringTask.__init__(self, 250)
        self.request_queue = Queue()

        # assigning invoke identifiers
        self.nextInvokeID = 1

        # keep track of requests to line up responses
        self.iocb = {}
        
        self.install_task()
Example #47
0
    def indication(self, apdu):
        if isinstance(apdu, IAmRequest):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                # Bail without an error.
                return

            _log.debug("Calling IAm callback.")

            self.i_am_callback(str(apdu.pduSource),
                               device_instance,
                               apdu.maxAPDULengthAccepted,
                               str(apdu.segmentationSupported),
                               apdu.vendorID)

        elif isinstance(apdu, ConfirmedCOVNotificationRequest):
            # Handling for ConfirmedCOVNotificationRequests. These requests are
            # sent by the device when a point with a COV subscription updates
            # past the covIncrement threshold(See COV_Detection class in
            # Bacpypes:
            # https://bacpypes.readthedocs.io/en/latest/modules/service/cov.html)
            _log.debug("ConfirmedCOVNotificationRequest received from {}"
                       .format(apdu.pduSource))
            point_name = None
            device_path = None

            result_dict = {}
            for element in apdu.listOfValues:
                property_id = element.propertyIdentifier
                if not property_id == "statusFlags":
                    values = []
                    for tag in element.value.tagList:
                        values.append(tag.app_to_object().value)
                    if len(values) == 1:
                        result_dict[property_id] = values[0]
                    else:
                        result_dict[property_id] = values

            if result_dict:
                context = \
                    self.sub_cov_contexts[apdu.subscriberProcessIdentifier]
                point_name = context.point_name
                device_path = context.device_path

            if point_name and device_path:
                self.forward_cov_callback(device_path, point_name, result_dict)
            else:
                _log.debug("Device {} does not have a subscription context."
                           .format(apdu.monitoredObjectIdentifier))

        # forward it along
        BIPSimpleApplication.indication(self, apdu)
    def do_IAmRequest(self, apdu):
        """Given an I-Am request, cache it."""
        if _debug:
            WhoIsIAmApplication._debug("do_IAmRequest %r", apdu)

        # build a key from the source, just use the instance number
        key = (str(apdu.pduSource), apdu.iAmDeviceIdentifier[1])

        # count the times this has been received
        i_am_counter[key] += 1

        # continue with the default implementation
        BIPSimpleApplication.do_IAmRequest(self, apdu)
    def do_WhoIsRequest(self, apdu):
        """Respond to a Who-Is request."""
        if _debug:
            WhoIsIAmApplication._debug("do_WhoIsRequest %r", apdu)

        # build a key from the source and parameters
        key = (str(apdu.pduSource), apdu.deviceInstanceRangeLowLimit, apdu.deviceInstanceRangeHighLimit)

        # count the times this has been received
        who_is_counter[key] += 1

        # continue with the default implementation
        BIPSimpleApplication.do_WhoIsRequest(self, apdu)
Example #50
0
    def request(self, iocb):
        apdu = iocb.ioRequest

        # assign an invoke identifier
        apdu.apduInvokeID = self.get_next_invoke_id(apdu.pduDestination)

        # build a key to reference the IOCB when the response comes back
        invoke_key = (apdu.pduDestination, apdu.apduInvokeID)

        # keep track of the request
        self.iocb[invoke_key] = iocb
        
        BIPSimpleApplication.request(self, apdu)
    def __init__(self, interval, *args):
        if _debug: PrairieDog._debug("__init__ %r, %r", interval, args)
        BIPSimpleApplication.__init__(self, *args)
        RecurringTask.__init__(self, interval * 1000)

        # keep track of requests to line up responses
        self._request = None

        # start out idle
        self.is_busy = False
        self.point_queue = deque()
        self.response_values = []

        # install it
        self.install_task()
    def do_WhoIsRequest(self, apdu):
        """Respond to a Who-Is request."""
        self.log(("do_WhoIsRequest {!r}".format(apdu)))

        # build a key from the source and parameters
        key = (
            str(apdu.pduSource),
            apdu.deviceInstanceRangeLowLimit,
            apdu.deviceInstanceRangeHighLimit,
        )

        # count the times this has been received
        self.who_is_counter[key] += 1

        # continue with the default implementation
        BIPSimpleApplication.do_WhoIsRequest(self, apdu)
Example #53
0
    def indication(self, apdu):
        if isinstance(apdu, IAmRequest):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                #Bail without an error.
                return

            _log.debug("Calling IAm callback.")

            self.i_am_callback(str(apdu.pduSource),
                               device_instance,
                               apdu.maxAPDULengthAccepted,
                               str(apdu.segmentationSupported),
                               apdu.vendorID)

        # forward it along
        BIPSimpleApplication.indication(self, apdu)
Example #54
0
    def __init__(self, *args):
        """Creation of the application. Adding properties to basic B/IP App.
        
        :param *args: local object device, local IP address
        
        See BAC0.scripts.BasicScript for more details.
        """
        if _debug: ScriptApplication._debug("__init__ %r", args)
        BIPSimpleApplication.__init__(self, *args)

        # keep track of requests to line up responses
        self._request = None
        self.value = None
        self.error = None
        self.values = []
        self.i_am_counter = defaultdict(int)
        self.ResponseQueue = Queue()
Example #55
0
 def request(self, iocb):
     apdu = iocb.ioRequest
     
     if isinstance(apdu, ConfirmedRequestSequence):
         # assign an invoke identifier
         apdu.apduInvokeID = self.get_next_invoke_id(apdu.pduDestination)
 
         # build a key to reference the IOCB when the response comes back
         invoke_key = (apdu.pduDestination, apdu.apduInvokeID)
 
         # keep track of the request
         self.iocb[invoke_key] = iocb
     
     try:    
         BIPSimpleApplication.request(self, apdu)
     except StandardError as e:
         iocb.set_exception(e)
Example #56
0
def main():
    global this_application

    # check the version
    if (sys.version_info[:2] != (2, 5)):
        sys.stderr.write("Python 2.5 only\n")
        sys.exit(1)

    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
        )

    # make a simple application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value

    # make a console
    this_console = ReadPropertyConsoleCmd()
    if _debug: _log.debug("    - this_console: %r", this_console)

    # enable sleeping will help with threads
    enable_sleeping()

    _log.debug("running")

    run()

    _log.debug("fini")
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
        )

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value

    # make a multistate value object
    msvo = MultiStateValueObject(
        objectIdentifier=('multiStateValue', 1),
        objectName='My Special Object',
        presentValue=1,
        numberOfStates=3,
        stateText=ArrayOf(CharacterString)(['red', 'green', 'blue']),
        )
    _log.debug("    - msvo: %r", msvo)

    # add it to the device
    this_application.add_object(msvo)
    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")
Example #58
0
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug:
        _log.debug("initialization")
    if _debug:
        _log.debug("    - args: %r", args)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # make a commandable analog value object, add to the device
    cavo1 = CommandableAnalogValueObject(objectIdentifier=("analogValue", 1), objectName="Commandable1")
    if _debug:
        _log.debug("    - cavo1: %r", cavo1)
    this_application.add_object(cavo1)

    # get the current date
    today = Date().now()

    # make a commandable date value object, add to the device
    cdvo2 = CommandableDateValueObject(
        objectIdentifier=("dateValue", 1), objectName="Commandable2", presentValue=today.value
    )
    if _debug:
        _log.debug("    - cdvo2: %r", cdvo2)
    this_application.add_object(cdvo2)

    if _debug:
        _log.debug("running")

    run()

    _log.debug("fini")