Example #1
0
    def confirmation(self, apdu):
        # build a key to look for the IOCB
        invoke_key = (apdu.pduSource, apdu.apduInvokeID)
        # find the request
        iocb = self.iocb.get(invoke_key, None)
        if not iocb:
            super()._app_complete(apdu.pduSource, apdu)
            return

        del self.iocb[invoke_key]

        if isinstance(apdu, Error):
            iocb.ioResponse = apdu
        elif isinstance(apdu, AbortPDU):
            iocb.ioResponse = apdu
        elif (isinstance(iocb.ioRequest, ReadPropertyRequest)) and (isinstance(
                apdu, ReadPropertyACK)):
            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0],
                                    apdu.propertyIdentifier)
            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)

            # assume primitive values for now, JSON would be better
            iocb.ioResponse = value

            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0],
                                    apdu.propertyIdentifier)
            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)

            # assume primitive values for now, JSON would be better
            iocb.ioResponse = value
        else:
            iocb.ioResponse = 'ok'

        # trigger the completion event
        iocb.ioComplete.set()
	def confirmation(self, apdu):
		if self._debug: print("confirmation %r", apdu)

		if isinstance(apdu, Error):
			sys.stdout.write("error: %s\n" % (apdu.errorCode,))
			sys.stdout.flush()
			if isinstance(self._request, WritePropertyRequest):
				self._hmi.report(False)
			elif isinstance(self._request, ReadPropertyRequest):
				self._hmi.report(None)

		elif isinstance(apdu, AbortPDU):
			apdu.debug_contents()

		elif (isinstance(self._request, ReadPropertyRequest)) and (isinstance(apdu, ReadPropertyACK)):
			# find the datatype
			datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
			if self._debug: print("	- 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 isinstance(value, float):
					value = round(value, 4)
				self._hmi.report(value)
			if self._debug: print("	- value: %r", value)

			#sys.stdout.write(str(value) + '\n')
			if hasattr(value, 'debug_contents'):
				value.debug_contents(file=sys.stdout)
			sys.stdout.flush()

		elif (isinstance(self._request, WritePropertyRequest)) and (isinstance(apdu, SimpleAckPDU)):
			self._hmi.report(True)

		elif (isinstance(self._request, ReadRangeRequest)) and (isinstance(apdu, ReadRangeACK)):
			# find the datatype
			datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
			if self._debug: print("	- datatype: %r", datatype)
			if not datatype:
				raise TypeError, "unknown datatype"

			# cast out of the single Any element into the datatype
			value = apdu.itemData[0].cast_out(datatype)

			# dump it out
			res = []
			for i, item in enumerate(value):
				res.append((i, item.logDatum.realValue))
			self._hmi.report(res)
    def _emit_responses(self, device_id, target_address, objects):
        """
        results = {}
        results['Reference Point Name'] = results[
            'Volttron Point Name'] = object_name
        results['Units'] = object_units
        results['Unit Details'] = object_units_details
        results['BACnet Object Type'] = obj_type
        results['Property'] = 'presentValue'
        results['Writable'] = writable
        results['Index'] = index
        results['Notes'] = object_notes

        :param objects:
        :return:
        """

        self._log.debug('emit_responses: objects: {}'.format(objects))
        for index, obj in objects.items():
            object_type = obj['object_type']
            present_value_type = get_datatype(object_type, 'presentValue')

            object_units_details = ''
            object_units = ''
            object_notes = ''

            if issubclass(present_value_type, Boolean):
                object_units = 'Boolean'
            elif issubclass(present_value_type, Enumerated):
                object_units, object_units_details, object_notes = \
                    self._process_enumerated(object_type, obj)
            elif get_datatype(object_type, 'units') is None:
                object_units, object_units_details, object_notes = \
                    self._process_units(object_type, obj)
            else:
                object_units, object_units_details, object_notes = \
                    self._process_unknown(object_type, obj)

            results = {}
            results['Reference Point Name'] = results[
                 'Volttron Point Name'] = obj['object_name']
            results['Units'] = object_units
            results['Unit Details'] = object_units_details
            results['BACnet Object Type'] = object_type
            results['Property'] = 'presentValue'
            results['Writable'] = 'FALSE'
            results['Index'] = obj['index']
            results['Notes'] = object_notes
            self._response_function(dict(device_id=device_id,
                                         address=target_address), results)
    def _emit_responses(self, device_id, target_address, objects):
        """
        results = {}
        results['Reference Point Name'] = results[
            'Volttron Point Name'] = object_name
        results['Units'] = object_units
        results['Unit Details'] = object_units_details
        results['BACnet Object Type'] = obj_type
        results['Property'] = 'presentValue'
        results['Writable'] = writable
        results['Index'] = index
        results['Notes'] = object_notes

        :param objects:
        :return:
        """

        _log.debug('emit_responses: objects: {}'.format(objects))
        for index, obj in objects.items():
            object_type = obj['object_type']
            present_value_type = get_datatype(object_type, 'presentValue')

            object_units_details = ''
            object_units = ''
            object_notes = ''

            if issubclass(present_value_type, Boolean):
                object_units = 'Boolean'
            elif issubclass(present_value_type, Enumerated):
                object_units, object_units_details, object_notes = \
                    self._process_enumerated(object_type, obj)
            elif get_datatype(object_type, 'units') is None:
                object_units, object_units_details, object_notes = \
                    self._process_units(object_type, obj)
            else:
                object_units, object_units_details, object_notes = \
                    self._process_unknown(object_type, obj)

            results = {}
            results['Reference Point Name'] = results[
                'Volttron Point Name'] = obj['object_name']
            results['Units'] = object_units
            results['Unit Details'] = object_units_details
            results['BACnet Object Type'] = object_type
            results['Property'] = 'presentValue'
            results['Writable'] = 'FALSE'
            results['Index'] = obj['index']
            results['Notes'] = object_notes
            self._response_function(
                dict(device_id=device_id, address=target_address), results)
    def confirmation(self, apdu):
        if _debug: ReadPropertyApplication._debug("confirmation %r", apdu)

        if isinstance(apdu, Error):
            sys.stdout.write("error: %s\n" % (apdu.errorCode,))
            sys.stdout.flush()

        elif isinstance(apdu, AbortPDU):
            apdu.debug_contents()

        if isinstance(apdu, SimpleAckPDU):
            sys.stdout.write("ack\n")
            sys.stdout.flush()

        elif (isinstance(self._request, ReadPropertyRequest)) and (isinstance(apdu, ReadPropertyACK)):
            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier, VendorAVObject.vendor_id)
            if _debug: ReadPropertyApplication._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: ReadPropertyApplication._debug("    - value: %r", value)

            sys.stdout.write(str(value) + '\n')
            sys.stdout.flush()
