示例#1
0
def create_MV(oid=1, pv=0, name='MV', states=['red', 'green', 'blue']):
    msvo = MultiStateValueObject(objectIdentifier=('multiStateValue', oid),
                                 objectName=name,
                                 presentValue=pv,
                                 numberOfStates=len(states),
                                 stateText=ArrayOf(CharacterString)(states))
    return msvo
示例#2
0
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).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)

    # make a multistate value object
    msvo = MultiStateValueObject(
        objectIdentifier=('multiStateValue', 1),
        objectName='My Special Object',
        presentValue=1,
        numberOfStates=3,
        stateText=ArrayOf(CharacterString)(['red', 'green', 'blue']),
        )
    _log.debug("    - msvo: %r", msvo)

    # add it to the device
    this_application.add_object(msvo)
    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")
    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
示例#4
0
    def _register_vav_objs(self, vav_id, zone_id):
        for idx, obj_template in enumerate(vav_point_templates):
            idx += 1
            obj_point_type = None
            for point_type_rule, point_type in point_type_rules.items():
                if point_type_rule in obj_template :
                    obj_point_type = point_type
            assert obj_point_type

            obj_value_type = None
            for value_type_rule, value_type in value_type_rules.items():
                if value_type_rule in obj_template :
                    obj_value_type = value_type
            assert obj_value_type
            obj_typestr = obj_value_type + obj_point_type
            obj_cls = eval('Random{0}Object'.format(obj_typestr))
            name_values = [NameValue(name=name_template, value=CharacterString(value_template))
                           for (name_template, value_template) in obj_template]
            name_values.append(NameValue(name='brick:isPointOf', value=CharacterString(vav_id)))
            name_values.append(NameValue(name='brick:isPointOf', value=CharacterString(zone_id)))
            tags = ArrayOf(NameValue)(name_values)
            obj = obj_cls(
                objectIdentifier=idx + 10,
                objectName='Random{0}-{1}'.format(obj_cls.__name__, idx),
                tags=tags,
            )
            self.add_object(obj)
示例#5
0
def create_MV(oid=1, pv=0, name="MV", states=["red", "green", "blue"]):
    msvo = MultiStateValueObject(
        objectIdentifier=("multiStateValue", oid),
        objectName=name,
        presentValue=pv,
        numberOfStates=len(states),
        stateText=ArrayOf(CharacterString)(states),
    )
    return msvo
class RandomAnalogValueObject(AnalogValueObject):

    properties = [
        RandomValueProperty('presentValue'),
        Property('eventMessageTexts', ArrayOf(CharacterString), mutable=True),
    ]

    def __init__(self, **kwargs):
        if _debug: RandomAnalogValueObject._debug("__init__ %r", kwargs)
        AnalogValueObject.__init__(self, **kwargs)
示例#7
0
class MyScheduleObject(ScheduleObject):

    properties = [
        WritableProperty('weeklySchedule', ArrayOf(DailySchedule)),
        WritableProperty('priorityForWriting', Unsigned),
    ]

    def __init__(self, **kwargs):
        if _debug: MyScheduleObject._debug("__init__ %r", kwargs)
        ScheduleObject.__init__(self, **kwargs)
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()
示例#9
0
 def _got_sensors_for_device(self, iocb):
     if iocb.ioError:
         print(
             "error (%s) when attempting to get objectList of device (%s)" %
             (str(iocb.ioError), iocb.pduSource))
     else:
         apdu = iocb.ioResponse
         new_sensors = apdu.propertyValue.cast_out(
             ArrayOf(ObjectIdentifier))
         self.bacnet_adapter.bacnet_sensors.add_new_sensors_from_device(
             new_sensors, self.devices[str(apdu.pduSource)])
示例#10
0
 def _got_object_list(self, iocb):
     if iocb.ioError:
         print("error (%s) when attempting to get object-list of device (%s)", str(iocb.ioError), self.id)
     elif iocb.ioResponse:
         apdu = iocb.ioResponse
         if not isinstance(apdu, ReadPropertyACK):
             print("response was not ReadPropertyACK as expected")
             return
         obj_list = apdu.propertyValue.cast_out(ArrayOf(ObjectIdentifier))
         self.object_list = ObjectList(obj_list, self, self.bacnet_adapter)
         self.object_list.get_properties_for_each_object()
