示例#1
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 !!"
示例#2
0
    def do_save(self, args):
        """save <addr> <device instance>"""
        args = args.split()
        if _debug: SaveToFlashConsoleCmd._debug("do_save %r", args)

        try:
            addr, obj_inst = args[:2]

            # object type = 8 (device). property = 1151 (SaveToFlash)
            obj_type = 8
            obj_inst = int(obj_inst)
            prop_id = 1151

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

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

            # send an Enumerated value of 1 means SaveToFlash
            tag_list = TagList([ApplicationTag(9, xtob('01'))])
            if _debug:
                SaveToFlashConsoleCmd._debug("    - tag_list: %r", tag_list)

            # stuff the tag list into an Any
            request.propertyValue = Any()
            request.propertyValue.decode(tag_list)

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

            # make an IOCB
            iocb = IOCB(request)
            if _debug: SaveToFlashConsoleCmd._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:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug: SaveToFlashConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            SaveToFlashConsoleCmd._exception("exception: %r", error)
    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}")
示例#4
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
示例#5
0
文件: api.py 项目: 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)
示例#6
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))
示例#7
0
    def make_weeklySchedule_request(self, destination, object_instance,
                                    weeklySchedule):
        request = WritePropertyRequest(
            objectIdentifier=("schedule", object_instance),
            propertyIdentifier="weeklySchedule",
        )

        address = Address(destination)
        request.pduDestination = address
        request.propertyValue = Any()
        request.propertyValue.cast_in(weeklySchedule)
        request.priority = 15
        return request
示例#8
0
文件: Text.py 项目: snuids/BAC0
    def build_text_write_request(self,
                                 addr,
                                 obj_type,
                                 obj_inst,
                                 value,
                                 prop_id="description"):
        request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst),
                                       propertyIdentifier=prop_id)
        request.pduDestination = Address(addr)

        _value = Any()
        _value.cast_in(CharacterString(value))
        request.propertyValue = _value

        return request
示例#9
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 == '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)

            iocb = IOCB(request, self.async_call)
            self.this_application.submit_request(iocb)
            result = iocb.ioResult.wait()
            if isinstance(result, SimpleAckPDU):
                return value
            raise RuntimeError("Failed to set value: " + str(result))
示例#10
0
    def write_recipient_list(addr, obj_inst, recipent_list):
        if _debug:
            EventNotificationConsoleCmd._debug("write_recipient_list %r %r %r",
                                               addr, obj_inst, recipent_list)

        # the new list has just us
        recipient_list = ListOfDestination(recipent_list)
        if _debug:
            EventNotificationConsoleCmd._debug("    - recipient_list: %r",
                                               recipient_list)

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

        # save the value
        request.propertyValue.cast_in(recipient_list)
        if _debug:
            EventNotificationConsoleCmd._debug("    - request: %r", request)

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

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

        # wait for it to complete
        iocb.wait()

        # do something for success
        if iocb.ioResponse:
            # should be an ack
            if not isinstance(iocb.ioResponse, SimpleAckPDU):
                if _debug:
                    EventNotificationConsoleCmd._debug("    - not an ack")
                return

            sys.stdout.write("ack\n")

        # do something for error/reject/abort
        if iocb.ioError:
            sys.stdout.write(str(iocb.ioError) + '\n')
示例#11
0
    def write_bac_set(self):

        addr = point_list[0][0]
        obj_type = self.obj
        obj_inst = self.inst
        prop_id = self.prop

        tags = self.response_bacset[0]
        proxy_ip = self.proxyIP
        print tags
        print proxy_ip

        try:

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

            # build a custom datastructure... BACnet settings IP net or bcp
            tag_list = contextTagsToWrite.build_list(self.response_bacset,
                                                     proxy_ip)

            #if _debug: WriteSomethingConsoleCmd._debug("    - tag_list: %r", tag_list)

            # stuff the tag list into an Any
            request.propertyValue = Any()
            request.propertyValue.decode(tag_list)

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

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

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

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

        except Exception as error:
            #WriteSomethingConsoleCmd._exception("exception: %r", error)
            print error
