Пример #1
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)
Пример #2
0
    def __init__(self, localIPAddr=None, localObjName='BAC0', Boid=None,
                 maxAPDULengthAccepted='1024', segmentationSupported='segmentedBoth'):
        """
        Initialization requires information about the local device
        Default values are localObjName = 'name', Boid = '2015',maxAPDULengthAccepted = '1024',segmentationSupported = 'segmentedBoth', vendorId = '842' )
        Local IP address must be given in a string.
        Normally, the address must be in the same subnet than the bacnet network (if no BBMD or Foreign device is used)
        Script doesn't support BBMD actually
        """
        log_debug("Configurating app")

        self.response = None
        self._initialized = False
        self._started = False
        self._stopped = False
        if localIPAddr:
            self.localIPAddr = localIPAddr
        else:
            self.localIPAddr = '127.0.0.1'
        self.segmentationSupported = segmentationSupported
        self.localObjName = localObjName
        if Boid:
            self.Boid = int(Boid)
        else:
            self.Boid = int('3056177') + int(random.uniform(0, 1000))
        self.maxAPDULengthAccepted = maxAPDULengthAccepted
        self.vendorId = '842'
        self.vendorName = CharacterString('SERVISYS inc.')
        self.modelName = CharacterString('BAC0 Scripting Tool')
        self.discoveredDevices = None
        self.ResponseQueue = Queue()
        self.systemStatus = DeviceStatus(1)

        self.startApp()
Пример #3
0
    def __init__(self, localIPAddr='127.0.0.1',
                 localObjName='BAC0', DeviceId=None,
                 maxAPDULengthAccepted='1024', maxSegmentsAccepted='1024',
                 segmentationSupported='segmentedBoth',
                 bbmdAddress=None, bbmdTTL=0):

        self._log.debug("Configurating app")

        self.response = None
        self._initialized = False
        self._started = False
        self._stopped = False

        self.localIPAddr = localIPAddr
        
        self.Boid = int(DeviceId) if DeviceId else (
            3056177 + int(random.uniform(0, 1000)))

        self.segmentationSupported = segmentationSupported
        self.maxSegmentsAccepted = maxSegmentsAccepted
        self.localObjName = localObjName

        self.maxAPDULengthAccepted = maxAPDULengthAccepted
        self.vendorId = 842
        self.vendorName = CharacterString('SERVISYS inc.')
        self.modelName = CharacterString('BAC0 Scripting Tool')

        self.discoveredDevices = None
        self.systemStatus = DeviceStatus(1)

        self.bbmdAddress = bbmdAddress
        self.bbmdTTL = bbmdTTL

        self.startApp()
Пример #4
0
    def __init__(self,
                 local_ip,
                 local_object_name='PyScada',
                 device_id=None,
                 max_APDU_length_accepted='1024',
                 max_segments_accepted='1024',
                 segmentation_supported='segmentedBoth',
                 bbmd_address=None,
                 bbmd_TTL=0,
                 *args):

        if _debug: logger.debug("__init__ %r", args)
        self.this_device = None
        self.this_application = None

        self.local_ip = local_ip
        self.local_object_name = local_object_name
        self.boid = int(device_id) if device_id else (
            3056177 + int(random.uniform(0, 1000)))
        self.vendor_id = 0
        self.vendor_name = CharacterString('PyScada')
        self.model_name = CharacterString('BACnet DAQ Service')
        self.system_status = DeviceStatus(1)
        self.max_APDU_length_accepted = max_APDU_length_accepted
        self.max_segments_accepted = max_segments_accepted
        self.segmentation_supported = segmentation_supported
        self.bbmd_address = bbmd_address
        self.bbmd_TTL = bbmd_TTL
        self.t = None
Пример #5
0
    def test_character_string(self):
        if _debug: TestCharacterString._debug("test_character_string")

        obj = CharacterString()
        assert obj.value == ''

        with self.assertRaises(TypeError):
            CharacterString(1)
        with self.assertRaises(TypeError):
            CharacterString(1.0)
