Example #1
0
File: api.py Project: hdqlife/blink
 def writeValue(self,addr,obj_id,prop_id,value,indx=None,priority=None):
     if isinstance(obj_id,str):
         obj_id=obj_id.split(':')
         obj_id[1]=int(obj_id[1])
     addr=RemoteStation(addr[0],bytearray(addr[1]))
     datatype = get_datatype(obj_id[0],prop_id)
     if datatype is None:return
     if (value == 'null'):
         value = Null()
     elif issubclass(datatype, AnyAtomic):
         dtype, dvalue = value.split(':', 1)
         datatype = {
             'b': Boolean,
             'u': lambda x: Unsigned(int(x)),
             'i': lambda x: Integer(int(x)),
             'r': lambda x: Real(float(x)),
             'd': lambda x: Double(float(x)),
             'o': OctetString,
             'c': CharacterString,
             'bs': BitString,
             'date': Date,
             'time': Time,
             'id': ObjectIdentifier,
             }[dtype]
         value = datatype(dvalue)
     elif issubclass(datatype, Atomic):
         if datatype is Integer:
             value = int(value)
         elif datatype is Real:
             value = float(value)
         elif datatype is Unsigned:
             value = int(value)
         value = datatype(value)
     elif issubclass(datatype, Array) and (indx is not None):
         if indx == 0:
             value = Integer(value)
         elif issubclass(datatype.subtype, Atomic):
             value = datatype.subtype(value)
         elif not isinstance(value, datatype.subtype):
             raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__,))
     elif not isinstance(value, datatype):
         raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__,))
     # build a request
     request = WritePropertyRequest(
         objectIdentifier=tuple(obj_id),
         propertyIdentifier=prop_id,
         destination=addr
     )
     # save the value
     request.propertyValue = Any()
     request.propertyValue.cast_in(value)
     if indx is not None:
         request.propertyArrayIndex = indx
     if priority is not None:
         request.priority = priority
     iocb = IOCB(request)
     self.request_io(iocb)
Example #2
0
    def test_null(self):
        if _debug: TestInteger._debug("test_null")

        obj = Null()
        assert obj.value == ()

        with self.assertRaises(TypeError):
            Null("some string")
        with self.assertRaises(TypeError):
            Null(1.0)
    def do_except(self, args):
        """except <date> <start> <stop>"""
        args = args.split()
        if _debug:
            TestConsoleCmd._debug("do_except %r", args)

        date_string, start_string, stop_string = args
        except_date = Date(date_string).value
        start_time = Time(start_string).value
        stop_time = Time(stop_string).value

        exception_schedule = ArrayOf(SpecialEvent)([
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    date=except_date)),
                listOfTimeValues=[
                    TimeValue(time=start_time, value=Real(999.0)),
                    TimeValue(time=stop_time, value=Null()),
                ],
                eventPriority=1,
            )
        ])
        if _debug:
            TestConsoleCmd._debug("    - exception_schedule: %r",
                                  exception_schedule)

        # new exception
        test_schedule.exceptionSchedule = exception_schedule
Example #4
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 !!"
Example #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))
Example #6
0
def write_property(self,
                   target_address,
                   value,
                   object_type,
                   instance_number,
                   property_name,
                   priority=None,
                   index=None):
    """Write to a property."""

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

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

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

    request.pduDestination = Address(target_address)

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

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

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


#k= write_property("2001:127", 1, "binaryOutput", 1, "presentValue", priority=None, index=None)
Example #7
0
def null_decode(tag):
    """Decode an integer application tag into an integer."""
    if _debug: null_decode._debug("null_decode %r", tag)

    obj = Null(tag)
    if _debug: null_decode._debug("    - obj: %r", obj)

    return obj