示例#12
0
 def set_state_async(self, bac_app, address, value):
     if not self.read_only:   
         request = WritePropertyRequest(
             objectIdentifier=(self.object_type, self.instance_number),
             propertyIdentifier=self.property)
         # save the value
         if self.datatype is Integer:
             value = int(value)
         elif self.datatype is Real:
             value = float(value)
         bac_value = self.datatype(value)
         request.propertyValue = Any()
         request.propertyValue.cast_in(bac_value)
             
         request.pduDestination = address
         iocb = IOCB(request)
         bac_app.request(iocb)
         iocb.ioDefered.addCallback(self.set_state_async_callback, value)
         return iocb.ioDefered
     raise TypeError('This register is read only.')
示例#13
0
    def set_state_async(self, bac_app, address, value):
        if not self.read_only:
            request = WritePropertyRequest(
                objectIdentifier=(self.object_type, self.instance_number),
                propertyIdentifier=self.property)
            # save the value
            if self.datatype is Integer:
                value = int(value)
            elif self.datatype is Real:
                value = float(value)
            bac_value = self.datatype(value)
            request.propertyValue = Any()
            request.propertyValue.cast_in(bac_value)

            request.pduDestination = address
            iocb = IOCB(request)
            bac_app.request(iocb)
            iocb.ioDefered.addCallback(self.set_state_async_callback, value)
            return iocb.ioDefered
        raise TypeError('This register is read only.')
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
示例#15
0
文件: Write.py 项目: RachelErin/BAC0
    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
示例#16
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 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
示例#18
0
	def _do_write(self, objtype, objinst, propname, new_val):
		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"

			print 'new val:' + str(new_val)
			prop_val = Any(Real(float(new_val)))
			#prop_val.cast_in()

			# build a request
			request = WritePropertyRequest(
				objectIdentifier=(obj_type, obj_inst),
				propertyIdentifier=prop_id,
				propertyValue=prop_val
				)
			request.pduDestination = Address(addr)
			if self._debug: print("writing")

			#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)
示例#19
0
    def process_task(self):
        if _debug:
            PrairieDog._debug("process_task")
        global args, this_application

        if _debug:
            PrairieDog._debug("    - args.values: %r", args.values)

        # pick up the next value
        value = args.values.pop(0)
        args.values.append(value)

        # make a primitive value out of it
        value = Real(float(value))

        # build a request
        request = WritePropertyRequest(
            destination=args.daddr,
            objectIdentifier=args.objid,
            propertyIdentifier=args.propid,
        )

        # save the value, application tagged
        request.propertyValue = Any()
        request.propertyValue.cast_in(value)
        if _debug:
            PrairieDog._debug("    - request: %r", request)

        # make an IOCB
        iocb = IOCB(request)
        iocb.add_callback(self.write_complete)
        if _debug:
            PrairieDog._debug("    - iocb: %r", iocb)

        # give it to the application to process
        deferred(this_application.request_io, iocb)
 def form_iocb(device, config=None, request_type="readProperty"):
     config = config if config is not None else device
     address = device["address"] if isinstance(device["address"], Address) else Address(device["address"])
     object_id = ObjectIdentifier(config["objectId"])
     property_id = config.get("propertyId")
     value = config.get("propertyValue")
     property_index = config.get("propertyIndex")
     priority = config.get("priority")
     vendor = device.get("vendor", config.get("vendorId", 0))
     request = None
     iocb = None
     if request_type == "readProperty":
         try:
             request = ReadPropertyRequest(
                 objectIdentifier=object_id,
                 propertyIdentifier=property_id
             )
             request.pduDestination = address
             if property_index is not None:
                 request.propertyArrayIndex = int(property_index)
             iocb = IOCB(request)
         except Exception as e:
             log.exception(e)
     elif request_type == "writeProperty":
         datatype = get_datatype(object_id.value[0], property_id, vendor)
         if (isinstance(value, str) and value.lower() == 'null') or value is None:
             value = Null()
         request = WritePropertyRequest(
             objectIdentifier=object_id,
             propertyIdentifier=property_id
         )
         request.pduDestination = address
         request.propertyValue = Any()
         try:
             value = datatype(value)
             request.propertyValue = Any(value)
         except AttributeError as e:
             log.debug(e)
         except Exception as error:
             log.exception("WriteProperty cast error: %r", error)
         if property_index is not None:
             request.propertyArrayIndex = property_index
         if priority is not None:
             request.priority = priority
         iocb = IOCB(request)
     else:
         log.error("Request type is not found or not implemented")
     return iocb