Пример #6
0
    def __init__(
        self,
        localIPAddr="127.0.0.1",
        localObjName="BAC0",
        DeviceId=None,
        maxAPDULengthAccepted="1024",
        maxSegmentsAccepted="1024",
        segmentationSupported="segmentedBoth",
        bbmdAddress=None,
        bbmdTTL=0,
    ):

        self._log.debug("Configurating app")

        self.response = None
        self._initialized = False
        self._started = False
        self._stopped = False

        if localIPAddr in Base._used_ips:
            raise InitializationError(
                "IP Address provided ({}) already used.".format(localIPAddr))

        if validate_ip_address(localIPAddr):
            self.localIPAddr = localIPAddr
        else:
            raise InitializationError(
                "IP Address provided ({}) invalid.".format(localIPAddr))

        self.Boid = (int(DeviceId) if DeviceId else
                     (3056177 + int(random.uniform(0, 1000))))

        self.segmentationSupported = segmentationSupported
        self.maxSegmentsAccepted = maxSegmentsAccepted
        self.localObjName = localObjName

        self.maxAPDULengthAccepted = maxAPDULengthAccepted
        self.vendorId = 842
        self.vendorName = CharacterString("SERVISYS inc.")
        self.modelName = CharacterString("BAC0 Scripting Tool")

        self.discoveredDevices = None
        self.systemStatus = DeviceStatus(1)

        self.bbmdAddress = bbmdAddress
        self.bbmdTTL = bbmdTTL

        try:
            self.startApp()
        except InitializationError as error:
            raise InitializationError("Gros probleme : {}".format(error))
def character_string_decode(tag):
    """Decode an character_string application tag into an character_string."""
    if _debug: character_string_decode._debug("character_string_decode %r", tag)

    obj = CharacterString(tag)
    if _debug: character_string_decode._debug("    - obj: %r", obj)

    return obj
Пример #8
0
def create(object_type, instance, objectName, presentValue, description):
    new_object = object_type(
        objectIdentifier=(object_type.objectType, instance),
        objectName="{}".format(objectName),
        presentValue=presentValue,
        description=CharacterString("{}".format(presentValue)),
    )
    return new_object
Пример #9
0
    def test_character_string_endec(self):
        if _debug: TestCharacterString._debug("test_character_string_endec")

        with self.assertRaises(InvalidTag):
            obj = CharacterString(character_string_tag(''))

        character_string_endec("", '00')
        character_string_endec("abc", '00616263')
    def test_character_string_tag(self):
        if _debug: TestCharacterString._debug("test_character_string_tag")

        tag = Tag(Tag.applicationTagClass, Tag.characterStringAppTag, 1, xtob('00'))
        obj = CharacterString(tag)
        assert obj.value == ''

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

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

        tag = Tag(Tag.openingTagClass, 0)
        with self.assertRaises(InvalidTag):
            CharacterString(tag)
Пример #11
0
    def test_character_string_unicode_with_latin(self):
        if _debug:
            TestCharacterString._debug(
                "test_character_string_unicode_with_latin")
        # some controllers encoding character string mixing latin-1 and utf-8
        # try to cover those cases without failing
        b = xtob('0030b043')  # zero degress celsius
        tag = Tag(Tag.applicationTagClass, Tag.characterStringAppTag, len(b),
                  b)
        obj = CharacterString()
        obj.decode(tag)
        assert str(obj) == "CharacterString(0,X'30b043')"

        if sys.version_info[0] == 2:
            assert obj.value == "0C"  # degree symbol dropped, see unicodedata.normalize()
        elif sys.version_info[0] == 3:
            assert obj.value == "0°C"
        else:
            raise RuntimeError("unsupported version")
Пример #12
0
def character_string_statement(value):
    if _debug: character_string_statement._debug("character_string_statement %r", value)

    # chop off the encoding
    encoding = None
    if value and value[0].isdigit():
        encoding, value = value.split(' ', 1)
        value = value.strip()
        if _debug: ExtendedTagList._debug("    - encoding: %r", encoding)

    # chop off the quotes
    if value:
        value = value[1:-1]

    element = CharacterString(value)
    if encoding:
        element.strEncoding = int(encoding)

    return element