示例#11
0
 def _got_properties_for_object(self, iocb, object_id):
     if iocb.ioError:
         print("error getting property list: %s", str(iocb.ioError))
         return
     elif iocb.ioResponse:
         apdu = iocb.ioResponse
         if not isinstance(apdu, ReadPropertyACK):
             print("response was not ReadPropertyACK")
             return
         self.prop_list_for_obj[object_id] = PropertyList(
             apdu.propertyValue.cast_out(ArrayOf(PropertyIdentifier)),
             object_id, self.device, self.bacnet_adapter)
         self.prop_list_for_obj[object_id].get_values_for_properties()
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

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

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
        _dcc_password="******",
    )

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

    # make a random input object
    ravo1 = RandomAnalogValueObject(
        objectIdentifier=('analogValue', 1),
        objectName='Random1',
        eventMessageTexts=ArrayOf(CharacterString)(["hello"]),
    )
    _log.debug("    - ravo1: %r", ravo1)

    ravo2 = RandomAnalogValueObject(objectIdentifier=('analogValue', 2),
                                    objectName='Random2')
    _log.debug("    - ravo2: %r", ravo2)

    # add it to the device
    this_application.add_object(ravo1)
    this_application.add_object(ravo2)
    _log.debug("    - object list: %r", this_device.objectList)

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value

    _log.debug("running")

    run()

    _log.debug("fini")
示例#13
0
def create_MV(oid=1,
              pv=0,
              name="MV",
              states=["red", "green", "blue"],
              pv_writable=False):
    msvo = MultiStateValueObject(
        objectIdentifier=("multiStateValue", oid),
        objectName=name,
        presentValue=pv,
        numberOfStates=len(states),
        stateText=ArrayOf(CharacterString)(states),
        priorityArray=PriorityArray(),
    )
    msvo = _make_mutable(msvo, mutable=pv_writable)
    return msvo
示例#14
0
文件: api.py 项目: hdqlife/blink
 def readBack(self,iocb):
     apdu=iocb.ioResponse
     if not isinstance(apdu, ReadPropertyACK):return
     if iocb.context[1]=='objectList':
         value=apdu.propertyValue.cast_out(ArrayOf(ObjectIdentifier))
         value=["%s:%s"%(v[0],v[1]) for v in value]
     else:
         datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
         if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):
             if apdu.propertyArrayIndex == 0:
                 value = apdu.propertyValue.cast_out(Unsigned)
             else:
                 value = apdu.propertyValue.cast_out(datatype.subtype)
         else:
             value = apdu.propertyValue.cast_out(datatype)
     iocb.context[0][iocb.context[1]]=value
示例#15
0
文件: Read.py 项目: gnmerritt/BAC0
def cast_datatype_from_tag(propertyValue, obj_id, prop_id):
    try:
        tag_list = propertyValue.tagList.tagList
        if tag_list[0].tagClass == 0:
            tag = tag_list[0].tagNumber

            datatype = Tag._app_tag_class[tag]
        else:
            from bacpypes.constructeddata import ArrayOf

            subtype_tag = propertyValue.tagList.tagList[0].tagList[0].tagNumber
            datatype = ArrayOf(Tag._app_tag_class[subtype_tag])
        value = {"{}_{}".format(obj_id, prop_id): propertyValue.cast_out(datatype)}
    except:
        value = {"{}_{}".format(obj_id, prop_id): propertyValue}
    return value