示例#21
0
    def write_property(self, target_address, value, object_type, instance_number, property_name, priority=None, index=None):
        """Write to a property."""
        # target_address = IP or network address of device
        # setvalue = the value you want to set to
        # object_type =  protocol related object type: eg: Analog Input (AI), Analog Output etc
        # instance_number = the interger id of the property you want to change (brightness, state etc)
        # property = always set to "presentValue"
        # priority =  the priority of your settings. Higher priority settings takes over

        request = WritePropertyRequest(
            objectIdentifier=(object_type, instance_number),
            propertyIdentifier=property_name)
        
        datatype = get_datatype(object_type, property_name)
        bac_value = Null()
        if 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, self.async_call)
        self.this_application.submit_request(iocb)
        result = iocb.ioResult.wait()
        if isinstance(result, SimpleAckPDU):
            return value
        raise RuntimeError("Failed to set value: " + str(result))
示例#22
0
    def confirmation(self, pdu):
        if _debug: WritePropertyClient._debug('confirmation %r', pdu)
        global this_application

        # decode the bytes into a string and strip off the end-of-line
        args = pdu.pduData.decode('utf-8').strip().split()
        if _debug: WritePropertyClient._debug("    - args: %r", args)

        try:
            addr, obj_type, obj_inst, prop_id = args[:4]
            if obj_type.isdigit():
                obj_type = int(obj_type)
            obj_inst = int(obj_inst)
            value = args[4]

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

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

            # get the datatype
            datatype = get_datatype(obj_type, prop_id)
            if _debug: WritePropertyClient._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: WritePropertyClient._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 as error:
                WritePropertyClient._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: WritePropertyClient._debug("    - request: %r", request)

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

            # reference the original request so the response goes back to the
            # correct client
            iocb.request_pdu = pdu

            # add ourselves to be called back for the response
            iocb.add_callback(self.complete)

            # give it to the application
            this_application.request_io(iocb)
        except Exception as error:
            WritePropertyClient._exception("exception: %r", error)

            # send it back to the client
            error_str = "exception: " + str(error) + '\r\n'
            self.request(PDU(error_str.encode('utf-8'), destination=pdu.pduSource))
    def do_write(self, args):
        """
        write <indx> <value>
        write 0 <len>
        write [ <value> ]...
        """
        args = args.split()
        ReadWritePropertyConsoleCmd._debug("do_write %r", args)

        try:
            addr, obj_type, obj_inst = context
            prop_id = 'eventMessageTexts'

            indx = None
            if args and args[0].isdigit():
                indx = int(args[0])
                if indx == 0:
                    value = Unsigned(int(args[1]))
                else:
                    value = CharacterString(args[1])
            else:
                value = ArrayOf(CharacterString)(args[0:])

            # 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 as error:
                ReadWritePropertyConsoleCmd._exception(
                    "WriteProperty cast error: %r", error)

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

            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:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug:
                        ReadWritePropertyConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            ReadWritePropertyConsoleCmd._exception("exception: %r", error)
