def next_request(self):
        if _debug: ReadPointListApplication._debug("next_request")

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

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

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

        # make an IOCB
        iocb = IOCB(request)

        # set a callback for the response
        iocb.add_callback(self.complete_request)
        if _debug: ReadPointListApplication._debug("    - iocb: %r", iocb)

        # send the request
        this_application.request_io(iocb)
Example #2
0
    def do_read(self, args):
        """read <addr> <objid> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: TestConsoleCmd._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) == 4:
                request.propertyArrayIndex = int(args[3])
            if _debug: TestConsoleCmd._debug("    - request: %r", request)

            # give it to the application
            vlan_app_1.request(request)

        except Exception, e:
            TestConsoleCmd._exception("exception: %r", e)
Example #3
0
def create_ReadPropertyRequest(args):
    """
    Create a ReadPropertyRequest from a string
    """
    args = args.split()
    addr, obj_type, obj_inst, prop_id = args[:4]
    print(addr)

    if obj_type.isdigit():
        obj_type = int(obj_type)
    elif not get_object_class(obj_type):
        raise ValueError("unknown object type")

    obj_inst = int(obj_inst)

    datatype = get_datatype(obj_type, prop_id)
    if not datatype:
        raise ValueError("invalid property for object type")

    # build a request
    request = ReadPropertyRequest(
        objectIdentifier=(obj_type, obj_inst),
        propertyIdentifier=prop_id,
    )
    request.pduDestination = Address(addr)

    if len(args) == 5:
        request.propertyArrayIndex = int(args[4])

    return request
Example #4
0
    def build_rp_request(self, args, arr_index=None, vendor_id=0, bacoid=None):
        addr, obj_type, obj_inst, prop_id = args[:4]
        vendor_id = vendor_id
        bacoid = bacoid

        if obj_type.isdigit():
            obj_type = int(obj_type)
        elif not get_object_class(obj_type):
            raise ValueError("unknown object type")

        obj_inst = int(obj_inst)

        if prop_id.isdigit():
            prop_id = int(prop_id)
        datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id)
        if not datatype:
            raise ValueError("invalid property for object type")

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
            propertyArrayIndex=arr_index,
        )
        request.pduDestination = Address(addr)

        if len(args) == 5:
            request.propertyArrayIndex = int(args[4])
        self._log.debug("{:<20} {!r}".format(
            'REQUEST', request))
        return request
    def do_read(self, args):
        """read <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: TestConsoleCmd._debug("do_read %r", args)

        try:
            addr, objType, objInst, propId = args[:4]
            if objType.isdigit():
                objType = int(objType)
            objInst = int(objInst)

            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(objType, objInst),
                propertyIdentifier=propId,
            )
            request.pduDestination = Address(addr)
            if len(args) == 5:
                request.propertyArrayIndex = int(args[4])
            if _debug: TestConsoleCmd._debug("    - request: %r", request)

            # give it to the application
            this_application.request(request)

        except Exception, e:
            TestConsoleCmd._exception("exception: %r", e)