def main():
    global args, schedule_objects

    # parse the command line arguments
    parser = ConfigArgumentParser(description=__doc__)

    # parse the command line arguments
    args = parser.parse_args()

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

    # set up testing
    setup_module()

    # reset the time machine
    reset_time_machine(start_time="1970-01-01")

    #
    #   Simple daily schedule (actually a weekly schedule with every day
    #   being identical.
    #
    so = LocalScheduleObject(
        objectIdentifier=('schedule', 1),
        objectName='Schedule 1',
        presentValue=Integer(5),
        effectivePeriod=DateRange(
            startDate=(0, 1, 1, 1),
            endDate=(254, 12, 31, 2),
        ),
        weeklySchedule=ArrayOf(DailySchedule)([
            DailySchedule(daySchedule=[
                TimeValue(time=(8, 0, 0, 0), value=Integer(8)),
                TimeValue(time=(14, 0, 0, 0), value=Null()),
                TimeValue(time=(17, 0, 0, 0), value=Integer(42)),
                #                   TimeValue(time=(0,0,0,0), value=Null()),
            ]),
        ] * 7),
        scheduleDefault=Integer(0),
    )
    _log.debug("    - so: %r", so)
    schedule_objects.append(so)

    print("{} @ {}".format(so.presentValue.value, Time().now()))

    for i in range(1, 25):
        hr = "{}:00:01".format(i)

        # let it run until just after midnight
        run_time_machine(stop_time=hr)

        print("{} @ {}".format(so.presentValue.value, Time().now()))

    # done testing
    teardown_module()
Example #9
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))
Example #10
0
def null_endec(v, x):
    """Pass the value to Integer, construct a tag from the hex string,
    and compare results of encode and decoding each other."""
    if _debug: null_endec._debug("null_endec %r %r", v, x)

    tag = null_tag(x)
    if _debug: null_endec._debug("    - tag: %r, %r", tag, tag.tagData)

    obj = Null(v)
    if _debug: null_endec._debug("    - obj: %r, %r", obj, obj.value)

    assert null_encode(obj) == tag
    assert null_decode(tag) == obj
class TestBACnetCoderMixin:
    @pytest.mark.parametrize(
        "priority_array, expected",
        [
            (PriorityArray([PriorityValue(null=Null())] * 16), [None] * 16),
            (
                PriorityArray([
                    *[PriorityValue(null=Null())] * 7,
                    PriorityValue(real=3.3),
                    *[PriorityValue(null=Null())] * 8,
                ]),
                [*[None] * 7, 3.3, *[None] * 8],
            ),
        ],
    )
    def test__decode_priority_array(self, priority_array, expected):
        bacnet_decoder = BACnetCoderMixin()
        assert (bacnet_decoder._decode_priority_array(
            priority_array=priority_array) == expected)

    @pytest.mark.parametrize(
        "value, expected",
        [
            (1, "active"),
            (0, "inactive"),
            (1.0, "active"),
            (True, "active"),
            (False, "inactive"),
            (None, "inactive"),
            ("1", "active"),
            ("0", "active"),
        ],
    )
    def test__encode_binary_present_value(self, value, expected):
        bacnet_decoder = BACnetCoderMixin()
        assert bacnet_decoder._encode_binary_present_value(
            value=value) == expected
 def form_iocb(device, config=None, request_type="readProperty"):
     config = config if config is not None else device
     address = device["address"] if isinstance(device["address"], Address) else Address(device["address"])
     object_id = ObjectIdentifier(config["objectId"])
     property_id = config.get("propertyId")
     value = config.get("propertyValue")
     property_index = config.get("propertyIndex")
     priority = config.get("priority")
     vendor = device.get("vendor", config.get("vendorId", 0))
     request = None
     iocb = None
     if request_type == "readProperty":
         try:
             request = ReadPropertyRequest(
                 objectIdentifier=object_id,
                 propertyIdentifier=property_id
             )
             request.pduDestination = address
             if property_index is not None:
                 request.propertyArrayIndex = int(property_index)
             iocb = IOCB(request)
         except Exception as e:
             log.exception(e)
     elif request_type == "writeProperty":
         datatype = get_datatype(object_id.value[0], property_id, vendor)
         if (isinstance(value, str) and value.lower() == 'null') or value is None:
             value = Null()
         request = WritePropertyRequest(
             objectIdentifier=object_id,
             propertyIdentifier=property_id
         )
         request.pduDestination = address
         request.propertyValue = Any()
         try:
             value = datatype(value)
             request.propertyValue = Any(value)
         except AttributeError as e:
             log.debug(e)
         except Exception as error:
             log.exception("WriteProperty cast error: %r", error)
         if property_index is not None:
             request.propertyArrayIndex = property_index
         if priority is not None:
             request.priority = priority
         iocb = IOCB(request)
     else:
         log.error("Request type is not found or not implemented")
     return iocb