示例#24
0
    def do_write(self, args):
        """write <addr> <type>:<inst> <prop> <value> [ <indx> ] [ <priority> ]"""
        args = args.split()
        BacnetClientConsoleCmd._debug("do_write %r", args)

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

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

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

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

            # change atomic values into something encodeable, null is a special case
            if (value == 'null'):
                value = Null()
            elif issubclass(datatype, AnyAtomic):
                dtype, dvalue = value.split(':', 1)
                if _debug:
                    BacnetClientConsoleCmd._debug(
                        "    - dtype, dvalue: %r, %r", dtype, dvalue)

                datatype = {
                    'b': Boolean,
                    'u': lambda x: Unsigned(int(x)),
                    'i': lambda x: Integer(int(x)),
                    'r': lambda x: Real(float(x)),
                    'd': lambda x: Double(float(x)),
                    'o': OctetString,
                    'c': CharacterString,
                    'bs': BitString,
                    'date': Date,
                    'time': Time,
                    'id': ObjectIdentifier,
                }[dtype]
                if _debug:
                    BacnetClientConsoleCmd._debug("    - datatype: %r",
                                                  datatype)

                value = datatype(dvalue)
                if _debug:
                    BacnetClientConsoleCmd._debug("    - value: %r", value)

            elif issubclass(datatype, Atomic):
                if datatype is Integer:
                    value = int(value)
                elif datatype is Real:
                    value = float(value)
                elif datatype is Unsigned:
                    value = int(value)
                value = datatype(value)
            elif issubclass(datatype, Array) and (indx is not None):
                if indx == 0:
                    value = Integer(value)
                elif issubclass(datatype.subtype, Atomic):
                    value = datatype.subtype(value)
                elif not isinstance(value, datatype.subtype):
                    raise TypeError("invalid result datatype, expecting %s" %
                                    (datatype.subtype.__name__, ))
            elif not isinstance(value, datatype):
                raise TypeError("invalid result datatype, expecting %s" %
                                (datatype.__name__, ))
            if _debug:
                BacnetClientConsoleCmd._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:
                BacnetClientConsoleCmd._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:
                BacnetClientConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: BacnetClientConsoleCmd._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:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug:
                        BacnetClientConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            BacnetClientConsoleCmd._exception("exception: %r", error)
    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)