Пример #13
0
    def whohas(
        self,
        object_id=None,
        object_name=None,
        instance_range_low_limit=0,
        instance_range_high_limit=4194303,
        destination=None,
        global_broadcast=False,
    ):
        """
        Object ID : analogInput:1
        Object Name : string
        Instance Range Low Limit : 0
        Instance Range High Limit : 4194303
        destination (optional) : If empty, local broadcast will be used.
        global_broadcast : False

        """
        obj_id = ObjectIdentifier(object_id)
        if object_name and not object_id:
            obj_name = CharacterString(object_name)
            obj = WhoHasObject(objectName=obj_name)
        elif object_id and not object_name:
            obj = WhoHasObject(objectIdentifier=obj_id)
        else:
            obj = WhoHasObject(objectIdentifier=obj_id, objectName=obj_name)
        limits = WhoHasLimits(
            deviceInstanceRangeLowLimit=instance_range_low_limit,
            deviceInstanceRangeHighLimit=instance_range_high_limit,
        )
        request = WhoHasRequest(object=obj, limits=limits)
        if destination:
            request.pduDestination = Address(destination)
        else:
            if global_broadcast:
                request.pduDestination = GlobalBroadcast()
            else:
                request.pduDestination = LocalBroadcast()
        iocb = IOCB(request)  # make an IOCB
        iocb.set_timeout(2)
        deferred(self.this_application.request_io, iocb)
        iocb.wait()

        iocb = IOCB(request)  # make an IOCB
        self.this_application._last_i_have_received = []

        if iocb.ioResponse:  # successful response
            apdu = iocb.ioResponse

        if iocb.ioError:  # unsuccessful: error/reject/abort
            pass

        time.sleep(3)
        # self.discoveredObjects = self.this_application.i_am_counter
        return self.this_application._last_i_have_received
Пример #14
0
def create_CharStrValue(oid=1, pv="null", name="String", pv_writable=False):
    charval = CharacterStringValueObject(
        objectIdentifier=("characterstringValue", oid),
        objectName=name,
        priorityArray=PriorityArray(),
        statusFlags=StatusFlags(),
    )
    charval = _make_mutable(charval, mutable=pv_writable)
    charval.presentValue = CharacterString(pv)
    deprecate_msg()
    return charval
    def dcc(self, address=None, duration=None, password=None, state=None):
        """
        Will send DeviceCommunicationControl request
        """
        if not self._started:
            raise ApplicationNotStarted(
                "BACnet stack not running - use startApp()")

        if not address:
            raise ValueError("Provide address for request")

        if not state:
            raise ValueError(
                "Provide state ('enable', 'disable', 'disableInitiation'")

        # build a request
        request = DeviceCommunicationControlRequest()
        request.enableDisable = DeviceCommunicationControlRequestEnableDisable.enumerations[
            state]
        request.pduDestination = Address(address)
        if duration:
            request.duration = Unsigned16(duration)

        request.password = CharacterString(password)

        self._log.debug("{:>12} {}".format("- request:", request))

        iocb = IOCB(request)  # make an IOCB

        # pass to the BACnet stack
        deferred(self.this_application.request_io, iocb)

        # Unconfirmed request...so wait until complete
        iocb.wait()  # Wait for BACnet response

        if iocb.ioResponse:  # successful response
            apdu = iocb.ioResponse

            if not isinstance(apdu, SimpleAckPDU):  # expect an ACK
                self._log.warning("Not an ack, see debug for more infos.")
                self._log.debug("Not an ack. | APDU : {} / {}".format(
                    (apdu, type(apdu))))
                return

        if iocb.ioError:  # unsuccessful: error/reject/abort
            apdu = iocb.ioError
            reason = find_reason(apdu)
            raise NoResponseFromController(
                "APDU Abort Reason : {}".format(reason))

        self._log.info(
            "DeviceCommunicationControl request sent to device : {}".format(
                address))
Пример #16
0
def character_string_statement(value):
    if _debug:
        character_string_statement._debug("character_string_statement %r",
                                          value)

    # chop off the encoding
    encoding = None
    if value and value[0].isdigit():
        encoding, value = value.split(' ', 1)
        value = value.strip()
        if _debug: ExtendedTagList._debug("    - encoding: %r", encoding)

    # chop off the quotes
    if value:
        value = value[1:-1]

    element = CharacterString(value)
    if encoding:
        element.strEncoding = int(encoding)

    return element
