Example #1
0
    def test_real(self):
        if _debug: TestReal._debug("test_real")

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

        with self.assertRaises(TypeError):
            Real("some string")
Example #2
0
    def test_real_real(self):
        if _debug: TestReal._debug("test_real_real")

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

        obj = Real(73.5)
        assert obj.value == 73.5
        assert str(obj) == "Real(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()
    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 #5
0
    def __init__(self, *args):
        BIPSimpleApplication.__init__(Mock())
        self.elementService = Mock()
        #self.ResponseQueue = Mock()
        #self.ResponseQueue.get.return_value = ([21, 'degreesCelcius'], Event())
        iocb = IOCB()
        apdu = ReadPropertyMultipleACK(listOfReadAccessResults=[
            ReadAccessResult(
                objectIdentifier=('analogValue', 1),
                listOfResults=[
                    ReadAccessResultElement(
                        propertyIdentifier='presentValue',
                        readResult=ReadAccessResultElementChoice(
                            propertyValue=Any(Real(21.0)), )),
                    ReadAccessResultElement(
                        propertyIdentifier='units',
                        readResult=ReadAccessResultElementChoice(
                            propertyValue=Any(Enumerated(62)), )),
                ],
            )
        ])

        iocb.complete(apdu)
        self.request = Mock()
        self.request.return_value = iocb
Example #6
0
    def test_readProperty(self):
        request = ReadPropertyRequest(
            objectIdentifier=("analogInput", 14), propertyIdentifier=85
        )
        request.apduMaxResp = 1024
        request.apduInvokeID = 101
        apdu = APDU()
        request.encode(apdu)
        pdu = PDU()
        apdu.encode(pdu)
        buf_size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.sendto(pdu.pduData, self.address)
        data = s.recvfrom(buf_size)
        s.close()
        received_data = data[0]

        expected = ReadPropertyACK()
        expected.pduDestination = GlobalBroadcast()
        expected.apduInvokeID = 101
        expected.objectIdentifier = 14
        expected.objectName = "AI 01"
        expected.propertyIdentifier = 85
        expected.propertyValue = Any(Real(68.0))

        exp_apdu = APDU()
        expected.encode(exp_apdu)
        exp_pdu = PDU()
        exp_apdu.encode(exp_pdu)

        self.assertEqual(exp_pdu.pduData, received_data)
Example #7
0
 def run(self):
     while not self.flag_stop:
         time.sleep(10)
         for obj in self.objs:
             objname = str(obj._values["objectName"])
             for meter in self.meters:
                 if meter.name == objname:
                     obj._values["outOfService"] = Boolean(
                         not meter.is_connected)
                     obj._values["presentValue"] = Real(
                         meter.getPresentValue())
                     fname = objname
                     #output_csv = os.path.join ( str ( '/home/cleangat/bacdevice/csv' ), fname + u".csv" )
                     output_csv = os.path.join(str('/var/www/html'),
                                               fname + u".csv")
                     mode = 'a'
                     if sys.version_info.major < 3:
                         mode += 'b'
                     with open(output_csv, mode) as f:
                         writer = csv.writer(f, delimiter=',')
                         outputvar = meter.getPresentValue()
                         writer.writerow([
                             datetime.datetime.now().replace(
                                 microsecond=0).isoformat(" "), outputvar
                         ])
                         f.close()
Example #8
0
    def test_primitive_tag(self):
        if _debug: TestNameValue._debug("test_primitive_tag")

        # try the primitive types
        name_value_endec("status", Boolean(False))
        name_value_endec("age", Integer(3))
        name_value_endec("experience", Real(73.5))
Example #9
0
def real_decode(tag):
    """Decode an real application tag into an real."""
    if _debug: real_decode._debug("real_decode %r", tag)

    obj = Real(tag)
    if _debug: real_decode._debug("    - obj: %r, %r", obj, obj.value)

    return obj
Example #10
0
    def test_real_tag(self):
        if _debug: TestReal._debug("test_real_tag")

        tag = Tag(Tag.applicationTagClass, Tag.realAppTag, 1, xtob('3f800000'))
        obj = Real(tag)
        assert obj.value == 1.0

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

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

        tag = Tag(Tag.openingTagClass, 0)
        with self.assertRaises(InvalidTag):
            Real(tag)