Example #6
0
    def next_request(self):
        if _debug: ReadPointListApplication._debug("next_request")

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

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

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

        # make an IOCB
        iocb = IOCB(request)

        # set a callback for the response
        iocb.add_callback(self.complete_request)
        if _debug: ReadPointListApplication._debug("    - iocb: %r", iocb)

        # send the request
        this_application.request_io(iocb)
    def do_read(self, args):
        """read <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadWritePropertyConsoleCmd._debug("do_read %r", args)

        try:
            addr, obj_type, obj_inst, prop_id = args[:4]

            if obj_type.isdigit():
                obj_type = int(obj_type)
            elif not get_object_class(obj_type):
                raise ValueError, "unknown object type"

            obj_inst = int(obj_inst)

            datatype = get_datatype(obj_type, prop_id)
            if not datatype:
                raise ValueError, "invalid property for object type"

            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
                )
            request.pduDestination = Address(addr)

            if len(args) == 5:
                request.propertyArrayIndex = int(args[4])
            if _debug: ReadWritePropertyConsoleCmd._debug("    - request: %r", request)

            # give it to the application
            this_application.request(request)

        except Exception, e:
            ReadWritePropertyConsoleCmd._exception("exception: %r", e)
Example #8
0
    def _discovery(self):
        global device_address

        # build a request
        obj_type, prop_id = ('device', 'objectList')

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, self._device_id),
            propertyIdentifier=prop_id,
        )
        request.pduSource = Address(this_device._address)
        request.pduDestination = Address(int(self._addr))
        request.propertyArrayIndex = self._instance_list.pop(0)

        if _debug:
            BacnetClientConsoleCmd._debug("    - request: %r", request)

        # make an IOCB
        iocb = IOCB(request)

        # set a callback for the response
        iocb.add_callback(self._discovery_response)
        if _debug:
            BacnetClientConsoleCmd._debug("    - iocb: %r", iocb)

        # send the request
        this_application.request_io(iocb)
Example #9
0
    def build_rp_request(self, args, arr_index=None, vendor_id=0, bacoid=None):
        addr, obj_type, obj_inst, prop_id = args[:4]
        vendor_id = vendor_id
        bacoid = bacoid

        if obj_type.isdigit():
            obj_type = int(obj_type)
        elif not get_object_class(obj_type):
            raise ValueError("unknown object type")

        obj_inst = int(obj_inst)

        if prop_id.isdigit():
            prop_id = int(prop_id)
        datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id)
        if not datatype:
            raise ValueError("invalid property for object type")

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
            propertyArrayIndex=arr_index,
        )
        request.pduDestination = Address(addr)

        if len(args) == 5:
            request.propertyArrayIndex = int(args[4])
        self._log.debug("{:<20} {!r}".format("REQUEST", request))
        return request
Example #10
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
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
        )
        request.pduDestination = Address(addr)
        if _debug: PrairieDog._debug("    - request: %r", request)

        # send the request
        iocb = self.request(request)
        if _debug: PrairieDog._debug("    - iocb: %r", iocb)

        # set a callback for the response
        iocb.add_callback(self.complete_request)
Example #11
0
    def _build_rp_request(self):
        addr = self.address()
        obj_type = self.obj_type()
        prop_id = self.property_id()
        vendor_id = self.vendor_id()
        bacoid = self.id()

        if obj_type.isdigit():
            obj_type = int(self.obj_type)
        elif not get_object_class(obj_type):
            raise ValueError("unknown object type")

        obj_inst = int(self.instance())

        if prop_id.isdigit():
            prop_id = int(prop_id)
        datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id)
        if not datatype:
            raise ValueError("invalid property for object type")

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
            propertyArrayIndex=self.array_index(),
        )
        request.pduDestination = Address(self.address())

        self.logger.debug("{:<20} {!r}".format('REQUEST', request))
        return request
Example #12
0
    def test_readProperty(self):

        request = ReadPropertyRequest(objectIdentifier=('analogInput', 14), propertyIdentifier=85)
        request.apduMaxResp = 1024
        request.apduInvokeID = 101
        apdu = APDU()
        request.encode(apdu)
        pdu = PDU()
        apdu.encode(pdu)
        buf_size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto(pdu.pduData, ('127.0.0.1', self.bacnet_server.server.server_port))
        data = s.recvfrom(buf_size)

        received_data = data[0]

        expected = ReadPropertyACK()
        expected.pduDestination = GlobalBroadcast()
        expected.apduInvokeID = 101
        expected.objectIdentifier = 14
        expected.objectName = 'AI 01'
        expected.propertyIdentifier = 85
        expected.propertyValue = Any(Real(68.0))

        exp_apdu = APDU()
        expected.encode(exp_apdu)
        exp_pdu = PDU()
        exp_apdu.encode(exp_pdu)

        self.assertEquals(exp_pdu.pduData, received_data)
Example #13
0
    def next_request(self):

        # check to see if we're done
        if not self.point_queue:
            stop()
            return

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

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
            propertyArrayIndex=idx
            )
        request.pduDestination = Address(addr)

        # make an IOCB
        iocb = IOCB(request)

        # set a callback for the response
        iocb.add_callback(self.complete_request)

        # send the request
        self.request_io(iocb)
Example #14
0
    def read(self, obj_type, obj_inst, prop_id, address):
        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            print("invalid property %s for object type %s" % (prop_id,object_type))
            return "error invalid property %s for object type %s" % (prop_id,object_type)

        # build a request
        request = ReadPropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id)
        request.pduDestination = Address(address)

        # TODO: How do we handle an index? This is a 'parameterized get' case that uses b
        # request.propertyArrayIndex = <handle me>

        # build an IOCB, save the request
        iocb = IOCB()
        iocb.ioRequest = request

        # give it to the application to send
        _ss.bacnet_app.do_request(request, iocb)

        # wait for the response
        iocb.ioComplete.wait()

        # filter out errors and aborts
        if isinstance(iocb.ioResponse, Error) or isinstance(iocb.ioResponse, AbortPDU):
            print( "get operation failed %s %s %s" % (obj_type, obj_inst, str(iocb.ioResponse)))
            n = "error get operation failed %s %s %s" % (obj_type, obj_inst, str(iocb.ioResponse))
        else:
            n = self._value_format(prop_id,iocb.ioResponse)
            
        print("read %s %s %s %s" % (address, obj_inst, prop_id, n))

        return n
Example #15
0
def create_ReadPropertyRequest(args):
    """
    Create a ReadPropertyRequest from a string
    """
    args = args.split()
    addr, obj_type, obj_inst, prop_id = args[:4]
    print(addr)

    if obj_type.isdigit():
        obj_type = int(obj_type)
    elif not get_object_class(obj_type):
        raise ValueError("unknown object type")

    obj_inst = int(obj_inst)

    datatype = get_datatype(obj_type, prop_id)
    if not datatype:
        raise ValueError("invalid property for object type")

    # build a request
    request = ReadPropertyRequest(
        objectIdentifier=(obj_type, obj_inst),
        propertyIdentifier=prop_id,
    )
    request.pduDestination = Address(addr)

    if len(args) == 5:
        request.propertyArrayIndex = int(args[4])

    return request
Example #16
0
    def build_rp_request(self, args, arr_index = None):
        addr, obj_type, obj_inst, prop_id = args[:4]

        if obj_type.isdigit():
            obj_type = int(obj_type)
        elif not get_object_class(obj_type):
            raise ValueError("unknown object type")

        obj_inst = int(obj_inst)

        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            raise ValueError("invalid property for object type")

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
            propertyArrayIndex=arr_index,
        )
        request.pduDestination = Address(addr)

        if len(args) == 5:
            request.propertyArrayIndex = int(args[4])
        log_debug(ReadProperty, "    - request: %r", request)

        return request              
Example #17
0
    def do_read(self):
        try:
            # query the present value of 'MLNTZ.PNL.J.DEMAND'
            obj_type = datapoints[point_count]['obj_type']
            obj_inst = datapoints[point_count]['obj_inst']
            prop_id =  datapoints[point_count]['prop_id']
            
            if not get_object_class(obj_type):
                raise ValueError, "unknown object type: " + obj_type

            datatype = get_datatype(obj_type, prop_id)
            if not datatype:
                raise ValueError, "invalid property for object type: " + prop_id

            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
                )
            request.pduDestination = Address(self.foreign_addr)

            # give it to the application
            self.app.request(request)

        except Exception, e:
            _log.exception("exception: %r", e)
Example #18
0
    def read_prop_vendor(self):
        #get bacnet source pdu from point_list array. point_list has been override by next_request method
        addr = point_list[0][0]

        obj_type = self.obj
        obj_inst = self.inst
        prop_id = self.prop

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=int(prop_id),
        )
        request.pduDestination = Address(addr)

        request.propertyArrayIndex = self.idx
        #if _debug: ReadPropertyAnyConsoleCmd._debug("    - request: %r", request)

        # make an IOCB
        iocb = IOCB(request)

        #if _debug: ReadPropertyAnyConsoleCmd._debug("    - iocb: %r", iocb)

        # set a callback for the response
        iocb.add_callback(self.prop_vendor_ack)

        # give it to the application
        this_application.request_io(iocb)
Example #19
0
    def build_rp_request(self, args):
        addr, obj_type, obj_inst, prop_id = args[:4]

        if obj_type.isdigit():
            obj_type = int(obj_type)
        elif not get_object_class(obj_type):
            raise ValueError("unknown object type")

        obj_inst = int(obj_inst)

        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            raise ValueError("invalid property for object type")

        # build a request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, obj_inst),
            propertyIdentifier=prop_id,
        )
        request.pduDestination = Address(addr)

        if len(args) == 5:
            request.propertyArrayIndex = int(args[4])
        log_debug(ReadProperty, "    - request: %r", request)

        return request
Example #20
0
	def _do_read(self, objtype, objinst, propname):

		try:
			addr, obj_type, obj_inst, prop_id = self._remote_addr, objtype, objinst, propname

			if obj_type.isdigit():
				obj_type = int(obj_type)
			elif not get_object_class(obj_type):
				raise ValueError, "unknown object type"

			obj_inst = int(obj_inst)

			datatype = get_datatype(obj_type, prop_id)
			if not datatype:
				raise ValueError, "invalid property for object type"

			# build a request
			request = ReadPropertyRequest(
				objectIdentifier=(obj_type, obj_inst),
				propertyIdentifier=prop_id,
				)
			if self._debug: print("requesting")
			request.pduDestination = Address(addr)

			#if len(args) == 5:
			#	request.propertyArrayIndex = int(args[4])
			#if _debug: ReadPropertyConsoleCmd._debug("	- request: %r", request)

			# give it to the application
			self._app.request(request)

		except Exception, e:
			print "exception:" + repr(e)
Example #21
0
 def get_state_async(self, bac_app, address):
     request = ReadPropertyRequest(
             objectIdentifier=(self.object_type, self.instance_number),
             propertyIdentifier=self.property)        
     request.pduDestination = address
     iocb = IOCB(request)
     bac_app.request(iocb)
     return iocb.ioDefered
Example #22
0
 def get_state_async(self, bac_app, address):
     request = ReadPropertyRequest(objectIdentifier=(self.object_type,
                                                     self.instance_number),
                                   propertyIdentifier=self.property)
     request.pduDestination = address
     iocb = IOCB(request)
     bac_app.request(iocb)
     return iocb.ioDefered
Example #23
0
    def do_saverl(self, args):
        """saverl <addr> <inst>"""
        args = args.split()
        if _debug: EventNotificationConsoleCmd._debug("do_saverl %r", args)
        global saved_recipent_list

        try:
            addr, obj_inst = args
            obj_inst = int(obj_inst)

            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=('notificationClass', obj_inst),
                propertyIdentifier='recipientList',
            )
            request.pduDestination = Address(addr)

            # make an IOCB
            iocb = IOCB(request)
            if _debug:
                EventNotificationConsoleCmd._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:
                        EventNotificationConsoleCmd._debug("    - not an ack")
                    return

                # turn the property tag list blob into a list of destinations
                saved_recipent_list = apdu.propertyValue.cast_out(
                    ListOfDestination)

                for destination in saved_recipent_list:
                    destination.debug_contents(file=sys.stdout)

            # do something with nothing?
            else:
                if _debug:
                    EventNotificationConsoleCmd._debug(
                        "    - ioError or ioResponse expected")

        except Exception as error:
            EventNotificationConsoleCmd._exception("exception: %r", error)
Example #24
0
    def run(self):
        if _debug: ReadPointListThread._debug("run")
        global this_application

        # loop through the points
        for addr, obj_type, obj_inst, prop_id in self.point_queue:
            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
            )
            request.pduDestination = Address(addr)
            if _debug: ReadPointListThread._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: ReadPointListThread._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

            # wait for the response
            iocb.wait()

            if iocb.ioResponse:
                apdu = iocb.ioResponse

                # find the datatype
                datatype = get_datatype(apdu.objectIdentifier[0],
                                        apdu.propertyIdentifier)
                if _debug:
                    ReadPointListThread._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: ReadPointListThread._debug("    - value: %r", value)

                # save the value
                self.response_values.append(value)

            if iocb.ioError:
                if _debug:
                    ReadPointListThread._debug("    - error: %r", iocb.ioError)
                self.response_values.append(iocb.ioError)

        # done
        stop()
Example #25
0
 def read_property(self, target_address, object_type, instance_number, property_name, property_index=None):
     request = ReadPropertyRequest(
         objectIdentifier=(object_type, instance_number),
         propertyIdentifier=property_name,
         propertyArrayIndex=property_index)
     request.pduDestination = Address(target_address)
     iocb = self.iocb_class(request)
     self.this_application.submit_request(iocb)
     bacnet_results = iocb.ioResult.get(10)
     return bacnet_results
Example #26
0
 def read_property(self, target_address, object_type, instance_number, property_name, property_index=None):
     request = ReadPropertyRequest(
         objectIdentifier=(object_type, instance_number),
         propertyIdentifier=property_name,
         propertyArrayIndex=property_index)
     request.pduDestination = Address(target_address)
     iocb = self.iocb_class(request)
     self.bacnet_application.submit_request(iocb)
     bacnet_results = iocb.ioResult.get(10)
     return bacnet_results
    def run(self):
        if _debug: ReadPointListThread._debug("run")
        global this_application

        # loop through the points
        for addr, obj_type, obj_inst, prop_id in self.point_queue:
            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
                )
            request.pduDestination = Address(addr)
            if _debug: ReadPointListThread._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: ReadPointListThread._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

            # wait for the response
            iocb.wait()

            if iocb.ioResponse:
                apdu = iocb.ioResponse

                # find the datatype
                datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
                if _debug: ReadPointListThread._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: ReadPointListThread._debug("    - value: %r", value)

                # save the value
                self.response_values.append(value)

            if iocb.ioError:
                if _debug: ReadPointListThread._debug("    - error: %r", iocb.ioError)
                self.response_values.append(iocb.ioError)

        # done
        stop()
Example #28
0
File: br.py Project: navkal/bg
def send_request( target_args, app ):

    # build a request
    request = ReadPropertyRequest(
        objectIdentifier=( target_args['type'], target_args['instance'] ),
        propertyIdentifier=target_args['property']
    )
    request.pduDestination = Address( target_args['address'] )

    # make an IOCB
    iocb = IOCB( request )

    # give it to the application
    app.request_io( iocb )

    # wait for it to complete
    iocb.wait()

    # Handle completion: error, success, neither
    if iocb.ioError:
        # Error
        success = False
        message = str( iocb.ioError )
        result = ''

    elif iocb.ioResponse:
        # Success
        success = True
        message = ''

        # Get the response PDU
        apdu = iocb.ioResponse

        # Extract the returned value
        datatype = get_datatype( apdu.objectIdentifier[0], apdu.propertyIdentifier )
        if issubclass( datatype, Array ) and (apdu.propertyArrayIndex is not None):
            if apdu.propertyArrayIndex == 0:
                result = apdu.propertyValue.cast_out( Unsigned )
            else:
                result = apdu.propertyValue.cast_out( datatype.subtype )
        else:
            result = apdu.propertyValue.cast_out( datatype )

    else:
        # Neither
        success = False
        message = 'Request terminated unexpectedly'
        result = ''

    rsp = { target_args['property']: result }

    return success, message, rsp
def read(device, portObject): 

    request_addr = device.getRequestAddress()    
    obj_type = portObject.getType()
    port = portObject.getPortNum()
    prop_id = portObject.getProp()
    maximumWait = 6  #seconds
    
    try: 

        #Jordan Trying to open thread in application
        #applicationThread = BACpypeThread('BACPYPE-APP')
        #applicationThread.start()  

        #--------------------------read property request
        #verify datatype
       # print "Reading..."
        print request_addr, obj_type, port, prop_id
        
        if obj_type.isdigit():
            obj_type = int(obj_type)
        elif not get_object_class(obj_type):
            raise ValueError, "unknown object type"
            
                
        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            print ValueError, ": invalid property for object type"
        
        port = int(port)
        
        #build request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, port),
            propertyIdentifier=prop_id,
            )
        request.pduDestination = Address(request_addr)
        time.sleep(.01)  #I dont know why, but this makes the code work correctly.
        #submit request
        this_application.request(request)
  #      print "Waiting for reply..."
        
        #wait for request
        wait = 0
        while this_application._Application__response_value == None and wait <= maximumWait:
            wait = wait + .01
            time.sleep(.01)
        returnVal = this_application._Application__response_value
    except Exception, e:
        returnVal = None
        print 'An error has happened (CPLRW 126): ' + str(e) + "\n"
def read_prop(app, address, obj_type, obj_inst, prop_id):
    request = ReadPropertyRequest(objectIdentifier=(obj_type, obj_inst),
                                  propertyIdentifier=prop_id)
    request.pduDestination = address

    result = this_application.make_request(request)
    if not isinstance(result, ReadPropertyACK):
        result.debug_contents(file=sys.stderr)
        raise TypeError, "Error reading property"

    # find the datatype
    datatype = get_datatype(obj_type, prop_id)

    return result.propertyValue.cast_out(datatype)
Example #31
0
def read(device, portObject): 
    global this_application
    request_addr = device.getRequestAddress()    
    obj_type = portObject.getType()
    port = portObject.getPortNum()
    prop_id = portObject.getProp()
    maximumWait = 6  #seconds
    
    try: 

        #Jordan Trying to open thread in application

        #--------------------------read property request
        #verify datatype
       # print "Reading..."
        print request_addr, obj_type, port, prop_id
        
        if obj_type.isdigit():
            obj_type = int(obj_type)
        elif not get_object_class(obj_type):
            raise ValueError, "unknown object type"
            
                
        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            print ValueError, ": invalid property for object type"
        
        port = int(port)
        
        #build request
        request = ReadPropertyRequest(
            objectIdentifier=(obj_type, port),
            propertyIdentifier=prop_id,
            )
        request.pduDestination = Address(request_addr)
        time.sleep(.01)  #I dont know why, but this makes the code work correctly.
        #submit request
        this_application.request(request)
  #      print "Waiting for reply..."
        
        #wait for request
        wait = 0
        while this_application._Application__response_value == None and wait <= maximumWait:
            wait = wait + .01
            time.sleep(.01)
        returnVal = this_application._Application__response_value
    except Exception, e:
        returnVal = None
        print 'An error has happened (CPLRW 126): ' + str(e) + "\n"
def read_prop(app, address, obj_type, obj_inst, prop_id):
    request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id)
    request.pduDestination = address
    
    result = this_application.make_request(request)
    if not isinstance(result, ReadPropertyACK):
        result.debug_contents(file=sys.stderr)
        raise TypeError("Error reading property")
    
    # find the datatype
    datatype = get_datatype(obj_type, prop_id)
    
    return result.propertyValue.cast_out(datatype)
def ReadProperty(
    object_type,
    object_instance,
    property_id,
    address,
    ):
    
    global application
    if (application == None):
        local_address = bacpypesip
        routers = None
        application = SynchronousApplication(local_address, routers)
    
    request = ReadPropertyRequest(objectIdentifier=(object_type,
                                  int(object_instance)),
                                  propertyIdentifier=property_id)
    request.pduDestination = Address(address)
    apdu = application.make_request(request)

    if isinstance(apdu, Error):
        sys.stdout.write('error: %s\n' % (apdu.errorCode, ))
        sys.stdout.flush()
        return 'Error!'
    elif isinstance(apdu, AbortPDU):

        apdu.debug_contents()
        return 'Error: AbortPDU'
    elif isinstance(request, ReadPropertyRequest) and isinstance(apdu,
            ReadPropertyACK):

        datatype = get_datatype(apdu.objectIdentifier[0],
                                apdu.propertyIdentifier)
        if not datatype:
            raise TypeError, 'unknown datatype'

        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(value=="inactive"):
            value=0.0
        if (value=="active"):
            value=1.0
        return value
 def form_iocb(device, config=None, request_type="readProperty"):
     config = config if config is not None else device
     address = device["address"] if isinstance(device["address"], Address) else Address(device["address"])
     object_id = ObjectIdentifier(config["objectId"])
     property_id = config.get("propertyId")
     value = config.get("propertyValue")
     property_index = config.get("propertyIndex")
     priority = config.get("priority")
     vendor = device.get("vendor", config.get("vendorId", 0))
     request = None
     iocb = None
     if request_type == "readProperty":
         try:
             request = ReadPropertyRequest(
                 objectIdentifier=object_id,
                 propertyIdentifier=property_id
             )
             request.pduDestination = address
             if property_index is not None:
                 request.propertyArrayIndex = int(property_index)
             iocb = IOCB(request)
         except Exception as e:
             log.exception(e)
     elif request_type == "writeProperty":
         datatype = get_datatype(object_id.value[0], property_id, vendor)
         if (isinstance(value, str) and value.lower() == 'null') or value is None:
             value = Null()
         request = WritePropertyRequest(
             objectIdentifier=object_id,
             propertyIdentifier=property_id
         )
         request.pduDestination = address
         request.propertyValue = Any()
         try:
             value = datatype(value)
             request.propertyValue = Any(value)
         except AttributeError as e:
             log.debug(e)
         except Exception as error:
             log.exception("WriteProperty cast error: %r", error)
         if property_index is not None:
             request.propertyArrayIndex = property_index
         if priority is not None:
             request.priority = priority
         iocb = IOCB(request)
     else:
         log.error("Request type is not found or not implemented")
     return iocb
Example #35
0
 def _get_prop_for_obj(self, obj_id):
     request = ReadPropertyRequest(destination=self.device.source,
                                   objectIdentifier=obj_id,
                                   propertyIdentifier='propertyList')
     iocb = IOCB(request)
     iocb.add_callback(self._got_properties_for_object, obj_id)
     self.bacnet_adapter.request_io(iocb)
Example #36
0
    def next_request(self):
        if _debug: ReadPropertyApplication._debug("next_request")
        global device_address, object_identifier, property_list

        # check to see if we're done
        if not property_list:
            if _debug: ReadPropertyApplication._debug("    - done")
            stop()
            return

        # get the next request
        self.property_identifier = property_list.popleft()
        if _debug:
            ReadPropertyApplication._debug("    - property_identifier: %r",
                                           self.property_identifier)

        # build a request
        request = ReadPropertyRequest(
            destination=device_address,
            objectIdentifier=object_identifier,
            propertyIdentifier=self.property_identifier,
        )
        if _debug: ReadPropertyApplication._debug("    - request: %r", request)

        # make an IOCB
        iocb = IOCB(request)

        # set a callback for the response
        iocb.add_callback(self.complete_request)
        if _debug: ReadPropertyApplication._debug("    - iocb: %r", iocb)

        # send the request
        this_application.request_io(iocb)
Example #37
0
    def read_object_list(self, device_id, device_addr):
        if _debug:
            ReadAllObjectPropertiesApplication._debug("read_object_list %r %r",
                                                      device_id, device_addr)

        # create a context to hold the results
        context = ObjectPropertyContext(device_id, device_addr)

        # build a request for the object name
        request = ReadPropertyRequest(
            destination=context.device_addr,
            objectIdentifier=context.device_id,
            propertyIdentifier='objectList',
        )
        if _debug:
            ReadAllObjectPropertiesApplication._debug("    - request: %r",
                                                      request)

        # make an IOCB, reference the context
        iocb = IOCB(request)
        iocb.context = context
        if _debug:
            ReadAllObjectPropertiesApplication._debug("    - iocb: %r", iocb)

        # let us know when its complete
        iocb.add_callback(self.object_list_results)

        # give it to the application
        self.request_io(iocb)
Example #38
0
    def read_next_object(self, context):
        if _debug:
            ReadObjectListApplication._debug("read_next_object %r", context)

        # if there's nothing more to do, we're done
        if not context._object_list_queue:
            if _debug: ReadObjectListApplication._debug("    - all done")
            context.completed()
            return

        # pop off the next object identifier
        object_id = context._object_list_queue.popleft()
        if _debug:
            ReadObjectListApplication._debug("    - object_id: %r", object_id)

        # build a request for the object name
        request = ReadPropertyRequest(
            destination=context.device_addr,
            objectIdentifier=object_id,
            propertyIdentifier='objectName',
        )
        if _debug:
            ReadObjectListApplication._debug("    - request: %r", request)

        # make an IOCB, reference the context
        iocb = IOCB(request)
        iocb.context = context
        if _debug: ReadObjectListApplication._debug("    - iocb: %r", iocb)

        # let us know when its complete
        iocb.add_callback(self.object_name_results)

        # give it to the application
        self.request_io(iocb)
Example #39
0
 def _get_device_info(self):
     request = ReadPropertyRequest(destination=self.source,
                                   objectIdentifier=self.id,
                                   propertyIdentifier='objectName')
     iocb = IOCB(request)
     iocb.add_callback(self._got_object_name)
     self.bacnet_adapter.request_io(iocb)
Example #40
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 #41
0
 def _get_value_for_prop(self, prop):
     request = ReadPropertyRequest(destination=self.device.source,
                                   objectIdentifier=self.object,
                                   propertyIdentifier=prop)
     iocb = IOCB(request)
     iocb.add_callback(self._got_prop, prop)
     self.bacnet_adapter.request_io(iocb)
Example #42
0
 def _get_new_sensors_for_new_device(self, source, device_id):
     request = ReadPropertyRequest(destination=source,
                                   objectIdentifier=device_id,
                                   propertyIdentifier="objectList")
     iocb = IOCB(request)
     iocb.add_callback(self._got_sensors_for_device)
     self.bacnet_adapter.request_io(iocb)
Example #43
0
async def discover_properties(app, device_id, addr):
    objects = await app.execute_request(
        ReadPropertyRequest(objectIdentifier=('device', device_id),
                            propertyIdentifier='objectList',
                            destination=Address(addr)))
    result = {}
    for object_identifier in objects:
        _logger.info(object_identifier)
        read_access_specs = [
            ReadAccessSpecification(
                objectIdentifier=object_identifier,
                listOfPropertyReferences=[
                    PropertyReference(propertyIdentifier='presentValue'),
                    PropertyReference(propertyIdentifier='objectName'),
                    PropertyReference(propertyIdentifier='objectType'),
                    PropertyReference(propertyIdentifier='description'),
                    PropertyReference(propertyIdentifier='units'),
                ],
            ),
        ]
        result.update(await app.execute_request(
            ReadPropertyMultipleRequest(
                listOfReadAccessSpecs=read_access_specs,
                destination=Address(addr)), ))
    global properties
    properties = result
    asyncio.get_event_loop().stop()
def read(obj_type, port, prop_id):

	try: 
		#--------------------------read property request
		#verify datatype
		print "Reading..."
		print obj_type, port, prop_id
		
		if obj_type.isdigit():
		    obj_type = int(obj_type)
		elif not get_object_class(obj_type):
		    raise ValueError, "unknown object type"
		    
		          
		datatype = get_datatype(obj_type, prop_id)
		if not datatype:
			print ValueError, ": invalid property for object type"
		
		port = int(port)	
		
		#build request
		request = ReadPropertyRequest(
		    objectIdentifier=(obj_type, port), 
		    propertyIdentifier=prop_id,
		    )
		request.pduDestination = Address(request_addr)
		
		#submit request
		
		print request.pduDestination
		
		
		this_application.request(request)
		print "Waiting for reply..."
		#wait for request
		wait = 0
		while this_application._Application__response_value == None:
		    wait = wait + .01
		    time.sleep(.01)
		returnVal = this_application._Application__response_value
        
        
	except Exception, e:
		returnVal = None
		print 'An error has happened (CPLRW 127): ' + str(e) + "\n"
Example #45
0
def read_prop(app, address, obj_type, obj_inst, prop_id, index=None):
    request = ReadPropertyRequest(
        objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, propertyArrayIndex=index
    )
    request.pduDestination = address

    result = this_application.make_request(request)
    if not isinstance(result, ReadPropertyACK):
        result.debug_contents(file=sys.stderr)
        raise TypeError("Error reading property")

    # find the datatype
    datatype = get_datatype(obj_type, prop_id)
    if issubclass(datatype, Array) and (result.propertyArrayIndex is not None):
        if result.propertyArrayIndex == 0:
            value = result.propertyValue.cast_out(Unsigned)
        else:
            value = result.propertyValue.cast_out(datatype.subtype)
    else:
        value = result.propertyValue.cast_out(datatype)

    return value
test_asap = ApplicationServiceAccessPoint()

# pass the device object to the state machine access point so it
# can know if it should support segmentation
test_smap = StateMachineAccessPoint(test_device)

# state machine
test_server = MatchingStateMachine()

# bind everything together
bind(test_application, test_asap, test_smap, test_server)

# ==============================================================================

read_property_request = ReadPropertyRequest(
    objectIdentifier=('device', 100),
    propertyIdentifier='objectName',
    )
read_property_request.pduSource = Address(2)
# read_property_request.pduDestination = Address(1)
read_property_request.apduInvokeID = 1

print("read_property_request")
read_property_request.debug_contents()
print("")

test_apdu = APDU()
read_property_request.encode(test_apdu)

print("test_apdu")
test_apdu.debug_contents()
print("")
    def do_read(self, args):
        """read <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadWritePropertyConsoleCmd._debug("do_read %r", args)

        try:
            addr, obj_type, obj_inst, prop_id = args[:4]

            if obj_type.isdigit():
                obj_type = int(obj_type)
            elif not get_object_class(obj_type, VendorAVObject.vendor_id):
                raise ValueError("unknown object type")
            if _debug: ReadWritePropertyConsoleCmd._debug("    - obj_type: %r", obj_type)

            obj_inst = int(obj_inst)
            if _debug: ReadWritePropertyConsoleCmd._debug("    - obj_inst: %r", obj_inst)

            if prop_id.isdigit():
                prop_id = int(prop_id)
            if _debug: ReadWritePropertyConsoleCmd._debug("    - prop_id: %r", prop_id)

            datatype = get_datatype(obj_type, prop_id, VendorAVObject.vendor_id)
            if not datatype:
                raise ValueError("invalid property for object type")

            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
                )
            request.pduDestination = Address(addr)

            if len(args) == 5:
                request.propertyArrayIndex = int(args[4])
            if _debug: ReadWritePropertyConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: ReadWritePropertyConsoleCmd._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

            # wait for it to complete
            iocb.wait()

            # do something for success
            if iocb.ioResponse:
                apdu = iocb.ioResponse

                # peek at the value tag
                value_tag = apdu.propertyValue.tagList.Peek()
                if _debug: ReadWritePropertyConsoleCmd._debug("    - value_tag: %r", value_tag)

                # make sure that it is application tagged
                if value_tag.tagClass != Tag.applicationTagClass:
                    sys.stdout.write("value is not application encoded\n")

                else:
                    # find the datatype
                    datatype = Tag._app_tag_class[value_tag.tagNumber]
                    if _debug: ReadWritePropertyConsoleCmd._debug("    - datatype: %r", datatype)
                    if not datatype:
                        raise TypeError("unknown datatype")

                    # cast out the value
                    value = apdu.propertyValue.cast_out(datatype)
                    if _debug: ReadWritePropertyConsoleCmd._debug("    - value: %r", value)

                    sys.stdout.write("%s (%s)\n" % (value, datatype))

                sys.stdout.flush()

            # do something for error/reject/abort
            if iocb.ioError:
                sys.stdout.write(str(iocb.ioError) + '\n')

        except Exception as error:
            ReadWritePropertyConsoleCmd._exception("exception: %r", error)