Пример #17
0
    def _add_points(qty, device):
        # Add a lot of points for tests (segmentation required)
        mvs = []
        avs = []
        bvs = []
        ais = []
        bis = []
        aos = []
        bos = []
        charstr = []

        for i in range(qty):
            mvs.append(
                create_MV(oid=i, name="mv{}".format(i), pv=1,
                          pv_writable=True))
            new_av = create_AV(oid=i,
                               name="av{}".format(i),
                               pv=99.9,
                               pv_writable=True)
            new_av.units = EngineeringUnits.enumerations["degreesCelsius"]
            new_av.description = "Fake Description {}".format(i)
            avs.append(new_av)
            bvs.append(
                create_BV(oid=i, name="bv{}".format(i), pv=1,
                          pv_writable=True))
            ais.append(create_AI(oid=i, name="ai{}".format(i), pv=99.9))
            aos.append(create_AO(oid=i, name="ao{}".format(i), pv=99.9))
            bis.append(create_BI(oid=i, name="bi{}".format(i), pv=1))
            bos.append(create_BO(oid=i, name="bo{}".format(i), pv=1))
            charstr.append(
                create_CharStrValue(
                    oid=i,
                    name="string{}".format(i),
                    pv=CharacterString("test"),
                    pv_writable=True,
                ))

        for mv in mvs:
            device.this_application.add_object(mv)
        for av in avs:
            device.this_application.add_object(av)
        for bv in bvs:
            device.this_application.add_object(bv)
        for ai in ais:
            device.this_application.add_object(ai)
        for ao in aos:
            device.this_application.add_object(ao)
        for bi in bis:
            device.this_application.add_object(bi)
        for bo in bos:
            device.this_application.add_object(bo)
        for cs in charstr:
            device.this_application.add_object(cs)
Пример #18
0
    def connect(self, bacnet_server):
        address = self._ip_address(bacnet_server)
        version = get_version()
        description = "nube-io bacnet server"
        self.ldo = LocalDeviceObject(
            objectName=bacnet_server.local_obj_name,
            objectIdentifier=int(bacnet_server.device_id),
            maxApduLengthAccepted=1024,
            segmentationSupported="segmentedBoth",
            vendorIdentifier=bacnet_server.vendor_id,
            firmwareRevision=CharacterString(version),
            modelName=CharacterString(bacnet_server.model_name),
            vendorName=CharacterString(bacnet_server.vendor_name),
            description=CharacterString(description),
            systemStatus=DeviceStatus(1),
            applicationSoftwareVersion=CharacterString(version),
            databaseRevision=0)

        self.__bacnet = BIPSimpleApplication(self.ldo, address)
        self.__bacnet.add_capability(ReadWritePropertyMultipleServices)
        self.sync_stack()
        FlaskThread(target=bacnet_run).start()  # start bacpypes thread
def character_string_endec(v, x):
    """Pass the value to CharacterString, construct a tag from the hex string,
    and compare results of encode and decoding each other."""
    if _debug: character_string_endec._debug("character_string_endec %r %r", v, x)

    tag = character_string_tag(x)
    if _debug: character_string_endec._debug("    - tag: %r, %r", tag, tag.tagData)

    obj = CharacterString(v)
    if _debug: character_string_endec._debug("    - obj: %r, %r", obj, obj.value)

    assert character_string_encode(obj) == tag
    assert character_string_decode(tag) == obj
Пример #20
0
 def build_binary(self, input_device, input_dev_point):
     self.input_device = input_device
     self.input_dev_point = input_dev_point
     register_object_type(BinaryValueCmdObject, vendor_id=842)
     bv_object = BinaryValueCmdObject(
         objectIdentifier=("binaryValue", BAC0_Converter.binary_value_num),
         objectName=self.input_dev_point,
         presentValue='inactive',
         description=CharacterString(
             f"imported from {self.input_device}: {self.input_dev_point} "))
     BAC0_Converter.binary_value_num += 1
     BAC0_Converter.binary_value_list.append(bv_object)
     self.device.this_application.add_object(bv_object)
     return bv_object
Пример #21
0
 def build_analog(self, input_device, input_dev_point):
     global objects
     self.input_device = input_device
     self.input_dev_point = input_dev_point
     register_object_type(AnalogValueCmdObject, vendor_id=842)
     av_object = AnalogValueCmdObject(
         objectIdentifier=("analogValue", BAC0_Converter.analog_value_num),
         objectName=self.input_dev_point,
         presentValue=666,
         description=CharacterString(
             f"imported from {self.input_device}: {self.input_dev_point} "))
     BAC0_Converter.analog_value_num += 1
     BAC0_Converter.analog_value_list.append(av_object)
     self.device.this_application.add_object(av_object)
     return av_object
Пример #22
0
    def build_text_write_request(self,
                                 addr,
                                 obj_type,
                                 obj_inst,
                                 value,
                                 prop_id="description"):
        request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst),
                                       propertyIdentifier=prop_id)
        request.pduDestination = Address(addr)

        _value = Any()
        _value.cast_in(CharacterString(value))
        request.propertyValue = _value

        return request
