Beispiel #1
0
    def test_double(self):
        if _debug: TestDouble._debug("test_double")

        obj = Double()
        assert obj.value == 0.0

        with self.assertRaises(TypeError):
            Double("some string")
Beispiel #2
0
    def test_double_double(self):
        if _debug: TestDouble._debug("test_double_double")

        obj = Double(1.0)
        assert obj.value == 1.0
        assert str(obj) == "Double(1)"

        obj = Double(73.5)
        assert obj.value == 73.5
        assert str(obj) == "Double(73.5)"
    def __init__(self, ini_file, overriding_port: int = None):
        self.args = ConfigArgumentParser().parse_args(["--ini", ini_file])
        #addr = Address(self.args.ini.address)
        #if overriding_port:
        #    addr.addrPort = overriding_port
        #print('Address: {0}'.format(addr.addrPort))
        if overriding_port:
            ip, port = self.args.ini['address'].split(':')
            self.args.ini['address'] = ip + ':' + str(overriding_port)
        self.this_device = LocalDeviceObject(ini=self.args.ini)
        BIPSimpleApplication.__init__(self, self.this_device,
                                      self.args.ini['address'])
        self.taskman = TaskManager()
        self.datatype_map = {
            '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,
        }

        thread_handle = threading.Thread(target=self.run_thread)
        thread_handle.daemon = True
        thread_handle.start()
Beispiel #4
0
def double_decode(tag):
    """Decode an double application tag into a double."""
    if _debug: double_decode._debug("double_decode %r", tag)

    obj = Double(tag)
    if _debug: double_decode._debug("    - obj: %r", obj)

    return obj
Beispiel #5
0
 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)
Beispiel #6
0
    def test_double_tag(self):
        if _debug: TestDouble._debug("test_double_tag")

        tag = Tag(Tag.applicationTagClass, Tag.doubleAppTag, 8, xtob('3ff0000000000000'))
        obj = Double(tag)
        assert obj.value == 1.0

        tag = Tag(Tag.applicationTagClass, Tag.booleanAppTag, 0, xtob(''))
        with self.assertRaises(InvalidTag):
            Double(tag)

        tag = Tag(Tag.contextTagClass, 0, 1, xtob('ff'))
        with self.assertRaises(InvalidTag):
            Double(tag)

        tag = Tag(Tag.openingTagClass, 0)
        with self.assertRaises(InvalidTag):
            Double(tag)
Beispiel #7
0
    def test_double_endec(self):
        if _debug: TestDouble._debug("test_double_endec")

        with self.assertRaises(InvalidTag):
            obj = Double(double_tag(''))

        double_endec(0, '0000000000000000')
        double_endec(1, '3ff0000000000000')
        double_endec(-1, 'bff0000000000000')

        double_endec(73.5, '4052600000000000')

        inf = float('inf')
        double_endec(inf, '7ff0000000000000')
        double_endec(-inf, 'fff0000000000000')

        nan = float('nan')
        double_endec(nan, '7ff8000000000000')
Beispiel #8
0
def double_endec(v, x):
    """Pass the value to Double, construct a tag from the hex string,
    and compare results of encode and decoding each other."""
    if _debug: double_endec._debug("double_endec %r %r", v, x)

    tag = double_tag(x)
    if _debug: double_endec._debug("    - tag: %r, %r", tag, tag.tagData)

    obj = Double(v)
    if _debug: double_endec._debug("    - obj: %r, %r", obj, obj.value)

    assert double_encode(obj) == tag
    if _debug: real_endec._debug("    - tags match")

    if math.isnan(v):
        assert math.isnan(double_decode(tag).value)
        if _debug: double_endec._debug("    - both NaN")
    else:
        assert double_decode(tag) == obj
        if _debug: double_endec._debug("    - objects match")
Beispiel #9
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)
Beispiel #10
0
    def test_double_copy(self):
        if _debug: TestDouble._debug("test_double_copy")

        obj1 = Double(12)
        obj2 = Double(obj1)
        assert obj2.value == 12
Beispiel #11
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')
Beispiel #12
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")
Beispiel #13
0
    def test_double_statement(self):
        if _debug: TestExtendedTagStatements._debug("test_double_statement")

        assert statement_to_tag("double 0.0") == tag_encode(Double(0.0))
        assert statement_to_tag("double 75.2") == tag_encode(Double(75.2))
        assert statement_to_tag("double 6.28 context 6") == tag_encode(Double(6.28), context=6)
Beispiel #14
0
def double_statement(value):
    if _debug: double_statement._debug("double_statement %r", value)

    return Double(float(value))