예제 #1
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
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
예제 #3
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
예제 #4
0
def write_property(self,
                   target_address,
                   value,
                   object_type,
                   instance_number,
                   property_name,
                   priority=None,
                   index=None):
    """Write to a property."""

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

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

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

    request.pduDestination = Address(target_address)

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

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

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


#k= write_property("2001:127", 1, "binaryOutput", 1, "presentValue", priority=None, index=None)
예제 #5
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))
예제 #6
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)
예제 #7
0
파일: agent.py 프로젝트: carlatpnl/volttron
 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))
예제 #8
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))
예제 #9
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
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
예제 #11
0
    def run(self):
        while True:
            try:
                TagsUpdated = self.smonitor.Pull()
                while (len(TagsUpdated) > 0):
                    Tag = TagsUpdated.pop()
                    for idx in RELACIONAL:
                        if Tag.name == RELACIONAL[idx]["NOME"]:
                            if Dispositivos[RELACIONAL[idx]["ID"]][
                                    RELACIONAL[idx]["OBJ"]][RELACIONAL[idx][
                                        "ARG"]]["escrita"] == True:
                                #print Tag.name, round(Tag.value, 2)
                                try:
                                    addr = Dispositivos[RELACIONAL[idx]
                                                        ["ID"]]["IPort"]
                                    obj_type = RELACIONAL[idx]["OBJ"].split(
                                        "_", 1)[0]
                                    obj_inst = int(
                                        RELACIONAL[idx]["OBJ"].split("_",
                                                                     1)[1])
                                    prop_id = RELACIONAL[idx]["ARG"]
                                    #value = int(round(Tag.value, 0))
                                    value = round(Tag.value, 2)
                                    Dispositivos[RELACIONAL[idx]["ID"]][
                                        RELACIONAL[idx]["OBJ"]][RELACIONAL[
                                            idx]["ARG"]]["valorActual"] = value
                                    indx = None
                                    priority = None
                                    datatype = get_datatype(obj_type, prop_id)
                                    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):
                                            break
                                            #raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__,))
                                    elif not isinstance(value, datatype):
                                        break
                                        #raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__,))
                                    request = WritePropertyRequest(
                                        objectIdentifier=(obj_type, obj_inst),
                                        propertyIdentifier=prop_id)
                                    request.pduDestination = Address(addr)
                                    request.propertyValue = Any()
                                    try:
                                        request.propertyValue.cast_in(value)
                                    except Exception as error:
                                        break
                                        #print("WriteProperty cast error: %r", error)
                                    if indx is not None:
                                        request.propertyArrayIndex = indx
                                    if priority is not None:
                                        request.priority = priority
                                    iocb = IOCB(request)
                                    this_application.queue_by_address.clear()
                                    this_application.request_io(iocb)
                                    iocb.wait(1)
                                    if iocb.ioResponse:
                                        if not isinstance(
                                                iocb.ioResponse, SimpleAckPDU):
                                            with open("ErrorLog.txt",
                                                      "a") as myfile:
                                                myfile.write(
                                                    str(
                                                        time.strftime(
                                                            "%d-%m-%Y %H:%M:%S"
                                                        )) +
                                                    "Did not received ACK for "
                                                    + str(addr) + " " +
                                                    str(obj_type) + " " +
                                                    str(obj_inst) + " " +
                                                    str(prop_id) + " " +
                                                    str(value))
                                        else:
                                            pass
                                            #print "ACK"
                                    if iocb.ioError:
                                        with open("ErrorLog.txt",
                                                  "a") as myfile:
                                            myfile.write(
                                                str(
                                                    time.strftime(
                                                        "%d-%m-%Y %H:%M:%S")) +
                                                " Error on response to " +
                                                str(addr) + " " +
                                                str(obj_type) + " " +
                                                str(obj_inst) + " " +
                                                str(prop_id) + " " +
                                                str(value))
                                except Exception as e:
                                    with open("ErrorLog.txt", "a") as myfile:
                                        myfile.write(
                                            str(
                                                time.strftime(
                                                    "%d-%m-%Y %H:%M:%S")) +
                                            " Failed to write parameter.\n")
                                        myfile.write("Error -> " + str(e) +
                                                     "\n")
                                    pass  #tenta processar a escrita, se nao conseguir ignora
                            else:
                                pass  # se a flag de escrita, nao for verdadeira, nao interessa
                            pass
                        else:
                            pass  # se nao constar no dicionario de relacoes, nao interessa

                for idx in xrange(0, len(SMTags)):
                    if SMTags[idx].name == RELACIONAL[idx]["NOME"]:
                        SMTags[idx].value = Dispositivos[
                            RELACIONAL[idx]["ID"]][RELACIONAL[idx]["OBJ"]][
                                RELACIONAL[idx]["ARG"]]["valorActual"]
                self.smonitor.Push()
            except Exception as e:
                with open("ErrorLog.txt", "a") as myfile:
                    myfile.write(
                        str(time.strftime("%d-%m-%Y %H:%M:%S")) +
                        " Failed to Pull/Push data to SMonitor.\n")
                    myfile.write("Error -> " + str(e) + "\n")
            time.sleep(TimeSMonitor)
예제 #12
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)
예제 #13
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
예제 #14
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)
예제 #15
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))
예제 #16
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
예제 #17
0
    def do_write(self, args):
        """write <addr> <objid> <prop> <value> [ <indx> ] [ <priority> ]"""
        args = args.split()
        ReadWritePropertyConsoleCmd._debug("do_write %r", args)

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

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

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

            value = args[3]

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

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

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

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

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

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

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

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

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

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

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

            # wait for it to complete
            iocb.wait()

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

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

        except Exception as error:
            ReadWritePropertyConsoleCmd._exception("exception: %r", error)
예제 #18
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
예제 #19
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
예제 #20
0
    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")
예제 #21
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
예제 #22
0
파일: Write.py 프로젝트: xiaotong0202/BAC0
    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)
예제 #24
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)