Example #13
0
    def _validate_value_vs_datatype(self, obj_type, prop_id, indx, vendor_id,
                                    value):
        """
        This will ensure the value can be encoded and is valid in the context
        """
        # get the datatype
        datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_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
                    # or datatype is not Real
                    or datatype is Unsigned or datatype is Enumerated):
                value = int(value)
            elif datatype is Real:
                value = float(value)
                # value = datatype(value)
            else:
                # value = float(value)
                value = datatype(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)))

        _value = Any()
        try:
            _value.cast_in(value)
        except WritePropertyCastError as error:
            self._log.error("WriteProperty cast error: {!r}".format(error))
            raise

        return _value
Example #14
0
    def __init__(self, init_value, **kwargs):
        if _debug:
            CommandableMixin._debug("__init__ %r, %r", init_value, kwargs)
        super(CommandableMixin, self).__init__(**kwargs)

        # if no present value given, give it the default value
        if ('presentValue' not in kwargs):
            if _debug:
                CommandableMixin._debug("    - initialize present value")
            self.presentValue = init_value

        # if no priority array given, give it an empty one
        if ('priorityArray' not in kwargs):
            if _debug:
                CommandableMixin._debug("    - initialize priority array")
            self.priorityArray = PriorityArray()
            for i in range(16):
                self.priorityArray.append(PriorityValue(null=Null()))

        # if no relinquish default value given, give it the default value
        if ('relinquishDefault' not in kwargs):
            if _debug:
                CommandableMixin._debug("    - initialize relinquish default")
            self.relinquishDefault = init_value

        # capture the present value property
        self._pv = self._properties['presentValue']
        if _debug: CommandableMixin._debug("    - _pv: %r", self._pv)

        # capture the datatype
        self._pv_datatype = self._pv.datatype
        if _debug:
            CommandableMixin._debug("    - _pv_datatype: %r",
                                    self._pv_datatype)

        # look up a matching priority value choice
        for element in PriorityValue.choiceElements:
            if element.klass is self._pv_datatype:
                self._pv_choice = element.name
                break
        else:
            self._pv_choice = 'constructedValue'
        if _debug:
            CommandableMixin._debug("    - _pv_choice: %r", self._pv_choice)
Example #15
0
def cast_value(value, data_type, prop_index=None, prop=None):
    # pylint: disable=too-many-branches
    """
    This function casts value to data type.

    :param value: object
    :param data_type: data type
    :param prop_index: property array index
    :param prop: property instance
    :return: casted value
    """

    cast_value._debug('start %r, %r, %r, %r', value, data_type, prop_index, prop)

    # get value from value
    if not hasattr(data_type, 'subtype') or isinstance(value, ObjectIdentifier):
        value = getattr(value, 'value', value)

    # cast value
    if value == 'null':
        value = Null()

    elif issubclass(data_type, Atomic):
        if data_type is Integer:
            if value is None:
                value = 0

            value = int(value)

        elif data_type is Real:
            if value is None:
                value = 0

            value = float(value)

        elif data_type is Unsigned:
            if value is None:
                value = 0

            value = int(value)

        elif (data_type is ObjectIdentifier) and (isinstance(value, basestring)):
            value = value.split()
            value[1] = int(value[1])
            value = tuple(value)

        value = data_type(value)

    elif issubclass(data_type, Array) and (prop_index is not None):

        if prop_index == 0:
            if isinstance(value, basestring) and not value.isdigit():
                raise ValueError('array size must be integer')

            value = Unsigned(value)

        elif issubclass(data_type.subtype, Atomic):
            value = cast_value(value, data_type.subtype, prop_index, prop=prop)

        elif not isinstance(value, data_type.subtype):
            raise TypeError(
                'invalid result datatype, expecting %s and got %s' %
                (data_type.subtype.__name__, type(value).__name__)
            )

    elif not isinstance(value, data_type) and value is not None:
        # check if value exists or property is optional
        if value is not None or prop is None or (prop is not None and not prop.optional):
            raise TypeError(
                'invalid result datatype, expecting %s and got %s' %
                (data_type.__name__, type(value).__name__)
            )

    # return casted value
    return value