Пример #23
0
def create_object(object_class,
                  oid,
                  objectName,
                  description,
                  presentValue=None,
                  commandable=False):
    new_object = object_class(
        objectIdentifier=(object_class.objectType, oid),
        objectName="{}".format(objectName),
        presentValue=presentValue,
        description=CharacterString("{}".format(description)),
        statusFlags=StatusFlags(),
    )
    deprecate_msg()
    return _make_mutable(new_object, mutable=commandable)
Пример #24
0
 def wrapper(*args, **kwargs):
     if callable(func):
         obj = func(*args, **kwargs)
     else:
         obj = func
     base_cls = obj.__class__
     base_cls_name = obj.__class__.__name__ + cls.__name__
     new_type = type(base_cls_name, (cls, base_cls), {})
     register_object_type(new_type, vendor_id=842)
     instance, objectName, presentValue, description = args
     new_object = new_type(
         objectIdentifier=(base_cls.objectType, instance),
         objectName="{}".format(objectName),
         presentValue=presentValue,
         description=CharacterString("{}".format(description)),
     )
     return new_object
Пример #25
0
def create_object_list(objects_dict):
    """
    d = {name: (name, description, presentValue, units, commandable)}
    """
    obj_list = []
    for obj_id, v in objects_dict.items():
        object_class, name, oid, description, presentValue, commandable = v
        description = CharacterString(description)
        new_obj = create_object(object_class,
                                name,
                                oid,
                                description,
                                commandable=commandable)
        if presentValue:
            new_obj.presentValue = presentValue
        obj_list.append(new_obj)
    return obj_list
Пример #26
0
 def wrapper(*args, **kwargs):
     if callable(func):
         obj = func(*args, **kwargs)
     else:
         obj = func
     allowed_prop = _allowed_prop(obj)
     _type = allowed_prop["presentValue"]
     _commando = Commandable(_type)
     base_cls = obj.__class__
     base_cls_name = obj.__class__.__name__ + "Cmd"
     new_type = type(base_cls_name, (_commando, base_cls), {})
     new_type.__name__ = base_cls_name
     register_object_type(new_type, vendor_id=842)
     objectType, instance, objectName, presentValue, description = args
     new_object = new_type(
         objectIdentifier=(base_cls.objectType, instance),
         objectName="{}".format(objectName),
         presentValue=presentValue,
         description=CharacterString("{}".format(description)),
     )
     return new_object
Пример #27
0
    def __init__(
        self,
        localIPAddr="127.0.0.1",
        localObjName="BAC0",
        deviceId=None,
        firmwareRevision="".join(sys.version.split("|")[:2]),
        maxAPDULengthAccepted="1024",
        maxSegmentsAccepted="1024",
        segmentationSupported="segmentedBoth",
        bbmdAddress=None,
        bbmdTTL=0,
        bdtable=None,
        modelName=CharacterString("BAC0 Scripting Tool"),
        vendorId=842,
        vendorName=CharacterString("SERVISYS inc."),
        description=CharacterString(
            "http://christiantremblay.github.io/BAC0/"),
    ):

        self._log.debug("Configurating app")

        if not _COMPLETE:
            self._log.debug(
                "To be able to run the web server, you must install pandas, bokeh, flask and flask_bootstrap"
            )
            self._log.debug(
                "Those are not all installed so BAC0 will work in Lite mode only."
            )

        self.response = None
        self._initialized = False
        self._started = False
        self._stopped = False

        if localIPAddr in Base._used_ips:
            raise InitializationError(
                "IP Address provided ({}) already used by BAC0. Check if another software is using port 47808 on this network interface. If so, you can define multiple IP per interface. Or specify another IP using BAC0.lite(ip='IP/mask')"
                .format(localIPAddr))

        if validate_ip_address(localIPAddr):
            self.localIPAddr = localIPAddr
        else:
            raise InitializationError(
                "IP Address provided ({}) invalid. Check if another software is using port 47808 on this network interface. If so, you can define multiple IP per interface. Or specify another IP using BAC0.lite(ip='IP/mask')"
                .format(localIPAddr))

        self.Boid = (int(deviceId) if deviceId else
                     (3056177 + int(random.uniform(0, 1000))))

        self.segmentationSupported = segmentationSupported
        self.maxSegmentsAccepted = maxSegmentsAccepted
        self.localObjName = localObjName
        self.local_objects = LocalObjects(device=self)

        self.maxAPDULengthAccepted = maxAPDULengthAccepted
        self.vendorId = vendorId
        self.vendorName = vendorName
        self.modelName = modelName
        self.description = description

        self.discoveredDevices = None
        self.systemStatus = DeviceStatus(1)

        self.bbmdAddress = bbmdAddress
        self.bbmdTTL = bbmdTTL
        self.bdtable = bdtable

        self.firmwareRevision = firmwareRevision
        self._ric = {}
        self.subscription_contexts = {}

        try:
            self.startApp()
        except InitializationError as error:
            raise InitializationError(
                "Gros probleme : {}. Address requested : {}".format(
                    error, localIPAddr))
    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)
