def IntegerTag(v): """Return an application encoded integer tag with the appropriate value. """ obj = Integer(v) tag = Tag() obj.encode(tag) return tag
def test_integer_statement(self): if _debug: TestExtendedTagStatements._debug("test_integer_statement") assert statement_to_tag("integer 0") == tag_encode(Integer(0)) assert statement_to_tag("integer 1") == tag_encode(Integer(1)) assert statement_to_tag("integer -1") == tag_encode(Integer(-1)) assert statement_to_tag("integer 1 context 4") == tag_encode(Integer(1), context=4)
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)
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)
def test_integer_int(self): if _debug: TestInteger._debug("test_integer_int") obj = Integer(1) assert obj.value == 1 assert str(obj) == "Integer(1)" obj = Integer(-1) assert obj.value == -1 assert str(obj) == "Integer(-1)"
def test_integer(self): if _debug: TestInteger._debug("test_integer") obj = Integer() assert obj.value == 0 with self.assertRaises(TypeError): Integer("some string") with self.assertRaises(TypeError): Integer(1.0)
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()
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 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))
def write_bacnet(app, address, obj_type, obj_inst, prop_id, value, index=None): request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id) request.pduDestination = address datatype = get_datatype(obj_type, prop_id) if (value is None or value == 'null'): bac_value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) bac_value = datatype(value) elif issubclass(datatype, Array) and (index is not None): if index == 0: bac_value = Integer(value) elif issubclass(datatype.subtype, Atomic): bac_value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__, )) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__, )) request.propertyValue = Any() request.propertyValue.cast_in(bac_value) result = app.make_request(request) if isinstance(result, SimpleAckPDU): print "Write Successful !!" else: print "Write was not successful !!"
def write_property(self, target_address, value, object_type, instance_number, property_name, priority=None, index=None): """Write to a property.""" _log.debug( write_debug_str.format(target=target_address, type=object_type, instance=instance_number, property=property_name, priority=priority, index=index, value=value)) request = WritePropertyRequest(objectIdentifier=(object_type, instance_number), propertyIdentifier=property_name) datatype = get_datatype(object_type, property_name) if (value is None or value == 'null'): bac_value = Null() elif issubclass(datatype, Atomic): bac_value = self._cast_value(value, datatype) elif issubclass(datatype, Array) and (index is not None): if index == 0: bac_value = Integer(value) elif issubclass(datatype.subtype, Atomic): bac_value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting {}".format( datatype.subtype.__name__, )) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s".format( datatype.__name__, )) request.propertyValue = Any() request.propertyValue.cast_in(bac_value) request.pduDestination = Address(target_address) # Optional index if index is not None: request.propertyArrayIndex = index # Optional priority if priority is not None: request.priority = priority iocb = self.iocb_class(request) self.this_application.submit_request(iocb) result = iocb.ioResult.get(10) if isinstance(result, SimpleAckPDU): return value raise RuntimeError("Failed to set value: " + str(result))
def write_property(self, target_address, value, object_type, instance_number, property_name, priority=None, index=None): """Write to a property.""" request = WritePropertyRequest(objectIdentifier=(object_type, instance_number), propertyIdentifier=property_name) datatype = get_datatype(object_type, property_name) if (value is None or value == 'null'): bac_value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) bac_value = datatype(value) elif issubclass(datatype, Array) and (index is not None): if index == 0: bac_value = Integer(value) elif issubclass(datatype.subtype, Atomic): bac_value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__, )) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__, )) request.propertyValue = Any() request.propertyValue.cast_in(bac_value) request.pduDestination = Address(target_address) # Optional index if index is not None: request.propertyArrayIndex = index # Optional priority if priority is not None: request.priority = priority iocb = IOCB(request, AsyncCall()) self.this_application.submit_request(iocb) result = iocb.ioResult.wait() if isinstance(result, SimpleAckPDU): return value raise RuntimeError("Failed to set value: " + str(result)) #k= write_property("2001:127", 1, "binaryOutput", 1, "presentValue", priority=None, index=None)
def integer_decode(tag): """Decode an integer application tag into an integer.""" if _debug: integer_decode._debug("integer_decode %r", tag) obj = Integer(tag) if _debug: integer_decode._debug(" - obj: %r", obj) return obj
def test_integer_tag(self): if _debug: TestInteger._debug("test_integer_tag") tag = Tag(Tag.applicationTagClass, Tag.integerAppTag, 1, xtob('01')) obj = Integer(tag) assert obj.value == 1 tag = Tag(Tag.applicationTagClass, Tag.booleanAppTag, 0, xtob('')) with self.assertRaises(InvalidTag): Integer(tag) tag = Tag(Tag.contextTagClass, 0, 1, xtob('ff')) with self.assertRaises(InvalidTag): Integer(tag) tag = Tag(Tag.openingTagClass, 0) with self.assertRaises(InvalidTag): Integer(tag)
def test_tag_list(self): if _debug: TestExtendedTagList._debug("test_tag_list") compare_tag_list(""" opening tag 1 integer 2 closing tag 3 """, OpeningTag(1), tag_encode(Integer(2)), ClosingTag(3), )
def write_property(self, target_address, value, object_type, instance_number, property_name, priority=None, index=None): """Write to a property.""" # target_address = IP or network address of device # setvalue = the value you want to set to # object_type = protocol related object type: eg: Analog Input (AI), Analog Output etc # instance_number = the interger id of the property you want to change (brightness, state etc) # property = always set to "presentValue" # priority = the priority of your settings. Higher priority settings takes over request = WritePropertyRequest( objectIdentifier=(object_type, instance_number), propertyIdentifier=property_name) datatype = get_datatype(object_type, property_name) bac_value = Null() if issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) bac_value = datatype(value) elif issubclass(datatype, Array) and (index is not None): if index == 0: bac_value = Integer(value) elif issubclass(datatype.subtype, Atomic): bac_value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__,)) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__,)) request.propertyValue = Any() request.propertyValue.cast_in(bac_value) request.pduDestination = Address(target_address) #Optional index if index is not None: request.propertyArrayIndex = index #Optional priority if priority is not None: request.priority = priority iocb = IOCB(request, self.async_call) self.this_application.submit_request(iocb) result = iocb.ioResult.wait() if isinstance(result, SimpleAckPDU): return value raise RuntimeError("Failed to set value: " + str(result))
def integer_endec(v, x): """Pass the value to Integer, construct a tag from the hex string, and compare results of encode and decoding each other.""" if _debug: integer_endec._debug("integer_endec %r %r", v, x) tag = integer_tag(x) if _debug: integer_endec._debug(" - tag: %r, %r", tag, tag.tagData) obj = Integer(v) if _debug: integer_endec._debug(" - obj: %r, %r", obj, obj.value) assert integer_encode(obj) == tag assert integer_decode(tag) == obj
def test_integer(self): if _debug: TestInteger._debug("test_integer") obj = Integer() assert obj.value == 0 assert Integer.is_valid(1) assert Integer.is_valid(-1) if sys.version[0] == 2: assert Integer.is_valid(long(1)) assert Integer.is_valid(long(-1)) assert not Integer.is_valid(True) assert not Integer.is_valid(1.0) with self.assertRaises(TypeError): Integer("some string") with self.assertRaises(TypeError): Integer(1.0)
def _validate_value_vs_datatype(self, obj_type, prop_id, indx, vendor_id, value): """ This will ensure the value can be encoded and is valid in the context """ # get the datatype datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id) # change atomic values into something encodeable, null is a special # case if value == "null": value = Null() elif issubclass(datatype, Atomic): if (datatype is Integer # or datatype is not Real or datatype is Unsigned or datatype is Enumerated): value = int(value) elif datatype is Real: value = float(value) # value = datatype(value) else: # value = float(value) value = datatype(value) value = datatype(value) elif issubclass(datatype, Array) and (indx is not None): if indx == 0: value = Integer(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting {}".format( (datatype.subtype.__name__, ))) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting {}".format( (datatype.__name__, ))) self._log.debug("{:<20} {!r} {}".format("Encodeable value", value, type(value))) _value = Any() try: _value.cast_in(value) except WritePropertyCastError as error: self._log.error("WriteProperty cast error: {!r}".format(error)) raise return _value
def test_integer_endec(self): if _debug: TestInteger._debug("test_integer_endec") with self.assertRaises(InvalidTag): obj = Integer(integer_tag('')) integer_endec(0, '00') integer_endec(1, '01') integer_endec(127, '7f') integer_endec(-128, '80') integer_endec(-1, 'ff') integer_endec(32767, '7fff') integer_endec(-32768, '8000') integer_endec(8388607, '7fffff') integer_endec(-8388608, '800000') integer_endec(2147483647, '7fffffff') integer_endec(-2147483648, '80000000')
def do_write(self, args): """write <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]""" args = args.split() ReadWritePropertyConsoleCmd._debug("do_write %r", args) try: addr, obj_type, obj_inst, prop_id = args[:4] if obj_type.isdigit(): obj_type = int(obj_type) obj_inst = int(obj_inst) value = args[4] indx = None if len(args) >= 6: if args[5] != "-": indx = int(args[5]) if _debug: ReadWritePropertyConsoleCmd._debug(" - indx: %r", indx) priority = None if len(args) >= 7: priority = int(args[6]) if _debug: ReadWritePropertyConsoleCmd._debug(" - priority: %r", priority) # get the datatype datatype = get_datatype(obj_type, prop_id) if _debug: ReadWritePropertyConsoleCmd._debug(" - datatype: %r", datatype) # change atomic values into something encodeable, null is a special case if (value == 'null'): value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) value = datatype(value) elif issubclass(datatype, Array) and (indx is not None): if indx == 0: value = Integer(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError, "invalid result datatype, expecting %s" % (datatype.subtype.__name__,) elif not isinstance(value, datatype): raise TypeError, "invalid result datatype, expecting %s" % (datatype.__name__,) if _debug: ReadWritePropertyConsoleCmd._debug(" - encodeable value: %r %s", value, type(value)) # build a request request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id ) request.pduDestination = Address(addr) # save the value request.propertyValue = Any() try: request.propertyValue.cast_in(value) except Exception, e: ReadWritePropertyConsoleCmd._exception("WriteProperty cast error: %r", e) # optional array index if indx is not None: request.propertyArrayIndex = indx # optional priority if priority is not None: request.priority = priority if _debug: ReadWritePropertyConsoleCmd._debug(" - request: %r", request) # give it to the application this_application.request(request)
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)
def confirmation(self, pdu): if _debug: WritePropertyClient._debug('confirmation %r', pdu) global this_application # decode the bytes into a string and strip off the end-of-line args = pdu.pduData.decode('utf-8').strip().split() if _debug: WritePropertyClient._debug(" - args: %r", args) try: addr, obj_type, obj_inst, prop_id = args[:4] if obj_type.isdigit(): obj_type = int(obj_type) obj_inst = int(obj_inst) value = args[4] indx = None if len(args) >= 6: if args[5] != "-": indx = int(args[5]) if _debug: WritePropertyClient._debug(" - indx: %r", indx) priority = None if len(args) >= 7: priority = int(args[6]) if _debug: WritePropertyClient._debug(" - priority: %r", priority) # get the datatype datatype = get_datatype(obj_type, prop_id) if _debug: WritePropertyClient._debug(" - datatype: %r", datatype) # change atomic values into something encodeable, null is a special case if (value == 'null'): value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) value = datatype(value) elif issubclass(datatype, Array) and (indx is not None): if indx == 0: value = Integer(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__,)) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__,)) if _debug: WritePropertyClient._debug(" - encodeable value: %r %s", value, type(value)) # build a request request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id ) request.pduDestination = Address(addr) # save the value request.propertyValue = Any() try: request.propertyValue.cast_in(value) except Exception as error: WritePropertyClient._exception("WriteProperty cast error: %r", error) # optional array index if indx is not None: request.propertyArrayIndex = indx # optional priority if priority is not None: request.priority = priority if _debug: WritePropertyClient._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: WritePropertyClient._debug(" - iocb: %r", iocb) # reference the original request so the response goes back to the # correct client iocb.request_pdu = pdu # add ourselves to be called back for the response iocb.add_callback(self.complete) # give it to the application this_application.request_io(iocb) except Exception as error: WritePropertyClient._exception("exception: %r", error) # send it back to the client error_str = "exception: " + str(error) + '\r\n' self.request(PDU(error_str.encode('utf-8'), destination=pdu.pduSource))
def build_wp_request(self, args, vendor_id=0): addr, obj_type, obj_inst, prop_id = args[:4] vendor_id = vendor_id if obj_type.isdigit(): obj_type = int(obj_type) obj_inst = int(obj_inst) value = args[4] indx = None if len(args) >= 6: if args[5] != "-": indx = int(args[5]) priority = None if len(args) >= 7: priority = int(args[6]) # get the datatype if prop_id.isdigit(): prop_id = int(prop_id) datatype = get_datatype(obj_type, prop_id, vendor_id=vendor_id) self.log_subtitle("Creating Request") self._log.debug("{:<20} {:<20} {:<20} {:<20}".format( "indx", "priority", "datatype", "value")) self._log.debug("{!r:<20} {!r:<20} {!r:<20} {!r:<20}".format( indx, priority, datatype, value)) # change atomic values into something encodeable, null is a special # case if value == "null": value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) value = datatype(value) elif issubclass(datatype, Array) and (indx is not None): if indx == 0: value = Integer(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting {}".format( (datatype.subtype.__name__, ))) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting {}".format( (datatype.__name__, ))) self._log.debug("{:<20} {!r} {}".format("Encodeable value", value, type(value))) # build a request request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id) request.pduDestination = Address(addr) # save the value request.propertyValue = Any() try: request.propertyValue.cast_in(value) except WritePropertyCastError as error: self._log.error("WriteProperty cast error: {!r}".format(error)) # optional array index if indx is not None: request.propertyArrayIndex = indx # optional priority if priority is not None: request.priority = priority self._log.debug("{:<20} {}".format("REQUEST", request)) return request
def do_write(self, args): """write <addr> <objid> <prop> <value> [ <indx> ] [ <priority> ]""" args = args.split() ReadWritePropertyConsoleCmd._debug("do_write %r", args) try: addr, obj_id, prop_id = args[:3] obj_id = ObjectIdentifier(obj_id).value if not get_object_class(obj_id[0], VendorAVObject.vendor_id): raise ValueError("unknown object type") if prop_id.isdigit(): prop_id = int(prop_id) if _debug: ReadWritePropertyConsoleCmd._debug(" - prop_id: %r", prop_id) value = args[3] indx = None if len(args) >= 5: if args[4] != "-": indx = int(args[4]) if _debug: ReadWritePropertyConsoleCmd._debug(" - indx: %r", indx) priority = None if len(args) >= 6: priority = int(args[5]) if _debug: ReadWritePropertyConsoleCmd._debug(" - priority: %r", priority) # get the datatype datatype = get_datatype(obj_id[0], prop_id, VendorAVObject.vendor_id) if _debug: ReadWritePropertyConsoleCmd._debug(" - datatype: %r", datatype) # change atomic values into something encodeable, null is a special case if (value == 'null'): value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) value = datatype(value) elif issubclass(datatype, Array) and (indx is not None): if indx == 0: value = Integer(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__, )) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__, )) if _debug: ReadWritePropertyConsoleCmd._debug( " - encodeable value: %r %s", value, type(value)) # build a request request = WritePropertyRequest(objectIdentifier=obj_id, propertyIdentifier=prop_id) request.pduDestination = Address(addr) # save the value request.propertyValue = Any() try: request.propertyValue.cast_in(value) except Exception as error: ReadWritePropertyConsoleCmd._exception( "WriteProperty cast error: %r", error) # optional array index if indx is not None: request.propertyArrayIndex = indx # optional priority if priority is not None: request.priority = priority if _debug: ReadWritePropertyConsoleCmd._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: ReadWritePropertyConsoleCmd._debug(" - iocb: %r", iocb) # give it to the application deferred(this_application.request_io, iocb) # wait for it to complete iocb.wait() # do something for success if iocb.ioResponse: sys.stdout.write("ack\n") # do something for error/reject/abort if iocb.ioError: sys.stdout.write(str(iocb.ioError) + '\n') except Exception as error: ReadWritePropertyConsoleCmd._exception("exception: %r", error)
def create_WritePropertyRequest(args): """ Create a WritePropertyRequest from a string """ args = args.split() addr, obj_type, obj_inst, prop_id = args[:4] if obj_type.isdigit(): obj_type = int(obj_type) obj_inst = int(obj_inst) value = args[4] indx = None if len(args) >= 6: if args[5] != "-": indx = int(args[5]) priority = None if len(args) >= 7: priority = int(args[6]) # get the datatype datatype = get_datatype(obj_type, prop_id) # change atomic values into something encodeable, null is a special # case if value == 'null': value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) value = datatype(value) elif issubclass(datatype, Array) and (indx is not None): if indx == 0: value = Integer(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__, )) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__, )) # build a request request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id) request.pduDestination = Address(addr) # save the value request.propertyValue = Any() try: request.propertyValue.cast_in(value) except WritePropertyCastError as error: raise ValueError("WriteProperty cast error: %r", error) # optional array index if indx is not None: request.propertyArrayIndex = indx # optional priority if priority is not None: request.priority = priority return request
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_integer_copy(self): if _debug: TestInteger._debug("test_integer_copy") obj1 = Integer(12) obj2 = Integer(obj1) assert obj2.value == 12
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")
def write(self, args): """ This function build a write request wait for an acknowledgment and return a boolean status (True if ok, False if not) :param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ] :returns: data read from device (str representing data like 10 or True) *Example*:: import BAC0 myIPAddr = '192.168.1.10' bacnet = BAC0.ReadWriteScript(localIPAddr = myIPAddr) bacnet.write('2:5 analogValue 1 presentValue 100') will write 100 to AV:1 of a controller with a MAC address of 5 in the network 2 """ if not self._started: raise Exception('App not running, use startApp() function') args = args.split() print_debug("do_write %r", args) try: addr, obj_type, obj_inst, prop_id = args[:4] if obj_type.isdigit(): obj_type = int(obj_type) obj_inst = int(obj_inst) value = args[4] indx = None if len(args) >= 6: if args[5] != "-": indx = int(args[5]) print_debug(" - indx: %r", indx) priority = None if len(args) >= 7: priority = int(args[6]) print_debug(" - priority: %r", priority) # get the datatype datatype = get_datatype(obj_type, prop_id) print_debug(" - datatype: %r", datatype) # change atomic values into something encodeable, null is a special case if value == 'null': value = Null() elif issubclass(datatype, Atomic): if datatype is Integer: value = int(value) elif datatype is Real: value = float(value) elif datatype is Unsigned: value = int(value) value = datatype(value) elif issubclass(datatype, Array) and (indx is not None): if indx == 0: value = Integer(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s" % (datatype.subtype.__name__,)) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s" % (datatype.__name__,)) print_debug(" - encodeable value: %r %s", value, type(value)) # build a request request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id ) request.pduDestination = Address(addr) # save the value request.propertyValue = Any() try: request.propertyValue.cast_in(value) except WritePropertyCastError as error: WriteProperty._exception("WriteProperty cast error: %r", error) # optional array index if indx is not None: request.propertyArrayIndex = indx # optional priority if priority is not None: request.priority = priority print_debug(" - request: %r", request) # give it to the application self.this_application.request(request) except WritePropertyException as error: WriteProperty._exception("exception: %r", error) while True: try: data, evt = self.this_application.ResponseQueue.get(timeout=self._TIMEOUT) evt.set() return data except Empty: raise NoResponseFromController return None