Example #16
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
Example #17
0
    def test_null_copy(self):
        if _debug: TestInteger._debug("test_null_copy")

        obj1 = Null()
        obj2 = Null(obj1)
        assert obj2.value == ()
    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)
Example #19
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)
Example #20
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")
Example #21
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 main():
    global args, test_analog_value, test_schedule

    # parse the command line arguments
    parser = ConfigArgumentParser(description=__doc__)

    # parse the command line arguments
    args = parser.parse_args()

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

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

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # create a writeable analog value object
    test_analog_value = WritableAnalogValueObject(
        objectIdentifier=("analogValue", 1),
        objectName="Test Analog Value",
        presentValue=0.0,
    )
    _log.debug("    - test_analog_value: %r", test_analog_value)
    this_application.add_object(test_analog_value)

    # print when the value changes
    test_analog_value._property_monitors["presentValue"].append(
        analog_value_changed)

    #
    #   Simple daily schedule (actually a weekly schedule with every day
    #   being identical.
    #
    test_schedule = LocalScheduleObject(
        objectIdentifier=("schedule", 1),
        objectName="Test Schedule",
        presentValue=Real(8.0),
        effectivePeriod=DateRange(startDate=(0, 1, 1, 1),
                                  endDate=(254, 12, 31, 2)),
        weeklySchedule=ArrayOf(DailySchedule, 7)([
            DailySchedule(daySchedule=[
                TimeValue(time=(8, 0, 0, 0), value=Real(8.0)),
                TimeValue(time=(14, 0, 0, 0), value=Null()),
                TimeValue(time=(17, 0, 0, 0), value=Real(42.0)),
            ])
        ] * 7),
        listOfObjectPropertyReferences=ListOf(DeviceObjectPropertyReference)([
            DeviceObjectPropertyReference(
                objectIdentifier=("analogValue", 1),
                propertyIdentifier="presentValue",
            )
        ]),
        scheduleDefault=Real(0.0),
    )
    _log.debug("    - test_schedule: %r", test_schedule)
    this_application.add_object(test_schedule)

    TestConsoleCmd()

    _log.debug("running")

    run()

    _log.debug("fini")