Example #11
0
 def _set_value(v):
     try:
         if dict_schedule["states"].lower() == "analog":
             return Real(v)
     except AttributeError:
         if dict_schedule["states"] == ["inactive", "active"]:
             return Integer(dict_schedule["states"][v])
         else:
             return Integer(dict_schedule["states"][v] - 1)
Example #12
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 #13
0
 def run(self):
     while not self.flag_stop:
         time.sleep(1)
         for obj in self.objs:
             objname = str(obj._values["objectName"])
             for meter in self.meters:
                 if meter.name == objname:
                     obj._values["outOfService"] = Boolean(
                         not meter.is_connected)
                     obj._values["presentValue"] = Real(
                         meter.getPresentValue())
Example #14
0
 def run(self):
     while not self.flag_stop:
         time.sleep(1)
         for obj in self.objs:
             objname = str(obj._values['objectName'])
             for meter in self.meters:
                 if meter.name == objname:
                     obj._values['outOfService'] = Boolean(
                         not meter.is_connected)
                     obj._values['presentValue'] = Real(meter.dust_small *
                                                        100)
Example #15
0
    def __init__(self, *args):
        BIPSimpleApplication.__init__(Mock())
        self.elementService = Mock()
        #self.value = None
        iocb = IOCB()

        # Forging apdu response
        fake_apdu = ReadPropertyACK(
            objectIdentifier=('analogInput', 0),
            propertyIdentifier='presentValue',
            propertyValue=Any(Real(32)),
        )
        iocb.complete(fake_apdu)
        self.request = Mock()
        self.request.return_value = iocb
Example #16
0
    def test_real_endec(self):
        if _debug: TestReal._debug("test_real_endec")

        with self.assertRaises(InvalidTag):
            obj = Real(real_tag(''))

        real_endec(0, '00000000')
        real_endec(1, '3f800000')
        real_endec(-1, 'bf800000')

        real_endec(73.5, '42930000')

        inf = float('inf')
        real_endec(inf, '7f800000')
        real_endec(-inf, 'ff800000')

        nan = float('nan')
        real_endec(nan, '7fc00000')
Example #17
0
def real_endec(v, x):
    """Pass the value to Real, construct a tag from the hex string,
    and compare results of encode and decoding each other."""
    if _debug: real_endec._debug("real_endec %r %r", v, x)

    tag = real_tag(x)
    if _debug: real_endec._debug("    - tag: %r, %r", tag, tag.tagData)

    obj = Real(v)
    if _debug: real_endec._debug("    - obj: %r, %r", obj, obj.value)

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

    if math.isnan(v):
        assert math.isnan(real_decode(tag).value)
        if _debug: real_endec._debug("    - both NaN")
    else:
        assert real_decode(tag) == obj
        if _debug: real_endec._debug("    - objects match")
Example #18
0
    def process_task(self):
        if _debug:
            PrairieDog._debug("process_task")
        global args, this_application

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

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

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

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

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

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

        # give it to the application to process
        deferred(this_application.request_io, iocb)
Example #19
0
def changeValues():
  for point in bacnet_objects:
     value = random.randrange(*point['random_args'])
     point['object'].presentValue = Real(value)
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 #21
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
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")
Example #24
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 #25
0
        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)),
                TimeValue(time=(10, 0, 0, 0), value=Null()),
            ]),
        ] * 7),
        scheduleDefault=Real(72.0),
    )
    _log.debug("    - so2: %r", so2)

    # add it to the device
    this_application.add_object(so1)
    this_application.add_object(so2)
    _log.debug("    - object list: %r", this_device.objectList)
Example #26
0
def changeValues():
    for i in range(10):
        vav_object = bacnet.this_application.get_object_name(f"DPR{i}-O")
        value = random.randrange(5, 95, 1)
        vav_object.presentValue = Real(value)
Example #27
0
    def test_real_copy(self):
        if _debug: TestReal._debug("test_real_copy")

        obj1 = Real(12)
        obj2 = Real(obj1)
        assert obj2.value == 12