示例#16
0
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

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

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=int(args.ini.objectidentifier),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),
    )

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

    # get the services supported
    services_supported = this_application.get_services_supported()
    if _debug: _log.debug("    - services_supported: %r", services_supported)

    # let the device object know
    this_device.protocolServicesSupported = services_supported.value

    # make a multistate value object
    msvo = MultiStateValueObject(
        objectIdentifier=('multiStateValue', 1),
        objectName='My Special Object',
        presentValue=1,
        numberOfStates=3,
        stateText=ArrayOf(CharacterString)(['red', 'green', 'blue']),
    )
    _log.debug("    - msvo: %r", msvo)

    # add it to the device
    this_application.add_object(msvo)
    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

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

    # make a device object
    mstp_args = {
        '_address': int(args.ini.address),
        '_interface': str(args.ini.interface),
        '_max_masters': int(args.ini.max_masters),
        '_baudrate': int(args.ini.baudrate),
        '_maxinfo': int(args.ini.maxinfo),
    }
    this_device = LocalDeviceObject(ini=args.ini, **mstp_args)
    if _debug: _log.debug("    - this_device: %r", this_device)

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

    # make a random input object
    ravo1 = RandomAnalogValueObject(
        objectIdentifier=('analogValue', 1),
        objectName='Random1',
        eventMessageTexts=ArrayOf(CharacterString)(
            ["to", "infinity", "and", "beyond"]),
    )
    _log.debug("    - ravo1: %r", ravo1)

    ravo2 = RandomAnalogValueObject(objectIdentifier=('analogValue', 2),
                                    objectName='Random2')
    _log.debug("    - ravo2: %r", ravo2)

    # add it to the device
    this_application.add_object(ravo1)
    this_application.add_object(ravo2)
    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")
示例#18
0
 def __property_value_from_apdu(apdu: APDU):
     tag_list = apdu.propertyValue.tagList
     non_app_tags = [
         tag for tag in tag_list if tag.tagClass != Tag.applicationTagClass
     ]
     if non_app_tags:
         raise RuntimeError("Value has some non-application tags")
     first_tag = tag_list[0]
     other_type_tags = [
         tag for tag in tag_list[1:] if tag.tagNumber != first_tag.tagNumber
     ]
     if other_type_tags:
         raise RuntimeError("All tags must be the same type")
     datatype = Tag._app_tag_class[first_tag.tagNumber]
     if not datatype:
         raise RuntimeError("unknown datatype")
     if len(tag_list) > 1:
         datatype = ArrayOf(datatype)
     value = apdu.propertyValue.cast_out(datatype)
     return value
示例#19
0
def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).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 = ReadPropertyMultipleApplication(this_device,
                                                       args.ini.address)

    # make a random input object
    ravo1 = RandomAnalogValueObject(
        objectIdentifier=('analogValue', 1),
        objectName='Random1',
        eventMessageTexts=ArrayOf(CharacterString)(["hello"]),
    )
    _log.debug("    - ravo1: %r", ravo1)

    ravo2 = RandomAnalogValueObject(objectIdentifier=('analogValue', 2),
                                    objectName='Random2')
    _log.debug("    - ravo2: %r", ravo2)

    # add it to the device
    this_application.add_object(ravo1)
    this_application.add_object(ravo2)
    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")
示例#20
0
def make_state_text(list_of_string):
    _arr = ArrayOf(CharacterString)
    _lst = [CharacterString(each) for each in list_of_string]
    return _arr(_lst)
示例#21
0
        # not an array, write access denied
        with self.assertRaises(ExecutionError):
            obj.ReadProperty('location', 0)

        # write access successful
        obj.WriteProperty('location', "work")
        assert obj.location == "work"

        # wrong data type
        with self.assertRaises(InvalidParameterDatatype):
            obj.WriteProperty('location', 12)


# array of character strings
ArrayOfCharacterString = ArrayOf(CharacterString)


@bacpypes_debugging
@register_object_type(vendor_id=999)
class SampleWritableArray(Object):

    objectType = 'sampleWritableLocation'
    properties = [
        WritableProperty('location', ArrayOfCharacterString),
    ]

    def __init__(self, **kwargs):
        if _debug: SampleWritableArray._debug("__init__ %r", kwargs)
        Object.__init__(self, **kwargs)
示例#22
0
import unittest

from bacpypes.debugging import bacpypes_debugging, ModuleLogger, xtob

from bacpypes.errors import MissingRequiredParameter
from bacpypes.primitivedata import Integer, Tag, TagList
from bacpypes.constructeddata import Element, Sequence, ArrayOf

from .helpers import SimpleSequence

# some debugging
_debug = 0
_log = ModuleLogger(globals())