Example #6
0
def write_bacnet(app, address, obj_type, obj_inst, prop_id, value, index=None):

    request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst),
                                   propertyIdentifier=prop_id)
    request.pduDestination = address
    datatype = get_datatype(obj_type, prop_id)
    if (value is None or value == 'null'):
        bac_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)
        bac_value = datatype(value)
    elif issubclass(datatype, Array) and (index is not None):
        if index == 0:
            bac_value = Integer(value)
        elif issubclass(datatype.subtype, Atomic):
            bac_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__, ))

    request.propertyValue = Any()
    request.propertyValue.cast_in(bac_value)
    result = app.make_request(request)
    if isinstance(result, SimpleAckPDU):
        print "Write Successful !!"
    else:
        print "Write was not successful !!"
    def complete_request(self, iocb):
        if _debug: ReadPointListApplication._debug("complete_request %r", iocb)

        if iocb.ioResponse:
            apdu = iocb.ioResponse

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

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

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

        # fire off another request
        deferred(self.next_request)
    def callback(self, iocb):
        try:
            global result, count, tag_keys
            import datetime
            dt = datetime.datetime.now()
            count += 1
            #print iocb.ioResponse,iocb.ioError
            if iocb.ioResponse:
                apdu = iocb.ioResponse
                key = str(apdu.pduSource) + "#" + str(
                    apdu.objectIdentifier[0]) + "#" + str(
                        apdu.objectIdentifier[1]) + "#" + apdu.apdu_contents(
                        )["propertyIdentifier"]
                tag = tag_keys.pop(key)
                timestamp = dt.strftime("%Y-%m-%d %H:%M:%S")
                datatype = get_datatype(
                    apdu.objectIdentifier[0],
                    apdu.apdu_contents()["propertyIdentifier"])
                if not datatype:
                    raise TypeError("unknown datatype")

                value = apdu.propertyValue.cast_out(datatype)

                result.append({
                    "timestamp": timestamp,
                    "value": str(value),
                    "item": tag["tag"],
                    "quality": "Good"
                })

            if count == len(tag_list):
                stop()
        except Exception as e:
            print e, "=================================="
            raise e
    def confirmation(self, apdu):
        if _debug: ReadPropertyApplication._debug("confirmation %r", apdu)

        if isinstance(apdu, Error):
            sys.stdout.write("error: %s\n" % (apdu.errorCode,))
            sys.stdout.flush()

        elif isinstance(apdu, AbortPDU):
            apdu.debug_contents()

        if isinstance(apdu, SimpleAckPDU):
            sys.stdout.write("ack\n")
            sys.stdout.flush()

        elif (isinstance(self._request, ReadPropertyRequest)) and (isinstance(apdu, ReadPropertyACK)):
            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
            if _debug: ReadPropertyApplication._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: ReadPropertyApplication._debug("    - value: %r", value)

            sys.stdout.write(str(value) + '\n')
            sys.stdout.flush()
    def do_read(self, args):
        """read <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadWritePropertyConsoleCmd._debug("do_read %r", args)

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

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

            obj_inst = int(obj_inst)

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

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

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

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

        except Exception, e:
            ReadWritePropertyConsoleCmd._exception("exception: %r", e)
Example #11
0
    def do_read(self):
        try:
            # query the present value of 'MLNTZ.PNL.J.DEMAND'
            obj_type = datapoints[point_count]['obj_type']
            obj_inst = datapoints[point_count]['obj_inst']
            prop_id =  datapoints[point_count]['prop_id']
            
            if not get_object_class(obj_type):
                raise ValueError, "unknown object type: " + obj_type

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

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

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

        except Exception, e:
            _log.exception("exception: %r", e)
Example #12
0
 def __init__(self, instance_number, object_type, property_name, read_only, pointName, units, description = ''):
     super(BACnetRegister, self).__init__("byte", read_only, pointName, units, description = '')
     self.instance_number = int(instance_number)
     self.object_type = object_type
     self.property = property_name
     
     # find the datatype
     self.datatype = get_datatype(object_type, property_name)
     if self.datatype is None:
         raise TypeError('Invalid Register Type')
     
     if not issubclass(self.datatype, (Enumerated,
                                       Unsigned,
                                       Boolean,
                                       Integer,
                                       Real,
                                       Double)):
         raise TypeError('Invalid Register Type') 
     
     if issubclass(self.datatype, (Enumerated,
                                   Unsigned,
                                   Boolean,
                                   Integer)):
         self.python_type = int
     else:
         self.python_type = float
Example #13
0
    def _build_rp_request(self):
        addr = self.address()
        obj_type = self.obj_type()
        prop_id = self.property_id()
        vendor_id = self.vendor_id()
        bacoid = self.id()

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

        obj_inst = int(self.instance())

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

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

        self.logger.debug("{:<20} {!r}".format('REQUEST', request))
        return request
Example #14
0
    def confirmation(self, apdu):
        if _debug: PrairieDog._debug("confirmation %r", apdu)

        if isinstance(apdu, Error):
            if _debug: PrairieDog._debug("    - error: %r", apdu)
            self.response_values.append(apdu)

        elif isinstance(apdu, AbortPDU):
            if _debug: PrairieDog._debug("    - abort: %r", apdu)
            self.response_values.append(apdu)

        elif (isinstance(self._request, ReadPropertyRequest)) and (isinstance(apdu, ReadPropertyACK)):
            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
            if _debug: PrairieDog._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: PrairieDog._debug("    - value: %r", value)

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

        # fire off another request
        deferred(self.next_request)
Example #15
0
    def __init__(self,
                 instance_number,
                 object_type,
                 property_name,
                 read_only,
                 pointName,
                 units,
                 description=''):
        super(BACnetRegister, self).__init__("byte",
                                             read_only,
                                             pointName,
                                             units,
                                             description='')
        self.instance_number = int(instance_number)
        self.object_type = object_type
        self.property = property_name

        # find the datatype
        self.datatype = get_datatype(object_type, property_name)
        if self.datatype is None:
            raise TypeError('Invalid Register Type')

        if not issubclass(
                self.datatype,
            (Enumerated, Unsigned, Boolean, Integer, Real, Double)):
            raise TypeError('Invalid Register Type')

        if issubclass(self.datatype, (Enumerated, Unsigned, Boolean, Integer)):
            self.python_type = int
        else:
            self.python_type = float
Example #16
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)
Example #17
0
    def build_rp_request(self, args, arr_index = None):
        addr, obj_type, obj_inst, prop_id = args[:4]

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

        obj_inst = int(obj_inst)

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

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

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

        return request              
Example #18
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
Example #19
0
    def build_rp_request(self, args, arr_index=None, vendor_id=0, bacoid=None):
        addr, obj_type, obj_inst, prop_id = args[:4]
        vendor_id = vendor_id
        bacoid = bacoid

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

        obj_inst = int(obj_inst)

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

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

        if len(args) == 5:
            request.propertyArrayIndex = int(args[4])
        self._log.debug("{:<20} {!r}".format(
            'REQUEST', request))
        return request
Example #20
0
    def complete_request(self, iocb):

        if iocb.ioResponse:
            apdu = iocb.ioResponse

            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0],
                                    apdu.propertyIdentifier)
            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)

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

        if iocb.ioError:
            self.response_values.append(iocb.ioError)

        # fire off another request
        deferred(self.next_request)
Example #21
0
    def do_read(self, args):
        """read <addr> <objid> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: TestConsoleCmd._debug("do_read %r", args)

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

            datatype = get_datatype(obj_id[0], prop_id)
            if not datatype:
                raise ValueError, "invalid property for object type"

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

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

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

        except Exception, e:
            TestConsoleCmd._exception("exception: %r", e)