Example #23
0
    def test_boolean_application_to_object(self):
        if _debug:
            TestApplicationTag._debug("test_boolean_application_to_object")

        # null
        obj_endec(Null(), '00')

        # boolean
        obj_endec(Boolean(True), '11')
        obj_endec(Boolean(False), '10')

        # unsigned
        obj_endec(Unsigned(0), '2100')
        obj_endec(Unsigned(1), '2101')
        obj_endec(Unsigned(127), '217F')
        obj_endec(Unsigned(128), '2180')

        # integer
        obj_endec(Integer(0), '3100')
        obj_endec(Integer(1), '3101')
        obj_endec(Integer(-1), '31FF')
        obj_endec(Integer(128), '320080')
        obj_endec(Integer(-128), '3180')

        # real
        obj_endec(Real(0), '4400000000')
        obj_endec(Real(1), '443F800000')
        obj_endec(Real(-1), '44BF800000')
        obj_endec(Real(73.5), '4442930000')

        # double
        obj_endec(Double(0), '55080000000000000000')
        obj_endec(Double(1), '55083FF0000000000000')
        obj_endec(Double(-1), '5508BFF0000000000000')
        obj_endec(Double(73.5), '55084052600000000000')

        # octet string
        obj_endec(OctetString(xtob('')), '60')
        obj_endec(OctetString(xtob('01')), '6101')
        obj_endec(OctetString(xtob('0102')), '620102')
        obj_endec(OctetString(xtob('010203040506')), '6506010203040506')

        # character string
        obj_endec(CharacterString(''), '7100')
        obj_endec(CharacterString('a'), '720061')
        obj_endec(CharacterString('abcde'), '7506006162636465')

        # bit string
        obj_endec(BitString([]), '8100')
        obj_endec(BitString([0]), '820700')
        obj_endec(BitString([1]), '820780')
        obj_endec(BitString([1, 1, 1, 1, 1]), '8203F8')
        obj_endec(BitString([1] * 10), '8306FFC0')

        # enumerated
        obj_endec(Enumerated(0), '9100')
        obj_endec(Enumerated(1), '9101')
        obj_endec(Enumerated(127), '917F')
        obj_endec(Enumerated(128), '9180')

        # date
        obj_endec(Date((1, 2, 3, 4)), 'A401020304')
        obj_endec(Date((255, 2, 3, 4)), 'A4FF020304')
        obj_endec(Date((1, 255, 3, 4)), 'A401FF0304')
        obj_endec(Date((1, 2, 255, 4)), 'A40102FF04')
        obj_endec(Date((1, 2, 3, 255)), 'A4010203FF')

        # time
        obj_endec(Time((1, 2, 3, 4)), 'B401020304')
        obj_endec(Time((255, 2, 3, 4)), 'B4FF020304')
        obj_endec(Time((1, 255, 3, 4)), 'B401FF0304')
        obj_endec(Time((1, 2, 255, 4)), 'B40102FF04')
        obj_endec(Time((1, 2, 3, 255)), 'B4010203FF')

        # object identifier
        obj_endec(ObjectIdentifier(0, 0), 'C400000000')
        obj_endec(ObjectIdentifier(1, 0), 'C400400000')
        obj_endec(ObjectIdentifier(0, 2), 'C400000002')
        obj_endec(ObjectIdentifier(3, 4), 'C400C00004')
    def test_local_schedule(self):
        if _debug: TestLocalSchedule._debug("test_local_schedule")

        # reset the time machine
        reset_time_machine(start_time="1970-01-01")

        # make a device object
        this_device = LocalDeviceObject(
            objectName="device 1",
            objectIdentifier=('device', 1),
            maxApduLengthAccepted=1024,
            segmentationSupported='segmentedBoth',
            vendorIdentifier=999,
        )

        # make a floating application, no network interface
        this_application = Application(this_device)

        # create a writeable analog value object
        avo = WritableAnalogValueObject(
            objectIdentifier=('analogValue', 1),
            objectName='analog value 1',
            presentValue=0.0,
        )
        _log.debug("    - avo: %r", avo)
        this_application.add_object(avo)

        # create a simple daily schedule, actually a weekly schedule with
        # every day identical
        so = LocalScheduleObject(
            objectIdentifier=('schedule', 1),
            objectName='Schedule 1',
            presentValue=Real(-1.0),
            effectivePeriod=DateRange(
                startDate=(0, 1, 1, 1),
                endDate=(254, 12, 31, 2),
            ),
            weeklySchedule=ArrayOf(DailySchedule)([
                DailySchedule(daySchedule=[
                    TimeValue(time=(8, 0, 0, 0), value=Real(8)),
                    TimeValue(time=(14, 0, 0, 0), value=Null()),
                    TimeValue(time=(17, 0, 0, 0), value=Real(42)),
                ]),
            ] * 7),
            listOfObjectPropertyReferences=[
                DeviceObjectPropertyReference(
                    objectIdentifier=('analogValue', 1),
                    propertyIdentifier='presentValue',
                ),
            ],
            priorityForWriting=7,
            scheduleDefault=Real(0.0),
        )
        _log.debug("    - so: %r", so)
        this_application.add_object(so)

        # run from midnight to just after midnight the next day
        for hr, val in zip(range(0, 26),
                           [0] * 8 + [8] * 6 + [0] * 3 + [42] * 7 + [0]):
            # let it run
            run_time_machine(stop_time="{}:00:01".format(hr))
            if _debug:
                TestLocalSchedule._debug(
                    "    - hr, val, pv: %s, %s, %s",
                    hr,
                    val,
                    so.presentValue.value,
                )

            assert so.presentValue.value == val
            assert avo.presentValue == val
Example #25
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
    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)