Example #48
0
    def do_read(self, args):
        """read <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadPropertyConsoleCmd._debug("do_read %r", args)

        try:
            addr, obj_type, obj_inst, prop_id = args[:4]

            if obj_type.isdigit():
                obj_type = int(obj_type)
            elif not get_object_class(obj_type):
                raise ValueError("unknown object type")

            obj_inst = int(obj_inst)

            datatype = get_datatype(obj_type, prop_id)
            if not datatype:
                raise ValueError("invalid property for object type")

            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
                )
            request.pduDestination = Address(addr)

            if len(args) == 5:
                request.propertyArrayIndex = int(args[4])
            if _debug: ReadPropertyConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: ReadPropertyConsoleCmd._debug("    - iocb: %r", iocb)

            # give it to the application
            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, ReadPropertyACK):
                    if _debug: ReadPropertyConsoleCmd._debug("    - not an ack")
                    return

                # find the datatype
                datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
                if _debug: ReadPropertyConsoleCmd._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: ReadPropertyConsoleCmd._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 for error/reject/abort
            if iocb.ioError:
                sys.stdout.write(str(iocb.ioError) + '\n')

        except Exception, error:
            ReadPropertyConsoleCmd._exception("exception: %r", error)
Example #49
0
    def read(self, args):
        """ This function build a read request wait for the answer and 
        return the value
        
        :param args: String with <addr> <type> <inst> <prop> [ <indx> ]
        :returns: data read from device (str representing data like 10 or True)
        
        *Example*::
            
            import BAC0
            myIPAddr = '192.168.1.10'
            bacnet = BAC0.ReadWriteScript(localIPAddr = myIPAddr)          
            bacnet.read('2:5 analogInput 1 presentValue')
        
        will read controller with a MAC address of 5 in the network 2
        Will ask for the present Value of analog input 1 (AI:1)
        """
        if not self._started: raise Exception('App not running, use startApp() function')
        args = args.split()
        self.this_application.value == None
        print_debug("do_read %r", args)

        try:
            addr, obj_type, obj_inst, prop_id = args[:4]

            if obj_type.isdigit():
                obj_type = int(obj_type)
            elif not get_object_class(obj_type):
                raise ValueError("unknown object type")

            obj_inst = int(obj_inst)

            datatype = get_datatype(obj_type, prop_id)
            if not datatype:
                raise ValueError("invalid property for object type")

            # build a request
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
                )
            request.pduDestination = Address(addr)

            if len(args) == 5:
                request.propertyArrayIndex = int(args[4])
            print_debug("    - request: %r", request)

            # give it to the application
            self.this_application.request(request)

        except ReadPropertyException as error:
            ReadProperty._exception("exception: %r", error)

        # Share response with Queue
        data = None
        while True:
            try:
                data, evt = self.this_application.ResponseQueue.get(timeout=self._TIMEOUT)
                evt.set()
                return data
            except Empty:
                print('No response from controller')
                return None