Example #22
0
    def read(self, obj_type, obj_inst, prop_id, address):
        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            print("invalid property %s for object type %s" % (prop_id,object_type))
            return "error invalid property %s for object type %s" % (prop_id,object_type)

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

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

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

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

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

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

        return n
Example #23
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
def get_static_object_types():
    obj_types = ObjectType.enumerations.keys()
    non_dynamic_objects = [
        obj_type for obj_type in obj_types
        if not get_datatype(obj_type, 'presentValue')
    ]
    return non_dynamic_objects
Example #25
0
def create_ReadPropertyRequest(args):
    """
    Create a ReadPropertyRequest from a string
    """
    args = args.split()
    addr, obj_type, obj_inst, prop_id = args[:4]
    print(addr)

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

    obj_inst = int(obj_inst)

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

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

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

    return request
Example #26
0
    def build_wp_request(self, args, vendor_id=0):
        vendor_id = vendor_id
        addr = args[0]
        args = args[1:]
        obj_type, obj_inst, prop_id, value, priority, indx = self._parse_wp_args(
            args)

        value = self._validate_value_vs_datatype(obj_type, prop_id, indx,
                                                 vendor_id, value)
        # build a request
        request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst),
                                       propertyIdentifier=prop_id)
        request.pduDestination = Address(addr)

        # save the value
        request.propertyValue = value

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

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

        self.log_subtitle("Creating Request")
        self._log.debug("{:<20} {:<20} {:<20} {:<20}".format(
            "indx", "priority", "datatype", "value"))
        datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id)

        self._log.debug("{!r:<20} {!r:<20} {!r:<20} {!r:<20}".format(
            indx, priority, datatype, value))

        self._log.debug("{:<20} {}".format("REQUEST", request))
        return request
