Exemplo n.º 1
0
    def get_server_application(self):
        if _debug: DeviceAbstraction._debug("    - creating application")
        # make a device object
        this_device = LocalDeviceObject(objectName="Betelgeuse",
                                        objectIdentifier=args.device_id,
                                        maxApduLengthAccepted=1024,
                                        segmentationSupported="segmentedBoth",
                                        vendorIdentifier=15)

        # build a bit string that knows about the bit names
        pss = ServicesSupported()
        pss['whoIs'] = 1
        pss['iAm'] = 1
        pss['readProperty'] = 1
        pss['readPropertyMultiple'] = 1
        pss['writeProperty'] = 1

        # set the property value to be just the bits
        this_device.protocolServicesSupported = pss.value

        # make a sample application
        this_application = ReadPropertyMultipleApplication(
            this_device, args.interface)

        registers = self.registers[('byte', True)]

        #Currently we don't actually enforce read only properties.
        for register in registers:
            if _debug:
                DeviceAbstraction._debug(
                    "    - creating object of type: %s, %i",
                    register.object_type, register.instance_number)
            klass = get_object_class(register.object_type)
            ravo = klass(objectIdentifier=(register.object_type,
                                           register.instance_number),
                         objectName=register.point_name)

            ravo.WriteProperty("presentValue", 0, direct=True)

            this_application.add_object(ravo)

        registers = self.registers[('byte', False)]

        for register in registers:
            if _debug:
                DeviceAbstraction._debug(
                    "    - creating object of type: %s, %i",
                    register.object_type, register.instance_number)
            klass = get_object_class(register.object_type)
            ravo = klass(objectIdentifier=(register.object_type,
                                           register.instance_number),
                         objectName=register.point_name)

            ravo.WriteProperty("presentValue", 0, direct=True)

            this_application.add_object(ravo)

        return this_application
Exemplo n.º 2
0
    def get_server_application(self):
        if _debug: DeviceAbstraction._debug("    - creating application")
        # make a device object
        this_device = LocalDeviceObject(
            objectName="Betelgeuse",
            objectIdentifier=599,
            maxApduLengthAccepted=1024,
            segmentationSupported="segmentedBoth",
            vendorIdentifier=15
            )
    
        # build a bit string that knows about the bit names
        pss = ServicesSupported()
        pss['whoIs'] = 1
        pss['iAm'] = 1
        pss['readProperty'] = 1
        pss['readPropertyMultiple'] = 1
        pss['writeProperty'] = 1
    
        # set the property value to be just the bits
        this_device.protocolServicesSupported = pss.value        

        # make a sample application
        this_application = ReadPropertyMultipleApplication(this_device, args.interface)
    
       
        registers= self.registers[('byte',True)]
        
        #Currently we don't actually enforce read only properties.        
        for register in registers:
            if _debug: DeviceAbstraction._debug("    - creating object of type: %s, %i", register.object_type, register.instance_number)
            klass = get_object_class(register.object_type)
            ravo = klass(objectIdentifier=(register.object_type, register.instance_number), 
                         objectName=register.point_name)
            
            ravo.WriteProperty("presentValue", 0, direct=True)
            
            this_application.add_object(ravo)
            
            
        registers= self.registers[('byte',False)]
        
        for register in registers:
            if _debug: DeviceAbstraction._debug("    - creating object of type: %s, %i", register.object_type, register.instance_number)
            klass = get_object_class(register.object_type)
            ravo = klass(objectIdentifier=(register.object_type, register.instance_number), 
                         objectName=register.point_name)
            
            ravo.WriteProperty("presentValue", 0, direct=True)
            
            this_application.add_object(ravo)
            
        return this_application
Exemplo n.º 3
0
def create_application(interface_str, device_name, device_id, config_list):

    _log.debug("    - creating application")
    # make a device object
    this_device = LocalDeviceObject(objectName=device_name,
                                    objectIdentifier=device_id,
                                    maxApduLengthAccepted=1024,
                                    segmentationSupported="segmentedBoth",
                                    vendorIdentifier=15)

    # make a sample application
    this_application = Application(this_device, interface_str)

    # Currently we don't actually enforce read only properties.
    for register in config_list:
        _log.debug("    - creating object of type: %s, %i" %
                   (register["type"], register["index"]))
        klass = get_object_class(register["type"])
        ravo = klass(objectIdentifier=(register["type"], register["index"]),
                     objectName=register["name"],
                     description=register.get("description", ""))

        ravo.WriteProperty("presentValue", 0, direct=True)

        this_application.add_object(ravo)

    return this_application
Exemplo n.º 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
Exemplo n.º 5
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
Exemplo n.º 6
0
    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)
Exemplo n.º 7
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)
Exemplo n.º 8
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)
Exemplo n.º 9
0
    def build_rrange_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 = ReadRangeRequest(
            objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id
        )
        request.pduDestination = Address(addr)

        if len(args) == 5:
            request.propertyArrayIndex = int(args[4])
        self._log.debug("{:<20} {!r}".format("REQUEST", request))
        return request
Exemplo n.º 10
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
Exemplo n.º 11
0
	def _do_readrange(self, objtype, objinst, propname, start, c, arrind=None):
		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 = ReadRangeRequest(
				objectIdentifier=(obj_type, obj_inst),
				propertyIdentifier=prop_id,
				range=Range(byPosition=RangeByPosition(referenceIndex=start, count=c))
				)
			request.pduDestination = Address(addr)

			if arrind:
				request.propertyArrayIndex = int(arrind)
			#if _debug: ReadRangeConsoleCmd._debug("	- request: %r", request)

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

		except Exception, e:
			print "exception:" + repr(e)
Exemplo n.º 12
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              
Exemplo n.º 13
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
Exemplo n.º 14
0
Arquivo: Read.py Projeto: snuids/BAC0
def validate_object_type(obj_type, vendor_id=842):
    if obj_type.isdigit():
        obj_type = int(obj_type)
    elif "@obj_" in obj_type:
        obj_type = int(obj_type.split("_")[1])
    elif not get_object_class(obj_type, vendor_id=vendor_id):
        raise ValueError("Unknown object type : {}".format(obj_type))
    return obj_type
Exemplo n.º 15
0
    def do_subscribe(self, args):
        """subscribe addr proc_id obj_type obj_inst [ confirmed ] [ lifetime ]
        """
        args = args.split()
        if _debug: SubscribeCOVConsoleCmd._debug("do_subscribe %r", args)

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

            proc_id = int(proc_id)

            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 len(args) >= 5:
                issue_confirmed = args[4]
                if issue_confirmed == '-':
                    issue_confirmed = None
                else:
                    issue_confirmed = issue_confirmed.lower() == 'true'
                if _debug: SubscribeCOVConsoleCmd._debug("    - issue_confirmed: %r", issue_confirmed)
            else:
                issue_confirmed = None

            if len(args) >= 6:
                lifetime = args[5]
                if lifetime == '-':
                    lifetime = None
                else:
                    lifetime = int(lifetime)
                if _debug: SubscribeCOVConsoleCmd._debug("    - lifetime: %r", lifetime)
            else:
                lifetime = None

            # build a request
            request = SubscribeCOVRequest(
                subscriberProcessIdentifier=proc_id,
                monitoredObjectIdentifier=(obj_type, obj_inst),
                )
            request.pduDestination = Address(addr)

            # optional parameters
            if issue_confirmed is not None:
                request.issueConfirmedNotifications = issue_confirmed
            if lifetime is not None:
                request.lifetime = lifetime

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

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

        except Exception as e:
            SubscribeCOVConsoleCmd._exception("exception: %r", e)
Exemplo n.º 16
0
def main():
    global this_application, device_address, object_identifier, property_list

    # parse the command line arguments
    parser = ConfigArgumentParser(description=__doc__)
    parser.add_argument(
        "address",
        help="device address",
    )
    parser.add_argument(
        "objtype",
        help="object types, e.g., analogInput",
    )
    parser.add_argument(
        "objinstance",
        type=int,
        help="object instance",
    )
    args = parser.parse_args()

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

    # interpret the address
    device_address = Address(args.address)
    if _debug: _log.debug("    - device_address: %r", device_address)

    # build an identifier
    object_identifier = (args.objtype, args.objinstance)
    if _debug: _log.debug("    - object_identifier: %r", object_identifier)

    # get the object class
    object_class = get_object_class(args.objtype)
    if _debug: _log.debug("    - object_class: %r", object_class)

    # make a queue of the properties
    property_list = deque(prop.identifier for prop in object_class.properties)
    if _debug: _log.debug("    - property_list: %r", property_list)

    # make a device object
    this_device = LocalDeviceObject(ini=args.ini)
    if _debug: _log.debug("    - this_device: %r", this_device)

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

    # fire off a request when the core has a chance
    deferred(this_application.next_request)

    _log.debug("running")

    run()

    _log.debug("fini")