Example #27
0
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # make a schedule object with an integer value
    so1 = ScheduleObject(
        objectIdentifier=1,
        objectName='Schedule 1 (integer)',
        presentValue=Integer(8),
        weeklySchedule=ArrayOf(DailySchedule)([
            DailySchedule(daySchedule=[
                TimeValue(time=(8, 0, 0, 0), value=Integer(8)),
                TimeValue(time=(14, 0, 0, 0), value=Null()),
                TimeValue(time=(17, 0, 0, 0), value=Integer(42)),
                TimeValue(time=(0, 0, 0, 0), value=Null()),
            ]),
        ] * 7),
        scheduleDefault=Integer(0),
    )
    _log.debug("    - so1: %r", so1)

    so2 = ScheduleObject(
        objectIdentifier=2,
        objectName='Schedule 2 (real)',
        presentValue=Real(73.5),
        weeklySchedule=ArrayOf(DailySchedule)([
            DailySchedule(daySchedule=[
                TimeValue(time=(9, 0, 0, 0), value=Real(78.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))
Example #29
0
    def test_null_null(self):
        if _debug: TestInteger._debug("test_null_null")

        obj = Null(())
        assert obj.value == ()
Example #30
0
    def test_null_tag(self):
        if _debug: TestInteger._debug("test_null_tag")

        tag = Tag(Tag.applicationTagClass, Tag.nullAppTag, 0, xtob(''))
        obj = Null(tag)
        assert obj.value == ()
def main():
    global args, schedule_objects

    # parse the command line arguments
    parser = ConfigArgumentParser(description=__doc__)

    # parse the command line arguments
    args = parser.parse_args()

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

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

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    #
    #   Simple daily schedule (actually a weekly schedule with every day
    #   being identical.
    #
    so = LocalScheduleObject(
        objectIdentifier=('schedule', 1),
        objectName='Schedule 1',
        presentValue=Integer(8),
        effectivePeriod=DateRange(
            startDate=(0, 1, 1, 1),
            endDate=(254, 12, 31, 2),
        ),
        weeklySchedule=ArrayOf(DailySchedule)([
            DailySchedule(daySchedule=[
                TimeValue(time=(8, 0, 0, 0), value=Integer(8)),
                TimeValue(time=(14, 0, 0, 0), value=Null()),
                TimeValue(time=(17, 0, 0, 0), value=Integer(42)),
                #                   TimeValue(time=(0,0,0,0), value=Null()),
            ]),
        ] * 7),
        scheduleDefault=Integer(0),
    )
    _log.debug("    - so: %r", so)
    this_application.add_object(so)
    schedule_objects.append(so)

    #
    #   A special schedule when the Year 2000 problem was supposed to collapse
    #   systems, the panic clears ten minutes later when it didn't.
    #
    so = LocalScheduleObject(
        objectIdentifier=('schedule', 2),
        objectName='Schedule 2',
        presentValue=CharacterString(""),
        effectivePeriod=DateRange(
            startDate=(0, 1, 1, 1),
            endDate=(254, 12, 31, 2),
        ),
        exceptionSchedule=ArrayOf(SpecialEvent)([
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    date=Date("2000-01-01").value, ), ),
                listOfTimeValues=[
                    TimeValue(time=(0, 0, 0, 0),
                              value=CharacterString("Panic!")),
                    TimeValue(time=(0, 10, 0, 0), value=Null()),
                ],
                eventPriority=1,
            ),
        ]),
        scheduleDefault=CharacterString("Don't panic."),
    )
    _log.debug("    - so: %r", so)
    this_application.add_object(so)
    schedule_objects.append(so)

    #
    #   A special schedule to celebrate Friday.
    #
    so = LocalScheduleObject(
        objectIdentifier=('schedule', 3),
        objectName='Schedule 3',
        presentValue=CharacterString(""),
        effectivePeriod=DateRange(
            startDate=(0, 1, 1, 1),
            endDate=(254, 12, 31, 2),
        ),
        exceptionSchedule=ArrayOf(SpecialEvent)([
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    weekNDay=xtob("FF.FF.05"), ), ),
                listOfTimeValues=[
                    TimeValue(time=(0, 0, 0, 0),
                              value=CharacterString("It's Friday!")),
                ],
                eventPriority=1,
            ),
        ]),
        scheduleDefault=CharacterString("Keep working."),
    )
    _log.debug("    - so: %r", so)
    this_application.add_object(so)
    schedule_objects.append(so)

    #
    #   A schedule object that refers to an AnalogValueObject in the test
    #   device.
    #
    so = LocalScheduleObject(
        objectIdentifier=('schedule', 4),
        objectName='Schedule 4',
        presentValue=Real(73.5),
        effectivePeriod=DateRange(
            startDate=(0, 1, 1, 1),
            endDate=(254, 12, 31, 2),
        ),
        weeklySchedule=ArrayOf(DailySchedule)([
            DailySchedule(daySchedule=[
                TimeValue(time=(9, 0, 0, 0), value=Real(78.0)),
                TimeValue(time=(10, 0, 0, 0), value=Null()),
            ]),
        ] * 7),
        scheduleDefault=Real(72.0),
        listOfObjectPropertyReferences=SequenceOf(
            DeviceObjectPropertyReference)([
                DeviceObjectPropertyReference(
                    objectIdentifier=('analogValue', 1),
                    propertyIdentifier='presentValue',
                ),
            ]),
    )
    _log.debug("    - so: %r", so)
    this_application.add_object(so)
    schedule_objects.append(so)

    #
    #   The beast
    #
    so = LocalScheduleObject(
        objectIdentifier=('schedule', 5),
        objectName='Schedule 5',
        presentValue=Integer(0),
        effectivePeriod=DateRange(
            startDate=(0, 1, 1, 1),
            endDate=(254, 12, 31, 2),
        ),
        exceptionSchedule=ArrayOf(SpecialEvent)([
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    weekNDay=xtob("FF.FF.FF"), ), ),
                listOfTimeValues=[
                    TimeValue(time=(5, 0, 0, 0), value=Integer(5)),
                    TimeValue(time=(6, 0, 0, 0), value=Null()),
                ],
                eventPriority=1,
            ),
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    weekNDay=xtob("FF.FF.FF"), ), ),
                listOfTimeValues=[
                    TimeValue(time=(4, 0, 0, 0), value=Integer(4)),
                    TimeValue(time=(7, 0, 0, 0), value=Null()),
                ],
                eventPriority=2,
            ),
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    weekNDay=xtob("FF.FF.FF"), ), ),
                listOfTimeValues=[
                    TimeValue(time=(3, 0, 0, 0), value=Integer(3)),
                    TimeValue(time=(8, 0, 0, 0), value=Null()),
                ],
                eventPriority=3,
            ),
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    weekNDay=xtob("FF.FF.FF"), ), ),
                listOfTimeValues=[
                    TimeValue(time=(2, 0, 0, 0), value=Integer(2)),
                    TimeValue(time=(9, 0, 0, 0), value=Null()),
                ],
                eventPriority=4,
            ),
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    weekNDay=xtob("FF.FF.FF"), ), ),
                listOfTimeValues=[
                    TimeValue(time=(1, 0, 0, 0), value=Integer(1)),
                ],
                eventPriority=5,
            ),
        ]),
        scheduleDefault=Integer(0),
    )
    _log.debug("    - so: %r", so)
    this_application.add_object(so)
    schedule_objects.append(so)

    # list of time values for every five minutes
    ltv = []
    for hr in range(24):
        for mn in range(0, 60, 5):
            ltv.append(
                TimeValue(time=(hr, mn, 0, 0), value=Integer(hr * 100 + mn)))

    so = LocalScheduleObject(
        objectIdentifier=('schedule', 6),
        objectName='Schedule 6',
        presentValue=Integer(0),
        effectivePeriod=DateRange(
            startDate=(0, 1, 1, 1),
            endDate=(254, 12, 31, 2),
        ),
        exceptionSchedule=ArrayOf(SpecialEvent)([
            SpecialEvent(
                period=SpecialEventPeriod(calendarEntry=CalendarEntry(
                    weekNDay=xtob("FF.FF.FF"), ), ),
                listOfTimeValues=ltv,
                eventPriority=1,
            ),
        ]),
        scheduleDefault=Integer(0),
    )
    _log.debug("    - so: %r", so)
    this_application.add_object(so)
    schedule_objects.append(so)

    # make sure they are all there
    _log.debug("    - object list: %r", this_device.objectList)

    TestConsoleCmd()

    _log.debug("running")

    run()

    _log.debug("fini")