Example #27
0
 def do_UnconfirmedCOVNotificationRequest(self, apdu):
     global rsvp
     for element in apdu.listOfValues:
         datatype = get_datatype(apdu.monitoredObjectIdentifier[0],
                                 element.propertyIdentifier)
         if not datatype:
             pass
         if issubclass(datatype, Array) and (element.propertyArrayIndex
                                             is not None):
             if element.propertyArrayIndex == 0:
                 value = element.value.cast_out(Unsigned)
             else:
                 value = element.value.cast_out(datatype.subtype)
         else:
             value = element.value.cast_out(datatype)
         deviceid = str(apdu.initiatingDeviceIdentifier[1])
         objecto = str(apdu.monitoredObjectIdentifier[0]) + "_" + str(
             apdu.monitoredObjectIdentifier[1])
         argumento = str(element.propertyIdentifier)
         if argumento in Dispositivos[deviceid][objecto]:
             Dispositivos[deviceid][objecto][argumento][
                 "valorActual"] = round(float(value), 1)
         else:
             pass
     if rsvp[0]:
         response = SimpleAckPDU(context=apdu)
     elif rsvp[1]:
         response = RejectPDU(reason=rsvp[1], context=apdu)
     elif rsvp[2]:
         response = AbortPDU(reason=rsvp[2], context=apdu)
     self.response(response)
def write(device, portObject, value):
    request_addr = device.getRequestAddress()
    obj_type = portObject.getType()
    obj_inst = portObject.getPortNum()
    prop_id = portObject.getProp()
    index = portObject.getIndex()
    priority = portObject.getPriority()

    try:
        #verify datatype
        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            raise ValueError, ": invalid property for object type"
        value = datatype(value)
        request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id)
        request.pduDestination = Address(request_addr)
        request.propertyValue = Any()
        request.propertyValue.cast_in(value)
        request.propertyArrayIndex = index
        request.priority = priority
        this_application.request(request)
        time.sleep(.1)
        returnVal = this_application._Application__response_value
    except:
        returnVal = "Error, unable to write"
    
    finally:
        return returnVal
Example #29
0
    def complete_request(self, iocb):
        if _debug: ReadPropertyApplication._debug("complete_request %r", iocb)

        if iocb.ioResponse:
            apdu = iocb.ioResponse

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

            # special case for array parts, others are managed by cast_out
            value = apdu.propertyValue.cast_out(datatype)
            if _debug: ReadPropertyApplication._debug("    - value: %r", value)

            sys.stdout.write(self.property_identifier + " = " + str(value) + '\n')
            if hasattr(value, 'debug_contents'):
                value.debug_contents(stream=sys.stdout)
            sys.stdout.flush()

        if iocb.ioError:
            if _debug: ReadPropertyApplication._debug("    - error: %r", iocb.ioError)

            # if it is an unknown property, just skip to the next one
            if getattr(iocb.ioError, 'errorCode', '') != 'unknownProperty':
                sys.stdout.write(self.property_identifier + "! " + str(iocb.ioError) + '\n')
                sys.stdout.flush()

        # fire off another request
        deferred(self.next_request)
Example #30
0
def decode_multiple_properties(read_access_results_list):
    decoded_properties = {}
    for result in read_access_results_list:
        # here is the object identifier
        objectIdentifier = result.objectIdentifier
        # now come the property values per object
        for element in result.listOfResults:
            # get the property and array index
            propertyIdentifier = element.propertyIdentifier
            propertyArrayIndex = element.propertyArrayIndex

            # here is the read result
            readResult = element.readResult

            # check for an error, but do nothing if one happened todo - should that be the case?
            if readResult.propertyAccessError is None:
                # here is the value
                propertyValue = readResult.propertyValue

                # find the datatype
                datatype = get_datatype(objectIdentifier[0], propertyIdentifier)
                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)

                decoded_properties[propertyIdentifier] = value
    return decoded_properties
Example #31
0
def write(device, portObject, value):
    request_addr = device.getRequestAddress()
    obj_type = portObject.getType()
    obj_inst = portObject.getPortNum()
    prop_id = portObject.getProp()
    index = portObject.getIndex()
    priority = portObject.getPriority()

    try:
        # verify datatype
        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            raise ValueError, ": invalid property for object type"
        value = datatype(value)
        request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id)
        request.pduDestination = Address(request_addr)
        request.propertyValue = Any()
        request.propertyValue.cast_in(value)
        request.propertyArrayIndex = index
        request.priority = priority
        this_application.request(request)
        time.sleep(0.1)
        returnVal = this_application._Application__response_value
    except:
        returnVal = "Error, unable to write"

    finally:
        return returnVal
Example #32
0
    def confirmation(self, apdu):
        if _debug:
            ReadRangeApplication._debug("confirmation %r", apdu)

        if isinstance(apdu, Error):
            sys.stdout.write("error: %s\n" % (apdu.errorCode,))
            sys.stdout.flush()

        elif isinstance(apdu, AbortPDU):
            apdu.debug_contents()

        elif (isinstance(self._request, ReadRangeRequest)) and (isinstance(apdu, ReadRangeACK)):
            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
            if _debug:
                ReadRangeApplication._debug("    - datatype: %r", datatype)
            if not datatype:
                raise TypeError, "unknown datatype"

            # cast out of the single Any element into the datatype
            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()