示例#26
0
    def do_write(self, args):
        """write <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: WriteSomethingConsoleCmd._debug("do_write %r", args)

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

            obj_type = int(obj_type)
            obj_inst = int(obj_inst)
            prop_id = int(prop_id)

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

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

            # build a custom datastructure
            tag_list = TagList([
                OpeningTag(1),
                ContextTag(0, xtob('9c40')),
                ContextTag(1, xtob('02')),
                ContextTag(2, xtob('02')),
                ClosingTag(1)
                ])
            if _debug: WriteSomethingConsoleCmd._debug("    - tag_list: %r", tag_list)

            # stuff the tag list into an Any
            request.propertyValue = Any()
            request.propertyValue.decode(tag_list)

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

            # make an IOCB
            iocb = IOCB(request)
            if _debug: WriteSomethingConsoleCmd._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:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug: WriteSomethingConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            WriteSomethingConsoleCmd._exception("exception: %r", error)
示例#27
0
    def build_wp_request(self, args, vendor_id=0):
        addr, obj_type, obj_inst, prop_id = args[:4]
        vendor_id = vendor_id
        if obj_type.isdigit():
            obj_type = int(obj_type)
        obj_inst = int(obj_inst)
        value = args[4]

        indx = None
        if len(args) >= 6:
            if args[5] != "-":
                indx = int(args[5])

        priority = None
        if len(args) >= 7:
            priority = int(args[6])

        # get the datatype
        if prop_id.isdigit():
            prop_id = int(prop_id)
        datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id)

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

        # 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 {}".format(
                        (datatype.subtype.__name__,)
                    )
                )

        elif not isinstance(value, datatype):
            raise TypeError(
                "invalid result datatype, expecting {}".format((datatype.__name__,))
            )
        self._log.debug("{:<20} {!r} {}".format("Encodeable value", 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 WritePropertyCastError as error:
            self._log.error("WriteProperty cast error: {!r}".format(error))

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

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

        self._log.debug("{:<20} {}".format("REQUEST", request))
        return request
示例#28
0
def create_WritePropertyRequest(args):
    """
    Create a WritePropertyRequest from a string
    """
    args = args.split()

    addr, obj_type, obj_inst, prop_id = args[:4]
    if obj_type.isdigit():
        obj_type = int(obj_type)
    obj_inst = int(obj_inst)
    value = args[4]

    indx = None
    if len(args) >= 6:
        if args[5] != "-":
            indx = int(args[5])

    priority = None
    if len(args) >= 7:
        priority = int(args[6])

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

    # 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__, ))

    # 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 WritePropertyCastError as error:
        raise ValueError("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
    return request
示例#29
0
    def write(self, obj_type, obj_inst, prop_id, address, value):
        n = ""
        datatype = get_datatype(obj_type, prop_id)
        if not datatype:
            return "error invalid property %s for object type %s" % (
                prop_id, object_type)

        # set a priority
        priority = 1  #o.get('priority') if o.get('priority') else 1

        # TODO: How do we handle an index? This is a 'parameterized set' case
        indx = None

        # 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):
                return "error invalid result datatype, expecting %s" % (
                    datatype.subtype.__name__, )
        elif not isinstance(value, datatype):
            return "error invalid result datatype, expecting %s" % (
                datatype.subtype.__name__, )

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

        # save the value
        request.propertyValue = Any()
        try:
            request.propertyValue.cast_in(value)
        except e as Exception:
            return "error write property 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

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

        # give it to the application to send
        _ss.this_application.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):
            return "error set operation failed %s %s %s" % (
                obj_inst, prop_id, str(iocb.ioResponse))

        print("wrote %s %s %s %s" % (address, obj_inst, prop_id, value))

        return n
示例#30
0
    def do_write(self, args):
        """write <addr> <objid> <prop> <operation> [ ... ]"""
        args = args.split()
        if _debug:
            WriteLightingConsoleCmd._debug("do_write %r", args)

        try:
            addr = args.pop(0)
            obj_id = ObjectIdentifier(args.pop(0)).value
            prop_id = args.pop(0)

            if obj_id[0] != "lightingOutput":
                raise ValueError("lightingOutput")
            if prop_id != "lightingCommand":
                raise ValueError("lightingCommand")
            if not args:
                raise ValueError("operation required")

            value = LightingCommand()
            value.operation = operation = args.pop(0)

            if operation == "fadeTo":
                if not args:
                    raise ValueError("target level required")
                value.targetLevel = float(args.pop(0))

                if args:
                    value.priority = int(args.pop(0))
                if args:
                    value.fadeTime = int(args.pop(0))

            elif operation == "rampTo":
                if not args:
                    raise ValueError("target level required")
                value.targetLevel = float(args.pop(0))

                if args:
                    value.priority = int(args.pop(0))
                if args:
                    value.rampRate = float(args.pop(0))

            elif operation == "stepUp":
                if args:
                    value.priority = int(args.pop(0))
                if args:
                    value.stepIncrement = float(args.pop(0))

            elif operation == "stepDown":
                if args:
                    value.priority = int(args.pop(0))
                if args:
                    value.stepIncrement = float(args.pop(0))

            elif operation == "stepOn":
                if args:
                    value.priority = int(args.pop(0))
                if args:
                    value.stepIncrement = float(args.pop(0))

            elif operation == "stepOff":
                if args:
                    value.priority = int(args.pop(0))
                if args:
                    value.stepIncrement = float(args.pop(0))

            elif operation == "warn":
                if args:
                    value.priority = int(args.pop(0))

            elif operation == "warnOff":
                if args:
                    value.priority = int(args.pop(0))

            elif operation == "warnRelinquish":
                if args:
                    value.priority = int(args.pop(0))

            elif operation == "stop":
                if args:
                    value.priority = int(args.pop(0))

            else:
                raise ValueError("invalid operation")

            if (value.targetLevel
                    is not None) and not (0.0 <= value.targetLevel <= 100.0):
                raise ValueError("invalid target level (0.0..100.0)")
            if (value.rampRate
                    is not None) and not (0.0 <= value.rampRate <= 100.0):
                raise ValueError("invalid ramp rate (0.0..100.0)")
            if (value.stepIncrement
                    is not None) and not (0.1 <= value.stepIncrement <= 100.0):
                raise ValueError("invalid step increment (0.1..100.0)")
            if (value.fadeTime
                    is not None) and not (100 <= value.fadeTime <= 86400000):
                raise ValueError("invalid fade time (100..86400000)")
            if (value.priority
                    is not None) and not (1 <= value.priority <= 16):
                raise ValueError("invalid priority (1..16)")

            if _debug:
                WriteLightingConsoleCmd._debug("    - value: %r", 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:
                WriteLightingConsoleCmd._exception(
                    "WriteProperty cast error: %r", error)
            if _debug:
                WriteLightingConsoleCmd._debug("    - request: %r", request)

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

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

            # wait for it to complete
            iocb.wait()

            # do something for success
            if iocb.ioResponse:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug:
                        WriteLightingConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            WriteLightingConsoleCmd._exception("exception: %r", error)
示例#31
0
    def run(self):
        if _debug: WritePointListThread._debug("run")
        global this_application
        prop_id = "presentValue"
        # loop through the points

        print("points in thread :", self.point_list)
        for obj_type, obj_inst, value in self.point_list:

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

            # build a request
            # change atomic values into something encodeable, null is a special case
            if (value == 'null'):
                value = Null()
            elif issubclass(datatype, AnyAtomic):
                dtype, dvalue = value.split(':')
                if _debug:
                    ReadWritePropertyConsoleCmd._debug(
                        "	   - dtype, dvalue: %r, %r", dtype, dvalue)

                datatype = {
                    'b': Boolean,
                    'u': lambda x: Unsigned(int(x)),
                    'i': lambda x: Integer(int(x)),
                    'r': lambda x: Real(float(x)),
                    'd': lambda x: Double(float(x)),
                    'o': OctetString,
                    'c': CharacterString,
                    'bs': BitString,
                    'date': Date,
                    'time': Time,
                }[dtype]
                if _debug:
                    ReadWritePropertyConsoleCmd._debug("	   - datatype: %r",
                                                       datatype)

                value = datatype(dvalue)
                if _debug:
                    ReadWritePropertyConsoleCmd._debug("	   - value: %r",
                                                       value)

            elif issubclass(datatype, Atomic):
                if datatype is Integer:
                    value = int(value)
                elif datatype is Real:
                    value = float(value)
                elif datatype is Unsigned:
                    value = int(value)
                value = datatype(value)
            elif issubclass(datatype, Array) and (indx is not None):
                if indx == 0:
                    value = Integer(value)
                elif issubclass(datatype.subtype, Atomic):
                    value = datatype.subtype(value)
                elif not isinstance(value, datatype.subtype):
                    raise TypeError("invalid result datatype, expecting %s" %
                                    (datatype.subtype.__name__, ))
            elif not isinstance(value, datatype):
                raise TypeError("invalid result datatype, expecting %s" %
                                (datatype.__name__, ))
            if _debug:
                ReadWritePropertyConsoleCmd._debug(
                    "	   - encodeable value: %r %s", value, type(value))

            # build a request
            request = WritePropertyRequest(destination=self.device_address,
                                           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 as error:
                ReadWritePropertyConsoleCmd._exception(
                    "WriteProperty cast error: %r", error)

            # optional array index

            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:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug:
                        ReadWritePropertyConsoleCmd._debug("	   - not an ack")
                    return

                print(obj_inst, "ack\n")

            # do something for error/reject/abort
            if iocb.ioError:
                print(obj_inst, str(iocb.ioError))

            if _debug: ReadPointListThread._debug("	   - fini")
示例#32
0
    def do_write(self, args):
        """write <addr> <objid> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: WriteSomethingConsoleCmd._debug("do_write %r", args)

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

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

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

            # build a custom datastructure
            tag_list = TagList([
                OpeningTag(1),
                ContextTag(0, xtob('9c40')),
                ContextTag(1, xtob('02')),
                ContextTag(2, xtob('02')),
                ClosingTag(1)
            ])
            if _debug:
                WriteSomethingConsoleCmd._debug("    - tag_list: %r", tag_list)

            # stuff the tag list into an Any
            request.propertyValue = Any()
            request.propertyValue.decode(tag_list)

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

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

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

            # wait for it to complete
            iocb.wait()

            # do something for success
            if iocb.ioResponse:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug:
                        WriteSomethingConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            WriteSomethingConsoleCmd._exception("exception: %r", error)