Exemplo n.º 17
0
    def build_rrange_request(
        self, args, range_params=None, 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, vendor_id=vendor_id):
            raise ValueError("Unknown object type {}".format(obj_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 = ReadRangeRequest(
            objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id
        )
        request.pduDestination = Address(addr)
        if range_params is not None:
            range_type, first, date, time, count = range_params
            if range_type == "p":
                rbp = RangeByPosition(referenceIndex=int(first), count=int(count))
                request.range = Range(byPosition=rbp)
            elif range_type == "s":
                rbs = RangeBySequenceNumber(
                    referenceSequenceNumber=int(first), count=int(count)
                )
                request.range = Range(bySequenceNumber=rbs)
            elif range_type == "t":
                rbt = RangeByTime(
                    referenceTime=DateTime(
                        date=Date(date).value, time=Time(time).value
                    ),
                    count=int(count),
                )
                request.range = Range(byTime=rbt)
            elif range_type == "x":
                # should be missing required parameter
                request.range = Range()
            else:
                raise ValueError("unknown range type: %r" % (range_type,))

        if len(args) == 5:
            request.propertyArrayIndex = int(args[4])
        self._log.debug("{:<20} {!r}".format("REQUEST", request))
        return request
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"
Exemplo n.º 19
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"
Exemplo n.º 20
0
    def object_list_results(self, iocb):
        if _debug:
            ReadAllObjectPropertiesApplication._debug("object_list_results %r",
                                                      iocb)

        # extract the context
        context = iocb.context

        # do something for error/reject/abort
        if iocb.ioError:
            context.completed(iocb.ioError)
            return

        # do something for success
        apdu = iocb.ioResponse

        # should be an ack
        if not isinstance(apdu, ReadPropertyACK):
            if _debug:
                ReadAllObjectPropertiesApplication._debug("    - not an ack")
            context.completed(RuntimeError("read property ack expected"))
            return

        # pull out the content
        object_list = apdu.propertyValue.cast_out(ArrayOfObjectIdentifier)
        if _debug:
            ReadAllObjectPropertiesApplication._debug("    - object_list: %r",
                                                      object_list)

        # store it in the context
        context.object_list = object_list

        #Get the object classes for each object in the object list and get all possible properties that can be queried for each device.
        object_classes = [(get_object_class(obj[0]), obj[1])
                          for obj in object_list]
        context.properties_dict_queue = {
            (object_class[0].objectType, object_class[1]):
            deque([(prop.identifier, prop.datatype)
                   for prop in Object.properties + object_class[0].properties])
            for object_class in object_classes
        }
        context.property_result_dict = dict()

        # make a queue of the identifiers to read, start reading them
        context._object_list_queue = deque(object_list)
        deferred(self.read_next_object_properties, context)
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"
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"
Exemplo n.º 23
0
    def do_read(self, args):
        if _debug: ThreadedHTTPRequestHandler._debug("do_read %r", args)

        try:
            addr, obj_type, obj_inst = args[:3]

            # get the object type
            if not get_object_class(obj_type):
                raise ValueError("unknown object type")

            # get the instance number
            obj_inst = int(obj_inst)

            # implement a default property, the bain of committee meetings
            if len(args) == 4:
                prop_id = args[3]
            else:
                prop_id = "presentValue"

            # look for its datatype, an easy way to see if the property is
            # appropriate for the object
            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)

            # look for an optional array index
            if len(args) == 5:
                request.propertyArrayIndex = int(args[4])
            if _debug: ThreadedHTTPRequestHandler._debug("    - request: %r", request)

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

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

            # wait for it to complete
            iocb.wait()

            # filter out errors and aborts
            if iocb.ioError:
                if _debug: ThreadedHTTPRequestHandler._debug("    - error: %r", iocb.ioError)
                result = { "error": str(iocb.ioError) }
            else:
                if _debug: ThreadedHTTPRequestHandler._debug("    - response: %r", iocb.ioResponse)
                result = { "value": iocb.ioResponse }

        except Exception as err:
            ThreadedHTTPRequestHandler._exception("exception: %r", err)
            result = { "exception": str(err) }

        # write the result
        json.dump(result, self.wfile)
Exemplo n.º 24
0
    def readMultiple(self, args):
        """ This function build a readMultiple 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.readMultiple('2:5 analogInput 1 presentValue units')
        
        will read controller with a MAC address of 5 in the network 2
        Will ask for the present Value and the units of analog input 1 (AI:1)
        """
        args = args.split()
        print_debug("readMultiple %r", args)

        try:
            i = 0
            addr = args[i]
            i += 1

            read_access_spec_list = []
            while i < len(args):
                obj_type = args[i]
                i += 1

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

                obj_inst = int(args[i])
                i += 1

                prop_reference_list = []
                while i < len(args):
                    prop_id = args[i]
                    if prop_id not in PropertyIdentifier.enumerations:
                        break

                    i += 1
                    if prop_id in ('all', 'required', 'optional'):
                        pass
                    else:
                        datatype = get_datatype(obj_type, prop_id)
                        if not datatype:
                            raise ValueError(
                                "invalid property for object type : %s | %s" %
                                (obj_type, prop_id))

                    # build a property reference
                    prop_reference = PropertyReference(
                        propertyIdentifier=prop_id, )

                    # check for an array index
                    if (i < len(args)) and args[i].isdigit():
                        prop_reference.propertyArrayIndex = int(args[i])
                        i += 1

                    # add it to the list
                    prop_reference_list.append(prop_reference)

                # check for at least one property
                if not prop_reference_list:
                    raise ValueError("provide at least one property")

                # build a read access specification
                read_access_spec = ReadAccessSpecification(
                    objectIdentifier=(obj_type, obj_inst),
                    listOfPropertyReferences=prop_reference_list,
                )

                # add it to the list
                read_access_spec_list.append(read_access_spec)

            # check for at least one
            if not read_access_spec_list:
                raise RuntimeError(
                    "at least one read access specification required")

            # build the request
            request = ReadPropertyMultipleRequest(
                listOfReadAccessSpecs=read_access_spec_list, )
            request.pduDestination = Address(addr)
            print_debug("    - request: %r", request)

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

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

        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
Exemplo n.º 25
0
    def do_read(self, args):
        """read <addr> ( <type> <inst> ( <prop> [ <indx> ] )... )..."""
        args = args.split()
        if _debug: ReadPropertyMultipleConsoleCmd._debug("do_read %r", args)

        try:
            i = 0
            addr = args[i]
            i += 1

            read_access_spec_list = []
            while i < len(args):
                obj_type = args[i]
                i += 1

                if obj_type.isdigit():
                    obj_type = int(obj_type)
                elif not get_object_class(obj_type):
                    raise ValueError, "unknown object type"
                
                obj_inst = int(args[i])
                i += 1

                prop_reference_list = []
                while i < len(args):
                    prop_id = args[i]
                    if prop_id not in PropertyIdentifier.enumerations:
                        break

                    i += 1
                    if prop_id in ('all', 'required', 'optional'):
                        pass
                    else:
                        datatype = get_datatype(obj_type, prop_id)
                        if not datatype:
                            raise ValueError, "invalid property for object type"

                    # build a property reference
                    prop_reference = PropertyReference(
                        propertyIdentifier=prop_id,
                        )

                    # check for an array index
                    if (i < len(args)) and args[i].isdigit():
                        prop_reference.propertyArrayIndex = int(args[i])
                        i += 1

                    # add it to the list
                    prop_reference_list.append(prop_reference)

                # check for at least one property
                if not prop_reference_list:
                    raise ValueError, "provide at least one property"

                # build a read access specification
                read_access_spec = ReadAccessSpecification(
                    objectIdentifier=(obj_type, obj_inst),
                    listOfPropertyReferences=prop_reference_list,
                    )

                # add it to the list
                read_access_spec_list.append(read_access_spec)

            # check for at least one
            if not read_access_spec_list:
                raise RuntimeError, "at least one read access specification required"

            # build the request
            request = ReadPropertyMultipleRequest(
                listOfReadAccessSpecs=read_access_spec_list,
                )
            request.pduDestination = Address(addr)
            if _debug: ReadPropertyMultipleConsoleCmd._debug("    - request: %r", request)

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

        except Exception, e:
            ReadPropertyMultipleConsoleCmd._exception("exception: %r", e)
Exemplo n.º 26
0
    def build_rpm_request(self, args, vendor_id=0):
        """
        Build request from args
        """
        self._log.debug(args)
        i = 0
        addr = args[i]
        i += 1
        vendor_id = vendor_id

        read_access_spec_list = []
        while i < len(args):
            obj_type = args[i]
            i += 1

            if obj_type.isdigit():
                obj_type = int(obj_type)
            elif "@obj_" in obj_type:
                obj_type = int(obj_type.split("_")[1])
            elif not get_object_class(obj_type, vendor_id=vendor_id):
                raise ValueError("Unknown object type : {}".format(obj_type))

            obj_inst = int(args[i])
            i += 1

            prop_reference_list = []
            while i < len(args):
                prop_id = args[i]
                if "@obj_" in prop_id:
                    break
                if prop_id not in PropertyIdentifier.enumerations:
                    try:
                        if "@prop_" in prop_id:
                            prop_id = int(prop_id.split("_")[1])
                            self._log.debug(
                                "Proprietary property : {} | {} -> Vendor : {}"
                                .format(obj_type, prop_id, vendor_id))
                        else:
                            break
                    except:
                        break

                elif prop_id in (
                        "all",
                        "required",
                        "optional",
                        "objectName",
                        "objectType",
                        "objectIdentifier",
                        "polarity",
                ):
                    pass
                else:
                    datatype = get_datatype(obj_type,
                                            prop_id,
                                            vendor_id=vendor_id)
                    if not datatype:
                        raise ValueError(
                            "invalid property for object type : {} | {}".
                            format(obj_type, prop_id))
                i += 1

                # build a property reference
                prop_reference = PropertyReference(propertyIdentifier=prop_id)

                # check for an array index
                if (i < len(args)) and args[i].isdigit():
                    prop_reference.propertyArrayIndex = int(args[i])
                    i += 1

                prop_reference_list.append(prop_reference)

            if not prop_reference_list:
                raise ValueError("provide at least one property")

            # build a read access specification
            read_access_spec = ReadAccessSpecification(
                objectIdentifier=(obj_type, obj_inst),
                listOfPropertyReferences=prop_reference_list,
            )

            read_access_spec_list.append(read_access_spec)

        if not read_access_spec_list:
            raise RuntimeError(
                "at least one read access specification required")

        # build the request
        request = ReadPropertyMultipleRequest(
            listOfReadAccessSpecs=read_access_spec_list)
        request.pduDestination = Address(addr)
        return request
Exemplo n.º 27
0
def create_ReadPropertyMultipleRequest(args):
    """
    Create a request to compare with called arg
    """
    args = args.split()

    i = 0
    addr = args[i]
    i += 1

    read_access_spec_list = []
    while i < len(args):
        obj_type = args[i]
        i += 1

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

        obj_inst = int(args[i])
        i += 1

        prop_reference_list = []
        while i < len(args):
            prop_id = args[i]
            if prop_id not in PropertyIdentifier.enumerations:
                break

            i += 1
            if prop_id in ('all', 'required', 'optional'):
                pass
            else:
                datatype = get_datatype(obj_type, prop_id)
                if not datatype:
                    raise ValueError(
                        "invalid property for object type : %s | %s" %
                        (obj_type, prop_id))

            # build a property reference
            prop_reference = PropertyReference(propertyIdentifier=prop_id, )

            # check for an array index
            if (i < len(args)) and args[i].isdigit():
                prop_reference.propertyArrayIndex = int(args[i])
                i += 1

            # add it to the list
            prop_reference_list.append(prop_reference)

        # check for at least one property
        if not prop_reference_list:
            raise ValueError("provide at least one property")

        # build a read access specification
        read_access_spec = ReadAccessSpecification(
            objectIdentifier=(obj_type, obj_inst),
            listOfPropertyReferences=prop_reference_list,
        )

        # add it to the list
        read_access_spec_list.append(read_access_spec)

    # check for at least one
    if not read_access_spec_list:
        raise RuntimeError("at least one read access specification required")

    # build the request
    request = ReadPropertyMultipleRequest(
        listOfReadAccessSpecs=read_access_spec_list, )
    request.pduDestination = Address(addr)
    return request
Exemplo n.º 28
0
    def do_write(self, args):
        """write <addr> <objid> <prop> <value> [ <indx> ] [ <priority> ]"""
        args = args.split()
        ReadWritePropertyConsoleCmd._debug("do_write %r", args)

        try:
            addr, obj_id, prop_id = args[:3]
            obj_id = ObjectIdentifier(obj_id).value

            if not get_object_class(obj_id[0], VendorAVObject.vendor_id):
                raise ValueError("unknown object type")

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

            value = args[3]

            indx = None
            if len(args) >= 5:
                if args[4] != "-":
                    indx = int(args[4])
            if _debug:
                ReadWritePropertyConsoleCmd._debug("    - indx: %r", indx)

            priority = None
            if len(args) >= 6:
                priority = int(args[5])
            if _debug:
                ReadWritePropertyConsoleCmd._debug("    - priority: %r",
                                                   priority)

            # get the datatype
            datatype = get_datatype(obj_id[0], prop_id,
                                    VendorAVObject.vendor_id)
            if _debug:
                ReadWritePropertyConsoleCmd._debug("    - datatype: %r",
                                                   datatype)

            # change atomic values into something encodeable, null is a special case
            if (value == 'null'):
                value = Null()
            elif issubclass(datatype, Atomic):
                if datatype is Integer:
                    value = int(value)
                elif datatype is Real:
                    value = float(value)
                elif datatype is Unsigned:
                    value = int(value)
                value = datatype(value)
            elif issubclass(datatype, Array) and (indx is not None):
                if indx == 0:
                    value = Integer(value)
                elif issubclass(datatype.subtype, Atomic):
                    value = datatype.subtype(value)
                elif not isinstance(value, datatype.subtype):
                    raise TypeError("invalid result datatype, expecting %s" %
                                    (datatype.subtype.__name__, ))
            elif not isinstance(value, datatype):
                raise TypeError("invalid result datatype, expecting %s" %
                                (datatype.__name__, ))
            if _debug:
                ReadWritePropertyConsoleCmd._debug(
                    "    - encodeable value: %r %s", value, type(value))

            # build a request
            request = WritePropertyRequest(objectIdentifier=obj_id,
                                           propertyIdentifier=prop_id)
            request.pduDestination = Address(addr)

            # save the value
            request.propertyValue = Any()
            try:
                request.propertyValue.cast_in(value)
            except Exception as error:
                ReadWritePropertyConsoleCmd._exception(
                    "WriteProperty cast error: %r", error)

            # optional array index
            if indx is not None:
                request.propertyArrayIndex = indx

            # optional priority
            if priority is not None:
                request.priority = priority

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

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

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

            # wait for it to complete
            iocb.wait()

            # do something for success
            if iocb.ioResponse:
                sys.stdout.write("ack\n")

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

        except Exception as error:
            ReadWritePropertyConsoleCmd._exception("exception: %r", error)
Exemplo n.º 29
0
    def build_rpm_request(self, args):
        """
        Build request from args
        """
        i = 0
        addr = args[i]
        i += 1

        read_access_spec_list = []
        while i < len(args):
            obj_type = args[i]
            i += 1

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

            obj_inst = int(args[i])
            i += 1

            prop_reference_list = []
            while i < len(args):
                prop_id = args[i]
                if prop_id not in PropertyIdentifier.enumerations:
                    break

                i += 1
                if prop_id in ("all", "required", "optional"):
                    pass
                else:
                    datatype = get_datatype(obj_type, prop_id)
                    if not datatype:
                        raise ValueError(
                            "invalid property for object type : {} | {}".format(
                                (obj_type, prop_id)
                            )
                        )

                # build a property reference
                prop_reference = PropertyReference(propertyIdentifier=prop_id)

                # check for an array index
                if (i < len(args)) and args[i].isdigit():
                    prop_reference.propertyArrayIndex = int(args[i])
                    i += 1

                prop_reference_list.append(prop_reference)

            if not prop_reference_list:
                raise ValueError("provide at least one property")

            # build a read access specification
            read_access_spec = ReadAccessSpecification(
                objectIdentifier=(obj_type, obj_inst),
                listOfPropertyReferences=prop_reference_list,
            )

            read_access_spec_list.append(read_access_spec)

        if not read_access_spec_list:
            raise RuntimeError("at least one read access specification required")

        # build the request
        request = ReadPropertyMultipleRequest(
            listOfReadAccessSpecs=read_access_spec_list
        )
        request.pduDestination = Address(addr)
        self._log.debug("{:<20} {!r}".format("REQUEST", request))
        return request
Exemplo n.º 30
0
    def do_read(self, args):
        """read <addr> ( <type> <inst> ( <prop> [ <indx> ] )... )..."""
        args = args.split()
        if _debug: ReadPropertyMultipleConsoleCmd._debug("do_read %r", args)

        try:
            i = 0
            addr = args[i]
            i += 1

            read_access_spec_list = []
            while i < len(args):
                obj_type = args[i]
                i += 1

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

                obj_inst = int(args[i])
                i += 1

                prop_reference_list = []
                while i < len(args):
                    prop_id = args[i]
                    if prop_id not in PropertyIdentifier.enumerations:
                        break

                    i += 1
                    if prop_id in ('all', 'required', 'optional'):
                        pass
                    else:
                        datatype = get_datatype(obj_type, prop_id)
                        if not datatype:
                            raise ValueError("invalid property for object type")

                    # build a property reference
                    prop_reference = PropertyReference(
                        propertyIdentifier=prop_id,
                        )

                    # check for an array index
                    if (i < len(args)) and args[i].isdigit():
                        prop_reference.propertyArrayIndex = int(args[i])
                        i += 1

                    # add it to the list
                    prop_reference_list.append(prop_reference)

                # check for at least one property
                if not prop_reference_list:
                    raise ValueError("provide at least one property")

                # build a read access specification
                read_access_spec = ReadAccessSpecification(
                    objectIdentifier=(obj_type, obj_inst),
                    listOfPropertyReferences=prop_reference_list,
                    )

                # add it to the list
                read_access_spec_list.append(read_access_spec)

            # check for at least one
            if not read_access_spec_list:
                raise RuntimeError("at least one read access specification required")

            # build the request
            request = ReadPropertyMultipleRequest(
                listOfReadAccessSpecs=read_access_spec_list,
                )
            request.pduDestination = Address(addr)
            if _debug: ReadPropertyMultipleConsoleCmd._debug("    - request: %r", request)

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

                # loop through the results
                for result in apdu.listOfReadAccessResults:
                    # here is the object identifier
                    objectIdentifier = result.objectIdentifier
                    if _debug: ReadPropertyMultipleConsoleCmd._debug("    - objectIdentifier: %r", objectIdentifier)

                    # now come the property values per object
                    for element in result.listOfResults:
                        # get the property and array index
                        propertyIdentifier = element.propertyIdentifier
                        if _debug: ReadPropertyMultipleConsoleCmd._debug("    - propertyIdentifier: %r", propertyIdentifier)
                        propertyArrayIndex = element.propertyArrayIndex
                        if _debug: ReadPropertyMultipleConsoleCmd._debug("    - propertyArrayIndex: %r", propertyArrayIndex)

                        # here is the read result
                        readResult = element.readResult

                        sys.stdout.write(propertyIdentifier)
                        if propertyArrayIndex is not None:
                            sys.stdout.write("[" + str(propertyArrayIndex) + "]")

                        # check for an error
                        if readResult.propertyAccessError is not None:
                            sys.stdout.write(" ! " + str(readResult.propertyAccessError) + '\n')

                        else:
                            # here is the value
                            propertyValue = readResult.propertyValue

                            # find the datatype
                            datatype = get_datatype(objectIdentifier[0], propertyIdentifier)
                            if _debug: ReadPropertyMultipleConsoleCmd._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 (propertyArrayIndex is not None):
                                if propertyArrayIndex == 0:
                                    value = propertyValue.cast_out(Unsigned)
                                else:
                                    value = propertyValue.cast_out(datatype.subtype)
                            else:
                                value = propertyValue.cast_out(datatype)
                            if _debug: ReadPropertyMultipleConsoleCmd._debug("    - value: %r", value)

                            sys.stdout.write(" = " + str(value) + '\n')
                        sys.stdout.flush()

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

        except Exception as error:
            ReadPropertyMultipleConsoleCmd._exception("exception: %r", error)
Exemplo n.º 31
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
Exemplo n.º 32
0
    def readMultiple(self, args):
        """ This function build a readMultiple 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.readMultiple('2:5 analogInput 1 presentValue units')
        
        will read controller with a MAC address of 5 in the network 2
        Will ask for the present Value and the units of analog input 1 (AI:1)
        """        
        args = args.split()
        print_debug("readMultiple %r", args)

        try:
            i = 0
            addr = args[i]
            i += 1

            read_access_spec_list = []
            while i < len(args):
                obj_type = args[i]
                i += 1

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

                obj_inst = int(args[i])
                i += 1

                prop_reference_list = []
                while i < len(args):
                    prop_id = args[i]
                    if prop_id not in PropertyIdentifier.enumerations:
                        break

                    i += 1
                    if prop_id in ('all', 'required', 'optional'):
                        pass
                    else:
                        datatype = get_datatype(obj_type, prop_id)
                        if not datatype:
                            raise ValueError("invalid property for object type : %s | %s" % (obj_type, prop_id))

                    # build a property reference
                    prop_reference = PropertyReference(
                        propertyIdentifier=prop_id,
                        )

                    # check for an array index
                    if (i < len(args)) and args[i].isdigit():
                        prop_reference.propertyArrayIndex = int(args[i])
                        i += 1

                    # add it to the list
                    prop_reference_list.append(prop_reference)

                # check for at least one property
                if not prop_reference_list:
                    raise ValueError("provide at least one property")

                # build a read access specification
                read_access_spec = ReadAccessSpecification(
                    objectIdentifier=(obj_type, obj_inst),
                    listOfPropertyReferences=prop_reference_list,
                    )

                # add it to the list
                read_access_spec_list.append(read_access_spec)

            # check for at least one
            if not read_access_spec_list:
                raise RuntimeError("at least one read access specification required")

            # build the request
            request = ReadPropertyMultipleRequest(
                listOfReadAccessSpecs=read_access_spec_list,
                )
            request.pduDestination = Address(addr)
            print_debug("    - request: %r", request)

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

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

        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
Exemplo n.º 33
0
    def do_subscribe(self, args):
        """subscribe addr proc_id obj_type obj_inst [ confirmed ] [ lifetime ]

        Generate a SubscribeCOVRequest and wait for the response.
        """
        args = args.split()
        if _debug: SubscribeCOVConsoleCmd._debug("do_subscribe %r", args)

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

            proc_id = int(proc_id)

            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 len(args) >= 5:
                issue_confirmed = args[4]
                if issue_confirmed == '-':
                    issue_confirmed = None
                else:
                    issue_confirmed = issue_confirmed.lower() == 'true'
                if _debug: SubscribeCOVConsoleCmd._debug("    - issue_confirmed: %r", issue_confirmed)
            else:
                issue_confirmed = None

            if len(args) >= 6:
                lifetime = args[5]
                if lifetime == '-':
                    lifetime = None
                else:
                    lifetime = int(lifetime)
                if _debug: SubscribeCOVConsoleCmd._debug("    - lifetime: %r", lifetime)
            else:
                lifetime = None

            # build a request
            request = SubscribeCOVRequest(
                subscriberProcessIdentifier=proc_id,
                monitoredObjectIdentifier=(obj_type, obj_inst),
                )
            request.pduDestination = Address(addr)

            # optional parameters
            if issue_confirmed is not None:
                request.issueConfirmedNotifications = issue_confirmed
            if lifetime is not None:
                request.lifetime = lifetime

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

            # make an IOCB
            iocb = IOCB(request)
            if _debug: SubscribeCOVConsoleCmd._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:
                if _debug: SubscribeCOVConsoleCmd._debug("    - response: %r", iocb.ioResponse)

            # do something for error/reject/abort
            if iocb.ioError:
                if _debug: SubscribeCOVConsoleCmd._debug("    - error: %r", iocb.ioError)

        except Exception as e:
            SubscribeCOVConsoleCmd._exception("exception: %r", e)
Exemplo n.º 34
0
    def build_rpm_request(self, args):
        """
        Build request from args
        """
        i = 0
        addr = args[i]
        i += 1

        read_access_spec_list = []
        while i < len(args):
            obj_type = args[i]
            i += 1

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

            obj_inst = int(args[i])
            i += 1

            prop_reference_list = []
            while i < len(args):
                prop_id = args[i]
                if prop_id not in PropertyIdentifier.enumerations:
                    break

                i += 1
                if prop_id in ('all', 'required', 'optional'):
                    pass
                else:
                    datatype = get_datatype(obj_type, prop_id)
                    if not datatype:
                        raise ValueError(
                            "invalid property for object type : {} | {}".format(
                                (obj_type, prop_id)))

                # build a property reference
                prop_reference = PropertyReference(propertyIdentifier=prop_id)

                # check for an array index
                if (i < len(args)) and args[i].isdigit():
                    prop_reference.propertyArrayIndex = int(args[i])
                    i += 1

                prop_reference_list.append(prop_reference)

            if not prop_reference_list:
                raise ValueError("provide at least one property")

            # build a read access specification
            read_access_spec = ReadAccessSpecification(
                objectIdentifier=(obj_type, obj_inst),
                listOfPropertyReferences=prop_reference_list)

            read_access_spec_list.append(read_access_spec)

        if not read_access_spec_list:
            raise RuntimeError(
                "at least one read access specification required")

        # build the request
        request = ReadPropertyMultipleRequest(
            listOfReadAccessSpecs=read_access_spec_list)
        request.pduDestination = Address(addr)
        self._log.debug("{:<20} {!r}".format(
            'REQUEST', request))
        return request
Exemplo n.º 35
0
    def do_subscribe(self, args):
        """subscribe addr proc_id obj_type obj_inst [ confirmed ] [ lifetime ]
        """
        args = args.split()
        if _debug: SubscribeCOVConsoleCmd._debug("do_subscribe %r", args)

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

            proc_id = int(proc_id)

            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 len(args) >= 5:
                issue_confirmed = args[4]
                if issue_confirmed == '-':
                    issue_confirmed = None
                else:
                    issue_confirmed = issue_confirmed.lower() == 'true'
                if _debug:
                    SubscribeCOVConsoleCmd._debug("    - issue_confirmed: %r",
                                                  issue_confirmed)
            else:
                issue_confirmed = None

            if len(args) >= 6:
                lifetime = args[5]
                if lifetime == '-':
                    lifetime = None
                else:
                    lifetime = int(lifetime)
                if _debug:
                    SubscribeCOVConsoleCmd._debug("    - lifetime: %r",
                                                  lifetime)
            else:
                lifetime = None

            # build a request
            request = SubscribeCOVRequest(
                subscriberProcessIdentifier=proc_id,
                monitoredObjectIdentifier=(obj_type, obj_inst),
            )
            request.pduDestination = Address(addr)

            # optional parameters
            if issue_confirmed is not None:
                request.issueConfirmedNotifications = issue_confirmed
            if lifetime is not None:
                request.lifetime = lifetime

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

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

        except Exception as e:
            SubscribeCOVConsoleCmd._exception("exception: %r", e)
Exemplo n.º 36
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 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:
                        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(stream=sys.stdout)
                sys.stdout.flush()

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

        except Exception as error:
            ReadPropertyConsoleCmd._exception("exception: %r", error)
Exemplo n.º 37
0
    def do_read(self, args):
        """read <addr> ( <type> <inst> ( <prop> [ <indx> ] )... )..."""
        args = args.split()
        if _debug: ReadPropertyMultipleConsoleCmd._debug("do_read %r", args)

        try:
            i = 0
            addr = args[i]
            i += 1

            read_access_spec_list = []
            while i < len(args):
                obj_type = args[i]
                i += 1

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

                obj_inst = int(args[i])
                i += 1

                prop_reference_list = []
                while i < len(args):
                    prop_id = args[i]
                    if prop_id not in PropertyIdentifier.enumerations:
                        break

                    i += 1
                    if prop_id in ('all', 'required', 'optional'):
                        pass
                    else:
                        datatype = get_datatype(obj_type, prop_id)
                        if not datatype:
                            raise ValueError(
                                "invalid property for object type")

                    # build a property reference
                    prop_reference = PropertyReference(
                        propertyIdentifier=prop_id, )

                    # check for an array index
                    if (i < len(args)) and args[i].isdigit():
                        prop_reference.propertyArrayIndex = int(args[i])
                        i += 1

                    # add it to the list
                    prop_reference_list.append(prop_reference)

                # check for at least one property
                if not prop_reference_list:
                    raise ValueError("provide at least one property")

                # build a read access specification
                read_access_spec = ReadAccessSpecification(
                    objectIdentifier=(obj_type, obj_inst),
                    listOfPropertyReferences=prop_reference_list,
                )

                # add it to the list
                read_access_spec_list.append(read_access_spec)

            # check for at least one
            if not read_access_spec_list:
                raise RuntimeError(
                    "at least one read access specification required")

            # build the request
            request = ReadPropertyMultipleRequest(
                listOfReadAccessSpecs=read_access_spec_list, )
            request.pduDestination = Address(addr)
            if _debug:
                ReadPropertyMultipleConsoleCmd._debug("    - request: %r",
                                                      request)

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

                # loop through the results
                for result in apdu.listOfReadAccessResults:
                    # here is the object identifier
                    objectIdentifier = result.objectIdentifier
                    if _debug:
                        ReadPropertyMultipleConsoleCmd._debug(
                            "    - objectIdentifier: %r", objectIdentifier)

                    # now come the property values per object
                    for element in result.listOfResults:
                        # get the property and array index
                        propertyIdentifier = element.propertyIdentifier
                        if _debug:
                            ReadPropertyMultipleConsoleCmd._debug(
                                "    - propertyIdentifier: %r",
                                propertyIdentifier)
                        propertyArrayIndex = element.propertyArrayIndex
                        if _debug:
                            ReadPropertyMultipleConsoleCmd._debug(
                                "    - propertyArrayIndex: %r",
                                propertyArrayIndex)

                        # here is the read result
                        readResult = element.readResult

                        sys.stdout.write(propertyIdentifier)
                        if propertyArrayIndex is not None:
                            sys.stdout.write("[" + str(propertyArrayIndex) +
                                             "]")

                        # check for an error
                        if readResult.propertyAccessError is not None:
                            sys.stdout.write(
                                " ! " + str(readResult.propertyAccessError) +
                                '\n')

                        else:
                            # here is the value
                            propertyValue = readResult.propertyValue

                            # find the datatype
                            datatype = get_datatype(objectIdentifier[0],
                                                    propertyIdentifier)
                            if _debug:
                                ReadPropertyMultipleConsoleCmd._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 (propertyArrayIndex
                                                      is not None):
                                if propertyArrayIndex == 0:
                                    value = propertyValue.cast_out(Unsigned)
                                else:
                                    value = propertyValue.cast_out(
                                        datatype.subtype)
                            else:
                                value = propertyValue.cast_out(datatype)
                            if _debug:
                                ReadPropertyMultipleConsoleCmd._debug(
                                    "    - value: %r", value)

                            sys.stdout.write(" = " + str(value) + '\n')
                        sys.stdout.flush()

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

        except Exception, error:
            ReadPropertyMultipleConsoleCmd._exception("exception: %r", error)
Exemplo n.º 38
0
    def do_read(self, args):
        """read <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadPropertyAnyConsoleCmd._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)

            # 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:
                ReadPropertyAnyConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: ReadPropertyAnyConsoleCmd._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:
                    ReadPropertyAnyConsoleCmd._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:
                        ReadPropertyAnyConsoleCmd._debug(
                            "    - datatype: %r", datatype)
                    if not datatype:
                        raise TypeError("unknown datatype")

                    # cast out the value
                    value = apdu.propertyValue.cast_out(datatype)
                    if _debug:
                        ReadPropertyAnyConsoleCmd._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:
            ReadPropertyAnyConsoleCmd._exception("exception: %r", error)
Exemplo n.º 39
0
    def do_read(self, args):
        """read <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadPropertyAnyConsoleCmd._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)

            # build a request
            # Pascal: modifier propertyIdentifier=int(prop_id) ....j'ai ajouter le int(  )
            request = ReadPropertyRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=int(prop_id),
            )
            request.pduDestination = Address(addr)

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

            # make an IOCB
            iocb = IOCB(request)

            if _debug: ReadPropertyAnyConsoleCmd._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

                temp = ""
                opening_tag_0 = ""
                context_tag_1_2 = ""
                IP_NetNumber = 0
                context_tag_4 = ""
                opening_tag_5 = ""
                context_tag_6_7 = ""
                opening_tag_8 = ""
                IP_type = ""
                IP_Port = 0
                Foreign_ttl = 0
                Proxy_IP = "0.0.0.0"
                Foreign_IP = "0.0.0.0"
                context_tag_5_6 = ""
                context_tag_10_13 = ""

                #get tag type
                value_tag = apdu.propertyValue.tagList.Peek()

                #opening tag #0
                if value_tag.tagClass == Tag.openingTagClass:

                    value_tag = apdu.propertyValue.tagList.Pop()
                    value_tag = apdu.propertyValue.tagList.Peek()

                    for i in range(0, 2):
                        if (i >= 0) and (i <= 1):
                            opening_tag_0 = opening_tag_0 + str(
                                value_tag.tagData).encode('hex')

                        value_tag = apdu.propertyValue.tagList.Pop()
                        value_tag = apdu.propertyValue.tagList.Peek()
                        if (value_tag.tagClass == Tag.closingTagClass): break

                    sys.stdout.write("opening_tag_0: " + str(opening_tag_0) +
                                     "\n")

                else:
                    pass

                #Go forward in tagList
                value_tag = apdu.propertyValue.tagList.Pop()
                value_tag = apdu.propertyValue.tagList.Peek()

                #context tag #1,2,3,4. Get Net Number
                if value_tag.tagClass == Tag.contextTagClass:

                    for i in range(1, 5):
                        if (i >= 1) and (i <= 2):
                            context_tag_1_2 = context_tag_1_2 + str(
                                value_tag.tagData).encode('hex')
                        elif (i == 3):
                            IP_NetNumber = int(
                                str(value_tag.tagData).encode('hex'), 16)
                        elif (i == 4):
                            context_tag_4 = str(
                                value_tag.tagData).encode('hex')

                        value_tag = apdu.propertyValue.tagList.Pop()
                        value_tag = apdu.propertyValue.tagList.Peek()
                        if (value_tag.tagClass == Tag.openingTagClass): break

                    sys.stdout.write("context_tag_1_2: " +
                                     str(context_tag_1_2) + "\n")
                    sys.stdout.write("IP_NetNumber: " + str(IP_NetNumber) +
                                     "\n")
                    sys.stdout.write("context_tag_4: " + str(context_tag_4) +
                                     "\n")

                else:
                    pass

                #get next tag type
                value_tag = apdu.propertyValue.tagList.Peek()

                #opening tag #5
                if value_tag.tagClass == Tag.openingTagClass:

                    value_tag = apdu.propertyValue.tagList.Pop()
                    value_tag = apdu.propertyValue.tagList.Peek()

                    for i in range(0, 2):
                        if (i >= 0) and (i <= 1):
                            opening_tag_5 = opening_tag_5 + str(
                                value_tag.tagData).encode('hex')

                        value_tag = apdu.propertyValue.tagList.Pop()
                        value_tag = apdu.propertyValue.tagList.Peek()
                        if (value_tag.tagClass == Tag.closingTagClass): break

                    sys.stdout.write("opening_tag_5: " + str(opening_tag_5) +
                                     "\n")

                else:
                    pass

                #Go forward in tagList
                value_tag = apdu.propertyValue.tagList.Pop()
                value_tag = apdu.propertyValue.tagList.Peek()

                #context tag #6,7 Get Net Number
                if value_tag.tagClass == Tag.contextTagClass:

                    for i in range(6, 8):
                        if (i >= 6) and (i <= 7):
                            context_tag_6_7 = context_tag_6_7 + str(
                                value_tag.tagData).encode('hex')

                        value_tag = apdu.propertyValue.tagList.Pop()
                        value_tag = apdu.propertyValue.tagList.Peek()
                        if (value_tag.tagClass == Tag.openingTagClass): break

                    sys.stdout.write("context_tag_6_7: " +
                                     str(context_tag_6_7) + "\n")

                else:
                    pass

                #get next tag type
                value_tag = apdu.propertyValue.tagList.Peek()

                #opening tag #8
                if value_tag.tagClass == Tag.openingTagClass:

                    value_tag = apdu.propertyValue.tagList.Pop()
                    value_tag = apdu.propertyValue.tagList.Peek()

                    for i in range(0, 9):
                        if (i >= 0) and (i <= 8):
                            opening_tag_8 = opening_tag_8 + str(
                                value_tag.tagData).encode('hex')

                        value_tag = apdu.propertyValue.tagList.Pop()
                        value_tag = apdu.propertyValue.tagList.Peek()
                        if (value_tag.tagClass == Tag.closingTagClass): break

                    sys.stdout.write("opening_tag_8: " + str(opening_tag_8) +
                                     "\n")

                else:
                    pass

                #Go forward in tagList
                value_tag = apdu.propertyValue.tagList.Pop()
                value_tag = apdu.propertyValue.tagList.Peek()

                #opening tag #9. Get Device Type, IP port,  Proxy addr and Foreign addr
                if value_tag.tagClass == Tag.openingTagClass:

                    value_tag = apdu.propertyValue.tagList.Pop()
                    value_tag = apdu.propertyValue.tagList.Peek()

                    for i in range(0, 7):
                        if (i == 0):
                            IP_type = str(value_tag.tagData).encode('hex')
                        elif (i == 1):
                            IP_Port = int(
                                str(value_tag.tagData).encode('hex'), 16)
                        elif (i == 2):
                            temp = bytearray.fromhex(
                                str(value_tag.tagData).encode('hex'))
                            if len(temp) == 4:
                                Foreign_IP = str(temp[0]) + "." + str(
                                    temp[1]) + "." + str(temp[2]) + "." + str(
                                        temp[3])
                        elif (i == 3):
                            Foreign_ttl = int(
                                str(value_tag.tagData).encode('hex'), 16)
                        elif (i == 4):
                            temp = bytearray.fromhex(
                                str(value_tag.tagData).encode('hex'))
                            if len(temp) == 4:
                                Proxy_IP = str(temp[0]) + "." + str(
                                    temp[1]) + "." + str(temp[2]) + "." + str(
                                        temp[3])
                        if (i >= 5) and (i <= 6):
                            context_tag_5_6 = context_tag_5_6 + str(
                                value_tag.tagData).encode('hex')

                        value_tag = apdu.propertyValue.tagList.Pop()
                        value_tag = apdu.propertyValue.tagList.Peek()
                        if (value_tag.tagClass == Tag.closingTagClass): break

                    sys.stdout.write(
                        "Bacnet IP Type (00=Regular 01=Foreign 02=BBMD): " +
                        str(IP_type) + "\n")
                    sys.stdout.write("BACnet IP Port: " + str(IP_Port) + "\n")
                    sys.stdout.write("Bacnet IP Foreign Address: " +
                                     str(Foreign_IP) + "\n")
                    sys.stdout.write("Bacnet IP Foreign time to live: " +
                                     str(Foreign_ttl) + "\n")
                    sys.stdout.write("Bacnet IP Proxy Address: " +
                                     str(Proxy_IP) + "\n")
                    sys.stdout.write("context_tag_5_6: " +
                                     str(context_tag_5_6) + "\n")

                else:
                    pass

                #Go forward in tagList
                value_tag = apdu.propertyValue.tagList.Pop()
                value_tag = apdu.propertyValue.tagList.Peek()

                #context tag #10,11,12,13
                if value_tag.tagClass == Tag.contextTagClass:

                    for i in range(10, 14):
                        if (i >= 10) and (i <= 13):
                            context_tag_10_13 = context_tag_10_13 + str(
                                value_tag.tagData).encode('hex')

                        value_tag = apdu.propertyValue.tagList.Pop()
                        value_tag = apdu.propertyValue.tagList.Peek()
                        if (i == 14): break

                    sys.stdout.write("context_tag_10_13: " +
                                     str(context_tag_10_13) + "\n")

                else:
                    pass

                sys.stdout.flush()

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

        except Exception as error:
            ReadPropertyAnyConsoleCmd._exception("exception: %r", error)