Example #33
0
    def confirmation(self, apdu):
        if _debug: ReadRangeApplication._debug("confirmation %r", apdu)

        if isinstance(apdu, Error):
            sys.stdout.write("error: %s\n" % (apdu.errorCode, ))
            sys.stdout.flush()

        elif isinstance(apdu, AbortPDU):
            apdu.debug_contents()

        elif (isinstance(self._request, ReadRangeRequest)) and (isinstance(
                apdu, ReadRangeACK)):
            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0],
                                    apdu.propertyIdentifier)
            if _debug:
                ReadRangeApplication._debug("    - datatype: %r", datatype)
            if not datatype:
                raise TypeError, "unknown datatype"

            # cast out of the single Any element into the datatype
            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()
Example #34
0
File: cov.py Project: snuids/BAC0
    def cov_notification(self, apdu):
        # make a rash assumption that the property value is going to be
        # a single application encoded tag
        source = apdu.pduSource
        object_changed = apdu.monitoredObjectIdentifier

        elements = {
            "source": source,
            "object_changed": object_changed,
            "properties": {},
        }
        for element in apdu.listOfValues:
            prop_id = element.propertyIdentifier
            datatype = get_datatype(object_changed[0], prop_id)
            value = element.value

            if not datatype:
                value = cast_datatype_from_tag(element.value,
                                               object_changed[0], prop_id)
            else:
                # special case for array parts, others are managed by cast_out
                if issubclass(datatype, Array) and (element.propertyArrayIndex
                                                    is not None):
                    if element.propertyArrayIndex == 0:
                        value = element.value.cast_out(Unsigned)
                    else:
                        value = element.value.cast_out(datatype.subtype)
                else:
                    value = element.value.cast_out(datatype)

            elements["properties"][prop_id] = value

        return elements
Example #35
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)
    def __write_value(self, config_obj_id: str, _value: float) -> None:
        try:
            # get config obj
            obj = self.__get_object(config_obj_id)
            obj_id = obj.get('object_id')
            obj_id = ObjectIdentifier(obj_id).value # make a bacpypes obj id
            addr = self.__get_device()
            prop_id = self.__get_prop()

            # write <addr> <objid> <prop> <value> 
            value = float(_value)
            self.logger.debug(f"write: {config_obj_id} {_value} for port \'{obj.get('name')}\' {str(obj_id)} {prop_id} {value}")

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

            # the value to write 
            datatype = get_datatype(obj_id[0], prop_id)
            value = datatype(value)
            request.propertyValue = Any()
            try:
                request.propertyValue.cast_in(value)
            except Exception as err:
                self.logger.critical(f"write: {err}")

            iocb = IOCB(request)
            self.app.request_io(iocb)
            self.logger.debug("write: waiting for response...")
            loopCount = 0
            while loopCount < 20 and not iocb.ioResponse:
                loopCount += 1
                run_once()
                asyncore.loop(timeout=0.2, count=1)
                time.sleep(0.2)
                self.logger.debug(f"write: loopy {loopCount}")
            stop()

            # do something for success
            if iocb.ioResponse:
                self.logger.debug(f"write: iocb response success!")

                apdu = iocb.ioResponse

                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    self.logger.error(f"write: Not an ACK")
                    return
                self.logger.debug(f"write: received ACK")

            # do something for error/reject/abort
            if iocb.ioError:
                self.logger.error(f"write: ioError {str(iocb.ioError)}")

        except Exception as err:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_tb(exc_traceback, file=sys.stdout)
            self.logger.critical(f"write: {err}")
Example #37
0
def create_ReadPropertyRequest(args):
    """
    Create a ReadPropertyRequest from a string
    """
    args = args.split()
    addr, obj_type, obj_inst, prop_id = args[:4]
    print(addr)

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

    obj_inst = int(obj_inst)

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

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

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

    return request
Example #38
0
def write_property(self,
                   target_address,
                   value,
                   object_type,
                   instance_number,
                   property_name,
                   priority=None,
                   index=None):
    """Write to a property."""

    request = WritePropertyRequest(objectIdentifier=(object_type,
                                                     instance_number),
                                   propertyIdentifier=property_name)

    datatype = get_datatype(object_type, property_name)
    if (value is None or value == 'null'):
        bac_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)
        bac_value = datatype(value)
    elif issubclass(datatype, Array) and (index is not None):
        if index == 0:
            bac_value = Integer(value)
        elif issubclass(datatype.subtype, Atomic):
            bac_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__, ))

    request.propertyValue = Any()
    request.propertyValue.cast_in(bac_value)

    request.pduDestination = Address(target_address)

    # Optional index
    if index is not None:
        request.propertyArrayIndex = index

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

    iocb = IOCB(request, AsyncCall())
    self.this_application.submit_request(iocb)
    result = iocb.ioResult.wait()
    if isinstance(result, SimpleAckPDU):
        return value
    raise RuntimeError("Failed to set value: " + str(result))