示例#33
0
    def do_write(self, args):
        """write <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]"""
        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)
            obj_inst = int(obj_inst)
            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)
            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)
示例#34
0
文件: Write.py 项目: duck-hunt/BAC0
    def build_wp_request(self, args):
        addr, obj_type, obj_inst, prop_id = args[:4]
        if obj_type.isdigit():
            obj_type = int(obj_type)
        obj_inst = int(obj_inst)
        value = args[4]

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

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

        # get the datatype
        datatype = get_datatype(obj_type, prop_id)
        log_debug(WriteProperty, "    - 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__,))
        log_debug(
            WriteProperty,
            "    - 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 WritePropertyCastError as error:
            log_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

        log_debug(WriteProperty, "    - request: %r", request)
        return request
    def do_write(self, device_id, object_type, object_instance, prop_id, value, \
                 prop_type='invalid prop_type', indx=None, priority=None):
        """ do_write( <object id>, <type>, <instance>, <property_id>, <value>,
                      <optional property type>, <optional index>, <optional priority> )
            write a property to a specific object.
            return Nothing if successful, else Raise an exception which can be logged.
        """
        addrlist = device_id["mac"]  #4 bytes of address, 2 bytes of port
        if len(addrlist) != 6:
            raise IOError('invalid address')
        addr = ".".join(str(x)
                        for x in addrlist[:4]) + ":" + str((addrlist[4] << 8) +
                                                           addrlist[5])

        obj_id = str(object_type) + ":" + str(object_instance)
        obj_id = ObjectIdentifier(obj_id).value
        datatype = get_datatype(obj_id[0], prop_id)

        # change atomic values into something encodeable, null is a special case
        if value == 'null':
            value = Null()
        elif issubclass(datatype, AnyAtomic):
            datatype = self.datatype_map[prop_type]
            value = datatype(value)  # based on prop type build a value

        elif issubclass(datatype, Atomic):
            if datatype is Integer:
                value = int(value)
            elif datatype is Real:
                value = float(value)
            elif datatype is Unsigned:
                value = int(value)
            value = datatype(value)

        elif issubclass(datatype, Array):
            if indx is None:
                raise Exception("Index field missing")
            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 request & save the value
        request = WritePropertyRequest(objectIdentifier=obj_id,
                                       propertyIdentifier=prop_id)
        request.pduDestination = Address(addr)

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

        if indx is not None:
            request.propertyArrayIndex = indx

        if priority is not None:
            request.priority = priority

        # make an IOCB
        iocb = IOCB(request)
        self.request_io(iocb)
        iocb.set_timeout(3)
        iocb.wait()

        if iocb.ioResponse:
            if not isinstance(iocb.ioResponse, SimpleAckPDU):
                raise Exception("Response Not an ACK")

            return  # write success

        if iocb.ioError:
            raise Exception("ioError: %s" + str(iocb.ioError))

        raise Exception("do_write failed")
示例#36
0
    def do_write(self, args):
        """write <addr> <type> <inst> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: WriteSomethingConsoleCmd._debug("do_write %r", args)

        try:
            addr = args[0]

            obj_type = 162  #int(obj_type)
            obj_inst = 1  #int(obj_inst)
            prop_id = 1034  #int(prop_id)
            idx = 2

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

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

            request.propertyArrayIndex = idx

            if len(args) == 6:
                #convert ip to byte array and then to hex string
                proxy = bytearray(args[5])
                proxy_hex = str(proxy).encode('hex')

            # build a custom data structure... BACnet settings BCP object IP BBMD Foreign port eTCH 3.40
            # Context #0 inside Opening tag #9 is the IP Type 00=Regular, 01=Foreign, 02=BBMD
            # Context #2 inside Opening tag #9 is the Foreign IP in hex
            # Context #4 inside Opening tag #9 is the Proxy IP in hex
            tag_list = TagList([
                OpeningTag(0),
                ContextTag(0, xtob('19')),
                ContextTag(1, xtob('01')),
                ClosingTag(0),
                ContextTag(1, xtob('01')),
                ContextTag(2, xtob('00')),
                ContextTag(3, xtob('9c40')),
                ContextTag(4, xtob('00')),
                OpeningTag(5),
                ContextTag(0, xtob('00')),
                ContextTag(1, xtob('00')),
                ClosingTag(5),
                ContextTag(6, xtob('00')),
                ContextTag(7, xtob('00')),
                OpeningTag(8),
                ContextTag(0, xtob('00')),
                ContextTag(1, xtob('00')),
                ContextTag(2, xtob('00')),
                ContextTag(3, xtob('00')),
                ContextTag(4, xtob('00')),
                ContextTag(5, xtob('00')),
                ContextTag(6, xtob('00')),
                ContextTag(7, xtob('00')),
                ContextTag(8, xtob('ffffffff')),
                ClosingTag(8),
                OpeningTag(9),
                ContextTag(0, xtob('02')),
                ContextTag(1, xtob('bac0')),
                ContextTag(2, xtob('00')),
                ContextTag(3, xtob('3c')),
                ContextTag(4, xtob('480c600c')),
                ContextTag(5, xtob('00')),
                ContextTag(6, xtob('ffffffff')),
                ClosingTag(9),
                ContextTag(10, xtob('00')),
                ContextTag(11, xtob('00')),
                ContextTag(12, xtob('00')),
                ContextTag(13, xtob('00000000'))
            ])
            if _debug:
                WriteSomethingConsoleCmd._debug("    - tag_list: %r", tag_list)

            # stuff the tag list into an Any
            request.propertyValue = Any()
            request.propertyValue.decode(tag_list)

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

            # make an IOCB
            iocb = IOCB(request)
            if _debug: WriteSomethingConsoleCmd._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:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug:
                        WriteSomethingConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            WriteSomethingConsoleCmd._exception("exception: %r", error)
示例#37
0
文件: Write.py 项目: farzamhm/BAC0
    def build_wp_request(self, args, vendor_id=0):
        addr, obj_type, obj_inst, prop_id = args[:4]
        vendor_id = vendor_id
        if obj_type.isdigit():
            obj_type = int(obj_type)
        obj_inst = int(obj_inst)
        value = args[4]

        indx = None
        if len(args) >= 6:
            if args[5] != "-":
                indx = int(args[5])

        priority = None
        if len(args) >= 7:
            priority = int(args[6])

        # get the datatype
        if prop_id.isdigit():
            prop_id = int(prop_id)
        datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id)

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

        # 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 {}".format(
                    (datatype.subtype.__name__, )))

        elif not isinstance(value, datatype):
            raise TypeError("invalid result datatype, expecting {}".format(
                (datatype.__name__, )))
        self._log.debug("{:<20} {!r} {}".format("Encodeable value", 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 WritePropertyCastError as error:
            self._log.error("WriteProperty cast error: {!r}".format(error))

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

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

        self._log.debug("{:<20} {}".format("REQUEST", request))
        return request
示例#38
0
    def write(self, args):
        """ This function build a write request wait for an acknowledgment and 
        return a boolean status (True if ok, False if not)
        
        :param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]
        :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.write('2:5 analogValue 1 presentValue 100')
        
        will write 100 to AV:1 of a controller with a MAC address of 5 in the network 2
        """
        if not self._started: raise Exception('App not running, use startApp() function')
        args = args.split()
        print_debug("do_write %r", args)

        try:
            addr, obj_type, obj_inst, prop_id = args[:4]
            if obj_type.isdigit():
                obj_type = int(obj_type)
            obj_inst = int(obj_inst)
            value = args[4]

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

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

            # get the datatype
            datatype = get_datatype(obj_type, prop_id)
            print_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__,))
            print_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 WritePropertyCastError as error:
                WriteProperty._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

            print_debug("    - request: %r", request)

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

        except WritePropertyException as error:
            WriteProperty._exception("exception: %r", error)

        while True:
            try:
                data, evt = self.this_application.ResponseQueue.get(timeout=self._TIMEOUT)
                evt.set()
                return data
            except Empty:
                raise NoResponseFromController
                return None
    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)
示例#40
0
    def do_write(self, args):
        """write <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]"""
        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)
            obj_inst = int(obj_inst)
            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)
            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 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
            this_application.request_io(iocb)

            # wait for it to complete
            iocb.wait()

            # do something for success
            if iocb.ioResponse:
                # should be an ack
                if not isinstance(iocb.ioResponse, SimpleAckPDU):
                    if _debug: ReadWritePropertyConsoleCmd._debug("    - not an ack")
                    return

                sys.stdout.write("ack\n")

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

        except Exception as error:
            ReadWritePropertyConsoleCmd._exception("exception: %r", error)