Exemplo n.º 40
0
    def do_readrange(self, args):
        """readrange <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadRangeConsoleCmd._debug("do_readrange %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 = ReadRangeRequest(
                objectIdentifier=(obj_type, obj_inst),
                propertyIdentifier=prop_id,
            )
            request.pduDestination = Address(addr)

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

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

                # find the datatype
                datatype = get_datatype(apdu.objectIdentifier[0],
                                        apdu.propertyIdentifier)
                if _debug:
                    ReadRangeConsoleCmd._debug("    - datatype: %r", datatype)
                if not datatype:
                    raise TypeError("unknown datatype")

                # cast out the data into a list
                value = apdu.itemData[0].cast_out(datatype)

                # dump it out
                for i, item in enumerate(value):
                    sys.stdout.write("[%d]\n" % (i, ))
                    item.debug_contents(file=sys.stdout, indent=2)
                sys.stdout.flush()

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

        except Exception as error:
            ReadRangeConsoleCmd._exception("exception: %r", error)
Exemplo n.º 41
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)
Exemplo n.º 42
0
def main():
    global this_application, device_address, object_identifier, property_list

    # parse the command line arguments
    parser = ConfigArgumentParser(description=__doc__)
    parser.add_argument(
        "address",
        help="device address",
    )
    parser.add_argument(
        "objtype",
        help="object types, e.g., analogInput",
    )
    parser.add_argument(
        "objinstance",
        type=int,
        help="object instance",
    )
    args = parser.parse_args()

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

    # interpret the address
    device_address = Address(args.address)
    if _debug: _log.debug("    - device_address: %r", device_address)

    # build an identifier
    object_identifier = (args.objtype, args.objinstance)
    if _debug: _log.debug("    - object_identifier: %r", object_identifier)

    # get the object class
    object_class = get_object_class(args.objtype)
    if _debug: _log.debug("    - object_class: %r", object_class)

    # make a queue of the properties
    property_list = deque(prop.identifier for prop in object_class.properties)
    if _debug: _log.debug("    - property_list: %r", property_list)

    # 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 = ReadPropertyApplication(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

    # fire off a request when the core has a chance
    deferred(this_application.next_request)

    _log.debug("running")

    run()

    _log.debug("fini")
    def do_write(self, args):
        """write <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]"""
        global this_application

        args = args.split()
        ReadWritePropertyConsoleCmd._debug("do_write %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)

            value = args[4]

            indx = None
            if len(args) >= 6:
                if args[5] != "-":
                    indx = int(args[5])
            if _debug:
                ReadWritePropertyConsoleCmd._debug("    - indx: %r", indx)

            priority = None
            if len(args) >= 7:
                priority = int(args[6])
            if _debug:
                ReadWritePropertyConsoleCmd._debug("    - priority: %r",
                                                   priority)

            # get the datatype
            datatype = get_datatype(obj_type, prop_id,
                                    VendorAVObject.vendor_id)
            if _debug:
                ReadWritePropertyConsoleCmd._debug("    - datatype: %r",
                                                   datatype)

            # change atomic values into something encodeable, null is a special case
            if (value == 'null'):
                value = Null()
            elif issubclass(datatype, Atomic):
                if datatype is Integer:
                    value = int(value)
                elif datatype is Real:
                    value = float(value)
                elif datatype is Unsigned:
                    value = int(value)
                value = datatype(value)
            elif issubclass(datatype, Array) and (indx is not None):
                if indx == 0:
                    value = Integer(value)
                elif issubclass(datatype.subtype, Atomic):
                    value = datatype.subtype(value)
                elif not isinstance(value, datatype.subtype):
                    raise TypeError, "invalid result datatype, expecting %s" % (
                        datatype.subtype.__name__, )
            elif not isinstance(value, datatype):
                raise TypeError, "invalid result datatype, expecting %s" % (
                    datatype.__name__, )
            if _debug:
                ReadWritePropertyConsoleCmd._debug(
                    "    - encodeable value: %r %s", value, type(value))

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

            # save the value
            request.propertyValue = Any()
            try:
                request.propertyValue.cast_in(value)
            except Exception, e:
                ReadWritePropertyConsoleCmd._exception(
                    "WriteProperty cast error: %r", e)

            # optional array index
            if indx is not None:
                request.propertyArrayIndex = indx

            # optional priority
            if priority is not None:
                request.priority = priority

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

            # give it to the application
            this_application.request(request)
Exemplo n.º 44
0
    def test_make_iocb(self):
        """inputs
        -------
        read_args : (iterable) of ('', 'read', <address>, <object_identifier>)
            address : (str) BACnet IP address of device we are trying to
                communicate with. Example 192.168.1.100
            object_identifier : (str) BACnet Object Identifier of the device
                defined in 'address'. This is of the form
                <ObjectType>:<Instance>.
                Typical values for ObjectType can be found where?
            """

        read_args = ('192.168.1.100', 'analogValue:1')

        addr, obj_id = read_args[:2]
        obj_id = ObjectIdentifier(obj_id).value

        # Enforce a specific object type
        if not get_object_class(
                obj_id[0]):  # bacpypes.object.AnalogInputObject
            raise ValueError("unknown object type")

        # implement a default property, the bain of committee meetings
        if len(read_args) == 3:
            prop_id = read_args[2]
        else:
            prop_id = "presentValue"

        # look for its datatype, an easy way to see if the property is
        # appropriate for the object
        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)

        # look for an optional array index
        if len(read_args) == 5:
            request.propertyArrayIndex = int(read_args[4])

        # make an IOCB
        iocb = IOCB(request)

        # Information related to destination and network control (context information and processing instructions)
        apci_contents = request.apci_contents()
        self.assertEqual(apci_contents['destination'], read_args[0])
        # Read property requests always require a confirmation PDU
        self.assertEqual(apci_contents['apduType'], 'ConfirmedRequestPDU')
        # This test only applies to ReadPropertyRequests
        self.assertEqual(apci_contents['apduService'], 'ReadPropertyRequest')

        # Information related to DATA
        apdu_contents = request.apdu_contents()
        self.assertEqual(apdu_contents['function'], 'ReadPropertyRequest')
        self.assertEqual(apdu_contents['objectIdentifier'], ('analogValue', 1))
        self.assertEqual(apdu_contents['propertyIdentifier'], 'presentValue')

        # Testing of IOCB - not much to test
        self.assertIsInstance(iocb.args[0], ReadPropertyRequest)
        return None
Exemplo n.º 45
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
Exemplo n.º 46
0
    def do_subscribe(self, args):
        """subscribe addr proc_id obj_type obj_inst [ confirmed ] [ lifetime ]

        Generate a SubscribeCOVRequest and wait for the response.
        """
        args = args.split()
        if _debug: SubscribeCOVConsoleCmd._debug("do_subscribe %r", args)

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

            proc_id = int(proc_id)

            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 len(args) >= 5:
                issue_confirmed = args[4]
                if issue_confirmed == '-':
                    issue_confirmed = None
                else:
                    issue_confirmed = issue_confirmed.lower() == 'true'
                if _debug:
                    SubscribeCOVConsoleCmd._debug("    - issue_confirmed: %r",
                                                  issue_confirmed)
            else:
                issue_confirmed = None

            if len(args) >= 6:
                lifetime = args[5]
                if lifetime == '-':
                    lifetime = None
                else:
                    lifetime = int(lifetime)
                if _debug:
                    SubscribeCOVConsoleCmd._debug("    - lifetime: %r",
                                                  lifetime)
            else:
                lifetime = None

            # build a request
            request = SubscribeCOVRequest(
                subscriberProcessIdentifier=proc_id,
                monitoredObjectIdentifier=(obj_type, obj_inst),
            )
            request.pduDestination = Address(addr)

            # optional parameters
            if issue_confirmed is not None:
                request.issueConfirmedNotifications = issue_confirmed
            if lifetime is not None:
                request.lifetime = lifetime

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

            # make an IOCB
            iocb = IOCB(request)
            if _debug: SubscribeCOVConsoleCmd._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:
                if _debug:
                    SubscribeCOVConsoleCmd._debug("    - response: %r",
                                                  iocb.ioResponse)

            # do something for error/reject/abort
            if iocb.ioError:
                if _debug:
                    SubscribeCOVConsoleCmd._debug("    - error: %r",
                                                  iocb.ioError)

        except Exception as e:
            SubscribeCOVConsoleCmd._exception("exception: %r", e)
Exemplo n.º 47
0
    def do_subscribe(self, args):
        """subscribe addr proc_id obj_type obj_inst [ confirmed ] [ lifetime ]
        """
        args = args.split()
        if _debug: COVConsoleCmd._debug("do_subscribe %r", args)
        global test_application

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

            client_addr = Address(addr)
            if _debug: COVConsoleCmd._debug("    - client_addr: %r", client_addr)

            proc_id = int(proc_id)
            if _debug: COVConsoleCmd._debug("    - proc_id: %r", proc_id)

            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)
            obj_id = (obj_type, obj_inst)
            if _debug: COVConsoleCmd._debug("    - obj_id: %r", obj_id)

            obj = test_application.get_object_id(obj_id)
            if not obj:
                print("object not found")
                return

            if len(args) >= 5:
                issue_confirmed = args[4]
                if issue_confirmed == '-':
                    issue_confirmed = None
                else:
                    issue_confirmed = issue_confirmed.lower() == 'true'
                if _debug: COVConsoleCmd._debug("    - issue_confirmed: %r", issue_confirmed)
            else:
                issue_confirmed = None

            if len(args) >= 6:
                lifetime = args[5]
                if lifetime == '-':
                    lifetime = None
                else:
                    lifetime = int(lifetime)
                if _debug: COVConsoleCmd._debug("    - lifetime: %r", lifetime)
            else:
                lifetime = None

            # can a match be found?
            cov = obj._cov_subscriptions.find(client_addr, proc_id, obj_id)
            if _debug: COVConsoleCmd._debug("    - cov: %r", cov)

            # build a request
            request = SubscribeCOVRequest(
                subscriberProcessIdentifier=proc_id,
                monitoredObjectIdentifier=obj_id,
                )

            # spoof that it came from the client
            request.pduSource = client_addr

            # optional parameters
            if issue_confirmed is not None:
                request.issueConfirmedNotifications = issue_confirmed
            if lifetime is not None:
                request.lifetime = lifetime

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

            # give it to the application
            test_application.do_SubscribeCOVRequest(request)

        except Exception as err:
            COVConsoleCmd._exception("exception: %r", err)
Exemplo n.º 48
0
    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)
Exemplo n.º 49
0
def create_ReadPropertyMultipleRequest(args):
    """
    Create a request to compare with called arg
    """
    args = args.split()

    i = 0
    addr = args[i]
    i += 1

    read_access_spec_list = []
    while i < len(args):
        obj_type = args[i]
        i += 1

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

        obj_inst = int(args[i])
        i += 1

        prop_reference_list = []
        while i < len(args):
            prop_id = args[i]
            if prop_id not in PropertyIdentifier.enumerations:
                break

            i += 1
            if prop_id in ('all', 'required', 'optional'):
                pass
            else:
                datatype = get_datatype(obj_type, prop_id)
                if not datatype:
                    raise ValueError(
                        "invalid property for object type : %s | %s" %
                        (obj_type, prop_id))

            # build a property reference
            prop_reference = PropertyReference(
                propertyIdentifier=prop_id,
            )

            # check for an array index
            if (i < len(args)) and args[i].isdigit():
                prop_reference.propertyArrayIndex = int(args[i])
                i += 1

            # add it to the list
            prop_reference_list.append(prop_reference)

        # check for at least one property
        if not prop_reference_list:
            raise ValueError("provide at least one property")

        # build a read access specification
        read_access_spec = ReadAccessSpecification(
            objectIdentifier=(obj_type, obj_inst),
            listOfPropertyReferences=prop_reference_list,
        )

        # add it to the list
        read_access_spec_list.append(read_access_spec)

    # check for at least one
    if not read_access_spec_list:
        raise RuntimeError(
            "at least one read access specification required")

    # build the request
    request = ReadPropertyMultipleRequest(
        listOfReadAccessSpecs=read_access_spec_list,
    )
    request.pduDestination = Address(addr)
    return request
Exemplo n.º 50
0
    def do_write(self, args):
        """write <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]"""
        global this_application

        args = args.split()
        ReadWritePropertyConsoleCmd._debug("do_write %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)

            value = args[4]

            indx = None
            if len(args) >= 6:
                if args[5] != "-":
                    indx = int(args[5])
            if _debug: ReadWritePropertyConsoleCmd._debug("    - indx: %r", indx)

            priority = None
            if len(args) >= 7:
                priority = int(args[6])
            if _debug: ReadWritePropertyConsoleCmd._debug("    - priority: %r", priority)

            # get the datatype
            datatype = get_datatype(obj_type, prop_id, VendorAVObject.vendor_id)
            if _debug: ReadWritePropertyConsoleCmd._debug("    - datatype: %r", datatype)

            # change atomic values into something encodeable, null is a special case
            if (value == 'null'):
                value = Null()
            elif issubclass(datatype, Atomic):
                if datatype is Integer:
                    value = int(value)
                elif datatype is Real:
                    value = float(value)
                elif datatype is Unsigned:
                    value = int(value)
                value = datatype(value)
            elif issubclass(datatype, Array) and (indx is not None):
                if indx == 0:
                    value = Integer(value)
                elif issubclass(datatype.subtype, Atomic):
                    value = datatype.subtype(value)
                elif not isinstance(value, datatype.subtype):
                    raise TypeError, "invalid result datatype, expecting %s" % (datatype.subtype.__name__,)
            elif not isinstance(value, datatype):
                raise TypeError, "invalid result datatype, expecting %s" % (datatype.__name__,)
            if _debug: ReadWritePropertyConsoleCmd._debug("    - encodeable value: %r %s", value, type(value))

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

            # save the value
            request.propertyValue = Any()
            try:
                request.propertyValue.cast_in(value)
            except Exception, e:
                ReadWritePropertyConsoleCmd._exception("WriteProperty cast error: %r", e)

            # optional array index
            if indx is not None:
                request.propertyArrayIndex = indx

            # optional priority
            if priority is not None:
                request.priority = priority

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

            # give it to the application
            this_application.request(request)
Exemplo n.º 51
0
    def do_read(self, args):
        if _debug:
            ThreadedHTTPRequestHandler._debug("do_read %r", args)

        try:
            addr, obj_id = args[:2]
            obj_id = ObjectIdentifier(obj_id).value

            # get the object type
            if not get_object_class(obj_id[0]):
                raise ValueError("unknown object type")

            # implement a default property, the bain of committee meetings
            if len(args) == 3:
                prop_id = args[2]
                if prop_id.isdigit():
                    prop_id = int(prop_id)
            else:
                prop_id = "presentValue"

            # look for its datatype, an easy way to see if the property is
            # appropriate for the object
            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)

            # look for an optional array index
            if len(args) == 5:
                request.propertyArrayIndex = int(args[4])
            if _debug:
                ThreadedHTTPRequestHandler._debug("    - request: %r", request)

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

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

            # wait for it to complete
            iocb.wait()

            # filter out errors and aborts
            if iocb.ioError:
                if _debug:
                    ThreadedHTTPRequestHandler._debug("    - error: %r",
                                                      iocb.ioError)
                result = {"error": str(iocb.ioError)}
            else:
                if _debug:
                    ThreadedHTTPRequestHandler._debug("    - response: %r",
                                                      iocb.ioResponse)
                apdu = iocb.ioResponse

                # find the datatype
                datatype = get_datatype(apdu.objectIdentifier[0],
                                        apdu.propertyIdentifier)
                if _debug:
                    ThreadedHTTPRequestHandler._debug("    - datatype: %r",
                                                      datatype)
                if not datatype:
                    raise TypeError("unknown datatype")

                # special case for array parts, others are managed by cast_out
                if issubclass(datatype, Array) and (apdu.propertyArrayIndex
                                                    is not None):
                    if apdu.propertyArrayIndex == 0:
                        datatype = Unsigned
                    else:
                        datatype = datatype.subtype
                    if _debug:
                        ThreadedHTTPRequestHandler._debug(
                            "    - datatype: %r", datatype)

                # convert the value to a dict if possible
                value = apdu.propertyValue.cast_out(datatype)
                if hasattr(value, "dict_contents"):
                    value = value.dict_contents(as_class=OrderedDict)
                if _debug:
                    ThreadedHTTPRequestHandler._debug("    - value: %r", value)

                result = {"value": value}

        except Exception as err:
            ThreadedHTTPRequestHandler._exception("exception: %r", err)
            result = {"exception": str(err)}

        # encode the results as JSON, convert to bytes
        result_bytes = json.dumps(result).encode("utf-8")

        # write the result
        self.wfile.write(result_bytes)