#k= write_property("2001:127", 1, "binaryOutput", 1, "presentValue", priority=None, index=None)
Example #39
0
    def write_property(self,
                       target_address,
                       value,
                       object_type,
                       instance_number,
                       property_name,
                       priority=None,
                       index=None):
        """Write to a property."""

        _log.debug(
            write_debug_str.format(target=target_address,
                                   type=object_type,
                                   instance=instance_number,
                                   property=property_name,
                                   priority=priority,
                                   index=index,
                                   value=value))

        request = WritePropertyRequest(objectIdentifier=(object_type,
                                                         instance_number),
                                       propertyIdentifier=property_name)

        datatype = get_datatype(object_type, property_name)
        if (value is None or value == 'null'):
            bac_value = Null()
        elif issubclass(datatype, Atomic):
            bac_value = self._cast_value(value, datatype)
        elif issubclass(datatype, Array) and (index is not None):
            if index == 0:
                bac_value = Integer(value)
            elif issubclass(datatype.subtype, Atomic):
                bac_value = datatype.subtype(value)
            elif not isinstance(value, datatype.subtype):
                raise TypeError("invalid result datatype, expecting {}".format(
                    datatype.subtype.__name__, ))
        elif not isinstance(value, datatype):
            raise TypeError("invalid result datatype, expecting %s".format(
                datatype.__name__, ))

        request.propertyValue = Any()
        request.propertyValue.cast_in(bac_value)

        request.pduDestination = Address(target_address)

        # Optional index
        if index is not None:
            request.propertyArrayIndex = index

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

        iocb = self.iocb_class(request)
        self.this_application.submit_request(iocb)
        result = iocb.ioResult.get(10)
        if isinstance(result, SimpleAckPDU):
            return value
        raise RuntimeError("Failed to set value: " + str(result))
    def confirmation(self, apdu):
        if _debug: ReadPropertyMultipleApplication._debug("confirmation %r", apdu)

        if isinstance(apdu, Error):
            sys.stdout.write("error: %s\n" % (apdu.errorCode,))
            sys.stdout.flush()

        elif isinstance(apdu, AbortPDU):
            apdu.debug_contents()

        elif (isinstance(self._request, ReadPropertyMultipleRequest)) and (isinstance(apdu, ReadPropertyMultipleACK)):
            # loop through the results
            for result in apdu.listOfReadAccessResults:
                # here is the object identifier
                objectIdentifier = result.objectIdentifier
                if _debug: ReadPropertyMultipleApplication._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: ReadPropertyMultipleApplication._debug("    - propertyIdentifier: %r", propertyIdentifier)
                    propertyArrayIndex = element.propertyArrayIndex
                    if _debug: ReadPropertyMultipleApplication._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: ReadPropertyMultipleApplication._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: ReadPropertyMultipleApplication._debug("    - value: %r", value)

                        sys.stdout.write(" = " + str(value) + '\n')
                    sys.stdout.flush()
Example #41
0
    def confirmation__read_property_multiple_ack(self, apdu):
        # loop through the results
        for result in apdu.listOfReadAccessResults:
            # here is the object identifier
            objectIdentifier = result.objectIdentifier
            if _debug:
                logger.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:
                    logger.debug("    - propertyIdentifier: %r",
                                 propertyIdentifier)
                propertyArrayIndex = element.propertyArrayIndex
                if _debug:
                    logger.debug("    - propertyArrayIndex: %r",
                                 propertyArrayIndex)

                # here is the read result
                readResult = element.readResult

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

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

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

                    # find the datatype
                    datatype = get_datatype(objectIdentifier[0],
                                            propertyIdentifier)
                    if _debug: logger.debug("    - datatype: %r", datatype)
                    if not datatype:
                        value = '?'
                    else:
                        # special case for array parts, others are managed by cast_out
                        if issubclass(datatype, Array) and (propertyArrayIndex
                                                            is not None):
                            if propertyArrayIndex == 0:
                                value = propertyValue.cast_out(Unsigned)
                            else:
                                value = propertyValue.cast_out(
                                    datatype.subtype)
                        else:
                            value = propertyValue.cast_out(datatype)
                        if _debug: logger.debug("    - value: %r", value)

                    sys.stdout.write(" = " + str(value) + '\n')
                sys.stdout.flush()
Example #42
0
File: api.py Project: hdqlife/blink
 def writeValue(self,addr,obj_id,prop_id,value,indx=None,priority=None):
     if isinstance(obj_id,str):
         obj_id=obj_id.split(':')
         obj_id[1]=int(obj_id[1])
     addr=RemoteStation(addr[0],bytearray(addr[1]))
     datatype = get_datatype(obj_id[0],prop_id)
     if datatype is None:return
     if (value == 'null'):
         value = Null()
     elif issubclass(datatype, AnyAtomic):
         dtype, dvalue = value.split(':', 1)
         datatype = {
             'b': Boolean,
             'u': lambda x: Unsigned(int(x)),
             'i': lambda x: Integer(int(x)),
             'r': lambda x: Real(float(x)),
             'd': lambda x: Double(float(x)),
             'o': OctetString,
             'c': CharacterString,
             'bs': BitString,
             'date': Date,
             'time': Time,
             'id': ObjectIdentifier,
             }[dtype]
         value = datatype(dvalue)
     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__,))
     # build a request
     request = WritePropertyRequest(
         objectIdentifier=tuple(obj_id),
         propertyIdentifier=prop_id,
         destination=addr
     )
     # save the value
     request.propertyValue = Any()
     request.propertyValue.cast_in(value)
     if indx is not None:
         request.propertyArrayIndex = indx
     if priority is not None:
         request.priority = priority
     iocb = IOCB(request)
     self.request_io(iocb)