# array of integers
IntegerArray = ArrayOf(Integer)


@bacpypes_debugging
class TestIntegerArray(unittest.TestCase):
    def test_empty_array(self):
        if _debug: TestIntegerArray._debug("test_empty_array")

        # create an empty array
        ary = IntegerArray()
        if _debug: TestIntegerArray._debug("    - ary: %r", ary)

        # array sematics
        assert len(ary) == 0
        assert ary[0] == 0
    def do_write(self, args):
        """
        write <indx> <value>
        write 0 <len>
        write [ <value> ]...
        """
        args = args.split()
        ReadWritePropertyConsoleCmd._debug("do_write %r", args)

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

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

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

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

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

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

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

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

            # wait for it to complete
            iocb.wait()

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

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

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

        except Exception as error:
            ReadWritePropertyConsoleCmd._exception("exception: %r", error)
示例#24
0
    def do_read(self, args):
        """read <addr> <objid> <prop> [ <indx> ]"""
        args = args.split()
        if _debug: ReadPropertyAnyConsoleCmd._debug("do_read %r", args)

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

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

            if len(args) == 4:
                request.propertyArrayIndex = int(args[3])
            if _debug:
                ReadPropertyAnyConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: ReadPropertyAnyConsoleCmd._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:
                apdu = iocb.ioResponse
                if _debug:
                    ReadPropertyAnyConsoleCmd._debug("    - apdu: %r", apdu)

                try:
                    tag_list = apdu.propertyValue.tagList

                    # all tags application encoded
                    non_app_tags = [
                        tag for tag in tag_list
                        if tag.tagClass != Tag.applicationTagClass
                    ]
                    if non_app_tags:
                        raise RuntimeError(
                            "value has some non-application tags")

                    # all the same type
                    first_tag = tag_list[0]
                    other_type_tags = [
                        tag for tag in tag_list[1:]
                        if tag.tagNumber != first_tag.tagNumber
                    ]
                    if other_type_tags:
                        raise RuntimeError(
                            "all the tags must be the same type")

                    # find the datatype
                    datatype = Tag._app_tag_class[first_tag.tagNumber]
                    if _debug:
                        ReadPropertyAnyConsoleCmd._debug(
                            "    - datatype: %r", datatype)
                    if not datatype:
                        raise RuntimeError("unknown datatype")

                    # more than one then it's an array of these
                    if len(tag_list) > 1:
                        datatype = ArrayOf(datatype)
                        if _debug:
                            ReadPropertyAnyConsoleCmd._debug(
                                "    - array: %r", datatype)

                    # cast out the value
                    value = apdu.propertyValue.cast_out(datatype)
                    if _debug:
                        ReadPropertyAnyConsoleCmd._debug(
                            "    - value: %r", value)

                    sys.stdout.write("%s (%s)\n" % (value, datatype))
                except RuntimeError as err:
                    sys.stdout.write("error: %s\n" % (err, ))

                sys.stdout.flush()

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

        except Exception as error:
            ReadPropertyAnyConsoleCmd._exception("exception: %r", error)