Example #28
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 #29
0
    def test_real_statement(self):
        if _debug: TestExtendedTagStatements._debug("test_real_statement")

        assert statement_to_tag("real 0.0") == tag_encode(Real(0.0))
        assert statement_to_tag("real 72.5") == tag_encode(Real(72.5))
        assert statement_to_tag("real 3.14 context 5") == tag_encode(Real(3.14), context=5)
Example #30
0
def main():
    device_info = {
        'ip': '10.169.204.200',
        'netmask': 23,
        'port': 47809,
        'objectName': 'FHL-DAF-DUSTMETER',
        'objectIdentifier': 522020,
        'vendorIdentifier': 15,
        'location': 'FHL-DAF-CLEAN-ROOM',
        'vendorName': 'DESY-ATLAS',
        'modelName': 'DUST-METERS',
        'softwareVersion': 'bacpypes_v0.16.2_py27',
        'description': 'FHL-DAF clean room dustmeter server'
    }

    print device_info

    this_device = LocalDeviceObject(
        objectName=device_info['objectName'],
        objectIdentifier=device_info['objectIdentifier'],
        vendorIdentifier=device_info['vendorIdentifier'])

    this_device._values['location'] = CharacterString(device_info['location'])
    this_device._values['vendorName'] = CharacterString(
        device_info['vendorName'])
    this_device._values['modelName'] = CharacterString(
        device_info['modelName'])
    this_device._values['applicationSoftwareVersion'] = CharacterString(
        device_info['softwareVersion'])
    this_device._values['description'] = CharacterString(
        device_info['description'])

    this_addr = str(device_info['ip'] + '/' + str(device_info['netmask']) +
                    ':' + str(device_info['port']))
    print 'bacnet server will listen at', this_addr
    this_application = BIPSimpleApplication(this_device, this_addr)
    this_application.add_capability(ReadWritePropertyMultipleServices)
    this_device.protocolServicesSupported = this_application.get_services_supported(
    ).value

    meter_info = [
        {
            'name': 'dustmeter_a19',
            'index': 1,
            'host': 'fhlrs232_a19.desy.de',
            'description': 'dustmeter on RS232-Ethernet bridge at somewhere',
        },
        {
            'name': 'dustmeter_a27',
            'index': 2,
            'host': 'fhlrs232_a27.desy.de',
            'description': 'dustmeter on RS232-Ethernet bridge at somewhere',
        },
        {
            'name': 'dustmeter_a40',
            'index': 3,
            'host': 'fhlrs232_a40.desy.de',
            'description': 'dustmeter on RS232-Ethernet bridge at somewhere',
        },
        {
            'name': 'dustmeter_a43',
            'index': 4,
            'host': 'fhlrs232_a43.desy.de',
            'description': 'dustmeter on RS232-Ethernet bridge at somewhere',
        },
        {
            'name': 'dustmeter_a49',
            'index': 5,
            'host': 'fhlrs232_a49.desy.de',
            'description': 'dustmeter on RS232-Ethernet bridge at somewhere',
        },
        {
            'name': 'dustmeter_a56',
            'index': 6,
            'host': 'fhlrs232_a56.desy.de',
            'description': 'dustmeter on RS232-Ethernet bridge at somewhere',
        },
    ]

    meters = []
    for info in meter_info:
        m = dustmeter.DustMeter(name=info['name'], host=info['host'])
        m.start()
        meters.append(m)

    objs = []
    for info in meter_info:
        ai_obj = AnalogInputObject(objectIdentifier=('analogInput', info['index']), \
                                   objectName=info['name'])
        ai_obj._values['description'] = CharacterString(info['description'])
        ai_obj._values['deviceType'] = CharacterString(
            'Particles(>0.5um) PerCubicFoot')
        ai_obj._values['units'] = EngineeringUnits('noUnits')
        ai_obj._values['updateInterval'] = Unsigned(60)
        ai_obj._values['resolution'] = Real(100)
        this_application.add_object(ai_obj)
        objs.append(ai_obj)

    mythread = dataThread(meters, objs)
    mythread.start()

    run()

    mythread.stop()
    mythread.join()
    for m in meters:
        m.stop()
        m.join()
    print "end of join"