Example #43
0
    def run(self):
        if _debug: ReadPointListThread._debug("run")
        global this_application

        # loop through the points
        for obj_id, prop_id in self.point_list:
            obj_id = ObjectIdentifier(obj_id).value

            # build a request
            request = ReadPropertyRequest(
                destination=self.device_address,
                objectIdentifier=obj_id,
                propertyIdentifier=prop_id,
            )
            if _debug: ReadPointListThread._debug("    - request: %r", request)

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

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

            # wait for the response
            iocb.wait()

            if iocb.ioResponse:
                apdu = iocb.ioResponse

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

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

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

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

        if _debug: ReadPointListThread._debug("    - fini")
    def _filter_present_value_from_results(self, results):
        """ Filter the results so that only presentValue datatypes are kept.

        The results of this function have an array of dictionaries.

        :param results: The results from a _read_props function.
        :return: An array of dictionaries.
        """
        # Currently our driver only deals with objects that have a
        # presentValue datatype.  This gives a list of dictionary's that
        # represent the individual lines in the config file (note not all of
        # the properties are currently present in the dictionary)
        presentValues = [dict(index=v[1], writable="FALSE",
                              datatype=get_datatype(v[0], 'presentValue'),
                              bacnet_type=v[0])
                         for k, v in results.items()
                         if get_datatype(v[0], 'presentValue')]
        return presentValues
Example #45
0
    def _filter_present_value_from_results(self, results):
        """ Filter the results so that only presentValue datatypes are kept.

        The results of this function have an array of dictionaries.

        :param results: The results from a _read_props function.
        :return: An array of dictionaries.
        """
        # Currently our driver only deals with objects that have a
        # presentValue datatype.  This gives a list of dictionary's that
        # represent the individual lines in the config file (note not all of
        # the properties are currently present in the dictionary)
        presentValues = [dict(index=v[1], writable="FALSE",
                              datatype=get_datatype(v[0], 'presentValue'),
                              bacnet_type=v[0])
                         for k, v in results.items()
                         if get_datatype(v[0], 'presentValue')]
        return presentValues
Example #46
0
 def write_property(self, target_address, value, object_type, instance_number, property_name, priority=None, index=None):
     """Write to a property."""
     
     _log.debug(write_debug_str.format(target=target_address,
                                       type=object_type,
                                       instance=instance_number,
                                       property=property_name,
                                       priority=priority,
                                       index=index,
                                       value=value))
     
     request = WritePropertyRequest(
         objectIdentifier=(object_type, instance_number),
         propertyIdentifier=property_name)
     
     datatype = get_datatype(object_type, property_name)
     if (value is None or value == 'null'):
         bac_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)
         bac_value = datatype(value)
     elif issubclass(datatype, Array) and (index is not None):
         if index == 0:
             bac_value = Integer(value)
         elif issubclass(datatype.subtype, Atomic):
             bac_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__,))
         
     request.propertyValue = Any()
     request.propertyValue.cast_in(bac_value)
         
     request.pduDestination = Address(target_address)
     
     #Optional index
     if index is not None:
         request.propertyArrayIndex = index
     
     #Optional priority
     if priority is not None:
         request.priority = priority
     
     iocb = self.iocb_class(request)
     self.this_application.submit_request(iocb)
     result = iocb.ioResult.wait()
     if isinstance(result, SimpleAckPDU):
         return value
     raise RuntimeError("Failed to set value: " + str(result))
    def run(self):
        if _debug: ReadPointListThread._debug("run")
        global this_application

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

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

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

            # wait for the response
            iocb.wait()

            if iocb.ioResponse:
                apdu = iocb.ioResponse

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

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

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

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

        # done
        stop()
Example #48
0
def read(device, portObject): 
    global this_application
    request_addr = device.getRequestAddress()    
    obj_type = portObject.getType()
    port = portObject.getPortNum()
    prop_id = portObject.getProp()
    maximumWait = 6  #seconds
    
    try: 

        #Jordan Trying to open thread in application

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

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

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

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

        if issubclass(datatype, Array) and apdu.propertyArrayIndex\
             is not None:
            if apdu.propertyArrayIndex == 0:
                value = apdu.propertyValue.cast_out(Unsigned)
            else:
                value = apdu.propertyValue.cast_out(datatype.subtype)
        else:
            value = apdu.propertyValue.cast_out(datatype)
        if(value=="inactive"):
            value=0.0
        if (value=="active"):
            value=1.0
        return value
def 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 _process_enumerated(self, object_type, obj):
        units = ''
        units_details = ''
        notes = ''

        units = 'Enum'
        present_value_type = get_datatype(object_type, 'presentValue')
        values = present_value_type.enumerations.values()
        min_value = min(values)
        max_value = max(values)

        vendor_range = ''
        if hasattr(present_value_type, 'vendor_range'):
            vendor_min, vendor_max = present_value_type.vendor_range
            vendor_range = ' (vendor {min}-{max})'.format(min=vendor_min,
                                                          max=vendor_max)

        units_details = '{min}-{max}{vendor}'.format(min=min_value,
                                                     max=max_value,
                                                     vendor=vendor_range)

        if not object_type.endswith('Input'):
            default_value = obj.get("relinquishDefault")
            if default_value:
                self._log.debug('DEFAULT VALUE IS: {}'.format(default_value))
                self._log.debug('ENUMERATION VALUES: {}'.format(
                    present_value_type.enumerations))
                for k, v in present_value_type.enumerations.items():
                    if v == default_value:
                        units_details += ' (default {default})'.format(
                            default=k)

        if not notes:
            enum_strings = []
            for name in Enumerated.keylist(present_value_type(0)):
                value = present_value_type.enumerations[name]
                enum_strings.append(str(value) + '=' + name)

            notes = present_value_type.__name__ + ': ' + ', '.join(
                enum_strings)

        return units, units_details, notes