Пример #29
0
#!/usr/bin/env python
# -*- coding utf-8 -*-

"""
Test Bacnet communication with another device
"""

from bacpypes.primitivedata import CharacterString

NEWCSVALUE = CharacterString("New_Test")


def test_WriteAV(network_and_devices):
    # Write to an object and validate new value is correct
    test_device = network_and_devices.test_device
    old_value = test_device["av0"].value
    test_device["av0"] = 11.2
    new_value = test_device["av0"].value
    assert (new_value - 11.2) < 0.01


def test_RelinquishDefault(network_and_devices):
    # Write to an object and validate new value is correct
    test_device = network_and_devices.test_device
    old_value = test_device["av0"].value
    test_device["av0"].default(90)
    new_value = test_device["av0"].value
    assert (new_value - 90) < 0.01


def test_WriteCharStr(network_and_devices):
Пример #30
0
def start_device():
    print("Starting BACnet device")
    new_device = BAC0.lite()
    new_device._log.info('Device ID : {}'.format(new_device.Boid))
    time.sleep(10)

    default_pv = CharacterString("empty")

    current_humidity = create_AV(oid=0,
                                 name="Current_Humidity",
                                 pv=0,
                                 pv_writable=False)
    current_humidity.units = EngineeringUnits("percent")
    current_humidity.description = CharacterString(
        "Current Humidity in percent relative humidity")

    current_temp = create_AV(oid=1,
                             name="Current_Temp",
                             pv=0,
                             pv_writable=False)
    current_temp.units = EngineeringUnits("degreesFahrenheit")
    current_temp.description = CharacterString("Current Temperature in degF")

    current_windspd = create_AV(oid=2,
                                name="Current_Wind_Speed",
                                pv=0,
                                pv_writable=False)
    current_windspd.units = EngineeringUnits("milesPerHour")
    current_windspd.description = CharacterString("Current Wind Speed")

    current_winddir = create_CharStrValue(oid=3,
                                          name="Current_Wind_Dir",
                                          pv=default_pv,
                                          pv_writable=False)
    current_winddir.description = CharacterString("Wind Direction String")

    current_pressure = create_AV(oid=4,
                                 name="Current_Pressure",
                                 pv=0,
                                 pv_writable=False)
    current_pressure.units = EngineeringUnits("hectopascals")
    current_pressure.description = CharacterString(
        "Current Barometric Pressure")

    current_cloudcov = create_AV(oid=5,
                                 name="Current_Cloud_Cover",
                                 pv=0,
                                 pv_writable=False)
    current_cloudcov.units = EngineeringUnits("percent")
    current_cloudcov.description = CharacterString(
        "Current Cloud Cover in Percent")

    last_update = create_DateTimeValue(oid=1, name="Last_Update")
    last_update.description = CharacterString("Last update timestamp")

    current_location = create_CharStrValue(oid=8,
                                           name="Weather_Station_City",
                                           pv=default_pv)
    current_location.description = CharacterString(
        "Location of Weather Station")

    current_description = create_CharStrValue(
        oid=9, name="Current_Weather_Description", pv=default_pv)
    current_description.description = CharacterString(
        "Weather Station Description String")

    current_dewpoint = create_AV(oid=10,
                                 name="Current_Dewpoint",
                                 pv=0,
                                 pv_writable=False)
    current_dewpoint.units = EngineeringUnits("degreesFahrenheit")
    current_dewpoint.description = CharacterString("Current Outdoor Dewpoint")

    new_device.this_application.add_object(current_humidity)
    new_device.this_application.add_object(current_temp)
    new_device.this_application.add_object(current_windspd)
    new_device.this_application.add_object(current_winddir)
    new_device.this_application.add_object(current_pressure)
    new_device.this_application.add_object(current_cloudcov)
    new_device.this_application.add_object(last_update)
    new_device.this_application.add_object(current_location)
    new_device.this_application.add_object(current_description)
    new_device.this_application.add_object(current_dewpoint)

    return new_device
Пример #31
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')