class ModbusAnalogInputObject(Object):
    objectType = 'analogInput'
    properties = \
        [ReadableProperty('presentValue', Real),
         OptionalProperty('deviceType', CharacterString),
         OptionalProperty('profileLocation', CharacterString),
         ReadableProperty('statusFlags', StatusFlags),
         ReadableProperty('eventState', EventState),
         OptionalProperty('reliability', Reliability),
         ReadableProperty('outOfService', Boolean),
         OptionalProperty('updateInterval', Unsigned),
         ReadableProperty('units', EngineeringUnits),
         OptionalProperty('minPresValue', Real, mutable=True),
         OptionalProperty('maxPresValue', Real, mutable=True),
         OptionalProperty('resolution', Real),
         OptionalProperty('covIncrement', Real),
         # OptionalProperty('timeDelay', Unsigned),
         # OptionalProperty('notificationClass', Unsigned),
         # OptionalProperty('highLimit', Real),
         # OptionalProperty('lowLimit', Real),
         # OptionalProperty('deadband', Real),
         # OptionalProperty('limitEnable', LimitEnable),
         # OptionalProperty('eventEnable', EventTransitionBits),
         OptionalProperty('ackedTransitions', EventTransitionBits),
         # OptionalProperty('notifyType', NotifyType),
         # OptionalProperty('eventTimeStamps', ArrayOf(TimeStamp)),
         # OptionalProperty('eventMessageTexts', ArrayOf(CharacterString)),
         # OptionalProperty('eventMessageTextsConfig', ArrayOf(CharacterString)),
         # OptionalProperty('eventDetectionEnable', Boolean),
         # OptionalProperty('eventAlgorithmInhibitRef', ObjectPropertyReference),
         # OptionalProperty('eventAlgorithmInhibit', Boolean),
         # OptionalProperty('timeDelayNormal', Unsigned),
         # OptionalProperty('reliabilityEvaluationInhibit', Boolean)
         ReadableProperty('modbusFunction', ModbusFunctions),
         ReadableProperty('registerStart', Unsigned),
         ReadableProperty('numberOfRegisters', Unsigned),
         ReadableProperty('registerFormat', CharacterString),
         ReadableProperty('wordOrder', CharacterString),
         ReadableProperty('modbusScaling', ArrayOf(Real)),
         ReadableProperty('modbusCommErr', ModbusErrors)
         ]

    def __init__(self, **kwargs):
        if _debug: ModbusAnalogInputObject._debug("__init__ %r", kwargs)
        Object.__init__(self, **kwargs)

        # set unassigned properties to default values
        for propid, prop in self._properties.items():
            if prop.ReadProperty(
                    self) is None and propid in modbus_ai_obj_def_vals:
                if _debug:
                    ModbusAnalogInputObject._debug(
                        '%s %s was not set, default is %s', self.objectName,
                        propid, modbus_ai_obj_def_vals[propid])

                prop.WriteProperty(self,
                                   modbus_ai_obj_def_vals[propid],
                                   direct=True)

    def ReadProperty(self, propid, arrayIndex=None):
        # if _debug: ModbusAnalogInputObject._debug('BACnet REQUEST for (%s, %s)  at %s: %s %s',_strftime(decimal_places=3), propid,
        #                                           getattr(self, propid))  # might need self._values[propid]

        # if _debug: ModbusAnalogInputObject._debug('BACnet REQUEST for (%s, %s), (%s, %s): %s at %s',
        #                                           self._app._values['objectName'],
        #                                           self._app._values['objectIdentifier'], self._values['objectName'],
        #                                           self._values['objectIdentifier'], propid, _strftime(decimal_places=3))
        value = Object.ReadProperty(self, propid, arrayIndex=arrayIndex)
        # if _debug: ModbusAnalogInputObject._debug('BACnet REQUEST for (%s, %s), (%s, %s), %s= %s at %s',
        #                                           self._app.localDevice._values['objectName'],
        #                                           self._app.localDevice._values['objectIdentifier'][1],
        #                                           self._values['objectName'], self._values['objectIdentifier'][1],
        #                                           propid, value, _strftime(decimal_places=3))
        if _debug:
            ModbusAnalogInputObject._debug(
                'BACnet REQUEST for (%s, %s), (%s, %s), %s= %s at %s',
                self._app.localDevice.objectName,
                self._app.localDevice.objectIdentifier[1], self.objectName,
                self.objectIdentifier[1], propid, value,
                _strftime(decimal_places=3))
        return value
示例#26
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)),
                TimeValue(time=(10, 0, 0, 0), value=Null()),
示例#27
0
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")
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")
示例#29
0
from bacpypes.object import Object

from bacpypes.object import get_object_class

import asyncio

import json

_debug = 0
_log = ModuleLogger(globals())

this_device = None
this_application = None
query_output = asyncio.Future()

ArrayOfObjectIdentifier = ArrayOf(ObjectIdentifier)


class ObjectPropertyContext:
    def __init__(self, device_id, device_addr):
        self.device_id = device_id
        self.device_addr = device_addr

        self.object_list = []
        self.object_names = []

        self.current_object_id = None
        self.current_property = None

        self._object_list_queue = None
        self.propertyid_dict_queue = None
    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