Example #53
0
    def _get_value_from_read_property_request(self, apdu, working_iocb):
        # find the datatype
        datatype = get_datatype(apdu.objectIdentifier[0],
                                apdu.propertyIdentifier)
        if not datatype:
            working_iocb.set_exception(TypeError("unknown datatype"))
            return

        # 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 issubclass(datatype, Enumerated):
                value = datatype(value).get_long()
        return value
def write(obj_type, obj_inst, prop_id, value, index, priority):

	try:
		#verify datatype
		datatype = get_datatype(obj_type, prop_id)
		if not datatype:
			raise ValueError, ": invalid property for object type"
		value = datatype(value)
		request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id)
		request.pduDestination = Address(request_addr)
		request.propertyValue = Any()
		request.propertyValue.cast_in(value)
		request.propertyArrayIndex = index
		request.priority = priority
		this_application.request(request)
		time.sleep(.1)
		returnVal = this_application._Application__response_value
	except:
		returnVal = "Error, unable to write"

	finally:
		return returnVal
Example #55
0
def read_prop(app, address, obj_type, obj_inst, prop_id, index=None):
    request = ReadPropertyRequest(
        objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, propertyArrayIndex=index
    )
    request.pduDestination = address

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

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

    return value
                             'PNNL Point Name',
                             'Units',
                             'Unit Details',
                             'BACnet Object Type',
                             'Property',
                             'Writable',
                             'Index',
                             'Notes'))
 
 config_writer.writeheader()
 
 for obj_type, index in object_list.value[1:]:
     
     writable = 'FALSE'
     
     present_value_type = get_datatype(obj_type, 'presentValue')
     if present_value_type is None:
         continue
     
     if not issubclass(present_value_type, (Enumerated,
                                            Unsigned,
                                            Boolean,
                                            Integer,
                                            Real,
                                            Double)):
         continue 
     
     try:
         object_name = read_prop(this_application, target_address, obj_type, index, "objectName")
         _log.debug('object name = ' + object_name)
     except TypeError:
    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)
Example #58
0
    def confirmation(self, apdu):
        """
        This function process confirmed answers from the stack and looks for a returned 
        value or an error.
        If a valid value is found, it's stored in the ResponseQueue. We'll wait for the
        response to be used by the caller then resume the function.
        
        How we deal with the Queue::
            
            # Creation of an event
            evt = Event()
            # Store the value and the event in the Queue
            self.ResponseQueue.put((self.value, evt))
            # Wait until the event is set by the caller (read function for example)
            evt.wait()
            
        :param apdu: apdu
        """
        if _debug: ScriptApplication._debug("confirmation %r", apdu)
        if isinstance(apdu, Error):
            self.error = "%s" % (apdu.errorCode,)   

        elif isinstance(apdu, AbortPDU):
            pass

        if isinstance(apdu, SimpleAckPDU):
            evt = Event()
            self.ResponseQueue.put((self.value, evt))
            evt.wait()

        elif (isinstance(self._request, ReadPropertyRequest)) \
            and (isinstance(apdu, ReadPropertyACK)):

            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
            if _debug: ScriptApplication._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:
                    self.value = apdu.propertyValue.cast_out(Unsigned)
                else:
                    self.value = apdu.propertyValue.cast_out(datatype.subtype)
            else:
                self.value = apdu.propertyValue.cast_out(datatype)

            # Share data with script
            evt = Event()
            self.ResponseQueue.put((self.value, evt))
            evt.wait()

            if _debug: ScriptApplication._debug("    - value: %r", self.value)

        elif (isinstance(self._request, ReadPropertyMultipleRequest)) \
            and (isinstance(apdu, ReadPropertyMultipleACK)):

            # loop through the results
            for result in apdu.listOfReadAccessResults:
                # here is the object identifier
                objectIdentifier = result.objectIdentifier
                if _debug: ScriptApplication._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: ScriptApplication._debug("    - propertyIdentifier: %r", propertyIdentifier)
                    propertyArrayIndex = element.propertyArrayIndex
                    if _debug: ScriptApplication._debug("    - propertyArrayIndex: %r", propertyArrayIndex)

                    # here is the read result
                    readResult = element.readResult

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

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

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

                        # find the datatype
                        datatype = get_datatype(objectIdentifier[0], propertyIdentifier)
                        if _debug: ScriptApplication._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:
                                self.values.append(propertyValue.cast_out(Unsigned))
                            else:
                                self.values.append(propertyValue.cast_out(datatype.subtype))
                        else:
                            value = propertyValue.cast_out(datatype)
                        if _debug: ScriptApplication._debug("    - value: %r", value)
                        self.values.append(value)
            # Use a queue to store the response, wait for it to be used then resume
            evt = Event()
            self.ResponseQueue.put((self.values, evt))
            evt.wait()