def __init__(self, *args): BIPSimpleApplication.__init__(Mock()) self.elementService = Mock() #self.ResponseQueue = Mock() #self.ResponseQueue.get.return_value = ([21, 'degreesCelcius'], Event()) iocb = IOCB() apdu = ReadPropertyMultipleACK(listOfReadAccessResults=[ ReadAccessResult( objectIdentifier=('analogValue', 1), listOfResults=[ ReadAccessResultElement( propertyIdentifier='presentValue', readResult=ReadAccessResultElementChoice( propertyValue=Any(Real(21.0)), )), ReadAccessResultElement( propertyIdentifier='units', readResult=ReadAccessResultElementChoice( propertyValue=Any(Enumerated(62)), )), ], ) ]) iocb.complete(apdu) self.request = Mock() self.request.return_value = iocb
def form_iocb(device, config=None, request_type="readProperty"): config = config if config is not None else device address = device["address"] if isinstance(device["address"], Address) else Address(device["address"]) object_id = ObjectIdentifier(config["objectId"]) property_id = config.get("propertyId") value = config.get("propertyValue") property_index = config.get("propertyIndex") priority = config.get("priority") vendor = device.get("vendor", config.get("vendorId", 0)) request = None iocb = None if request_type == "readProperty": try: request = ReadPropertyRequest( objectIdentifier=object_id, propertyIdentifier=property_id ) request.pduDestination = address if property_index is not None: request.propertyArrayIndex = int(property_index) iocb = IOCB(request) except Exception as e: log.exception(e) elif request_type == "writeProperty": datatype = get_datatype(object_id.value[0], property_id, vendor) if (isinstance(value, str) and value.lower() == 'null') or value is None: value = Null() request = WritePropertyRequest( objectIdentifier=object_id, propertyIdentifier=property_id ) request.pduDestination = address request.propertyValue = Any() try: value = datatype(value) request.propertyValue = Any(value) except AttributeError as e: log.debug(e) except Exception as error: log.exception("WriteProperty cast error: %r", error) if property_index is not None: request.propertyArrayIndex = property_index if priority is not None: request.priority = priority iocb = IOCB(request) else: log.error("Request type is not found or not implemented") return iocb
def write(device, portObject, value): request_addr = device.getRequestAddress() obj_type = portObject.getType() obj_inst = portObject.getPortNum() prop_id = portObject.getProp() index = portObject.getIndex() priority = portObject.getPriority() try: #verify datatype datatype = get_datatype(obj_type, prop_id) if not datatype: raise ValueError, ": invalid property for object type" value = datatype(value) request = WritePropertyRequest(objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id) request.pduDestination = Address(request_addr) request.propertyValue = Any() request.propertyValue.cast_in(value) request.propertyArrayIndex = index request.priority = priority this_application.request(request) time.sleep(.1) returnVal = this_application._Application__response_value except: returnVal = "Error, unable to write" finally: return returnVal
def test_readProperty(self): request = ReadPropertyRequest( objectIdentifier=("analogInput", 14), propertyIdentifier=85 ) request.apduMaxResp = 1024 request.apduInvokeID = 101 apdu = APDU() request.encode(apdu) pdu = PDU() apdu.encode(pdu) buf_size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto(pdu.pduData, self.address) data = s.recvfrom(buf_size) s.close() received_data = data[0] expected = ReadPropertyACK() expected.pduDestination = GlobalBroadcast() expected.apduInvokeID = 101 expected.objectIdentifier = 14 expected.objectName = "AI 01" expected.propertyIdentifier = 85 expected.propertyValue = Any(Real(68.0)) exp_apdu = APDU() expected.encode(exp_apdu) exp_pdu = PDU() exp_apdu.encode(exp_pdu) self.assertEqual(exp_pdu.pduData, received_data)
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 do_save(self, args): """save <addr> <device instance>""" args = args.split() if _debug: SaveToFlashConsoleCmd._debug("do_save %r", args) try: addr, obj_inst = args[:2] # object type = 8 (device). property = 1151 (SaveToFlash) obj_type = 8 obj_inst = int(obj_inst) prop_id = 1151 # build a request request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, ) request.pduDestination = Address(addr) if len(args) == 5: request.propertyArrayIndex = int(args[4]) # send an Enumerated value of 1 means SaveToFlash tag_list = TagList([ApplicationTag(9, xtob('01'))]) if _debug: SaveToFlashConsoleCmd._debug(" - tag_list: %r", tag_list) # stuff the tag list into an Any request.propertyValue = Any() request.propertyValue.decode(tag_list) if _debug: SaveToFlashConsoleCmd._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: SaveToFlashConsoleCmd._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: SaveToFlashConsoleCmd._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: SaveToFlashConsoleCmd._exception("exception: %r", error)
def __write_value(self, config_obj_id: str, _value: float) -> None: try: # get config obj obj = self.__get_object(config_obj_id) obj_id = obj.get('object_id') obj_id = ObjectIdentifier(obj_id).value # make a bacpypes obj id addr = self.__get_device() prop_id = self.__get_prop() # write <addr> <objid> <prop> <value> value = float(_value) self.logger.debug(f"write: {config_obj_id} {_value} for port \'{obj.get('name')}\' {str(obj_id)} {prop_id} {value}") request = WritePropertyRequest( objectIdentifier=obj_id, propertyIdentifier=prop_id ) request.pduDestination = Address(addr) # the value to write datatype = get_datatype(obj_id[0], prop_id) value = datatype(value) request.propertyValue = Any() try: request.propertyValue.cast_in(value) except Exception as err: self.logger.critical(f"write: {err}") iocb = IOCB(request) self.app.request_io(iocb) self.logger.debug("write: waiting for response...") loopCount = 0 while loopCount < 20 and not iocb.ioResponse: loopCount += 1 run_once() asyncore.loop(timeout=0.2, count=1) time.sleep(0.2) self.logger.debug(f"write: loopy {loopCount}") stop() # do something for success if iocb.ioResponse: self.logger.debug(f"write: iocb response success!") apdu = iocb.ioResponse # should be an ack if not isinstance(iocb.ioResponse, SimpleAckPDU): self.logger.error(f"write: Not an ACK") return self.logger.debug(f"write: received ACK") # do something for error/reject/abort if iocb.ioError: self.logger.error(f"write: ioError {str(iocb.ioError)}") except Exception as err: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, file=sys.stdout) self.logger.critical(f"write: {err}")
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 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 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 make_weeklySchedule_request(self, destination, object_instance, weeklySchedule): request = WritePropertyRequest( objectIdentifier=("schedule", object_instance), propertyIdentifier="weeklySchedule", ) address = Address(destination) request.pduDestination = address request.propertyValue = Any() request.propertyValue.cast_in(weeklySchedule) request.priority = 15 return request
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
def __init__(self, *args): BIPSimpleApplication.__init__(Mock()) self.elementService = Mock() #self.value = None iocb = IOCB() # Forging apdu response fake_apdu = ReadPropertyACK( objectIdentifier=('analogInput', 0), propertyIdentifier='presentValue', propertyValue=Any(Real(32)), ) iocb.complete(fake_apdu) self.request = Mock() self.request.return_value = iocb
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 write_recipient_list(addr, obj_inst, recipent_list): if _debug: EventNotificationConsoleCmd._debug("write_recipient_list %r %r %r", addr, obj_inst, recipent_list) # the new list has just us recipient_list = ListOfDestination(recipent_list) if _debug: EventNotificationConsoleCmd._debug(" - recipient_list: %r", recipient_list) # build a request request = WritePropertyRequest( objectIdentifier=('notificationClass', obj_inst), propertyIdentifier='recipientList', propertyValue=Any(), ) request.pduDestination = Address(addr) # save the value request.propertyValue.cast_in(recipient_list) if _debug: EventNotificationConsoleCmd._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: EventNotificationConsoleCmd._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: # should be an ack if not isinstance(iocb.ioResponse, SimpleAckPDU): if _debug: EventNotificationConsoleCmd._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')
def write_bac_set(self): addr = point_list[0][0] obj_type = self.obj obj_inst = self.inst prop_id = self.prop tags = self.response_bacset[0] proxy_ip = self.proxyIP print tags print proxy_ip try: # build a request request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, ) request.pduDestination = Address(addr) request.propertyArrayIndex = self.idx # build a custom datastructure... BACnet settings IP net or bcp tag_list = contextTagsToWrite.build_list(self.response_bacset, proxy_ip) #if _debug: WriteSomethingConsoleCmd._debug(" - tag_list: %r", tag_list) # stuff the tag list into an Any request.propertyValue = Any() request.propertyValue.decode(tag_list) #if _debug: WriteSomethingConsoleCmd._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) #if _debug: WriteSomethingConsoleCmd._debug(" - iocb: %r", iocb) # set a callback for the response iocb.add_callback(self.simple_ack) # give it to the application this_application.request_io(iocb) except Exception as error: #WriteSomethingConsoleCmd._exception("exception: %r", error) print error
def ReadPropertyToAny(obj, propertyIdentifier, propertyArrayIndex=None): """Read the specified property of the object, with the optional array index, and cast the result into an Any object.""" if _debug: ReadPropertyToAny._debug("ReadPropertyToAny %s %r %r", obj, propertyIdentifier, propertyArrayIndex) # get the datatype datatype = obj.get_datatype(propertyIdentifier) if _debug: ReadPropertyToAny._debug(" - datatype: %r", datatype) if datatype is None: raise ExecutionError(errorClass='property', errorCode='datatypeNotSupported') # get the value value = obj.ReadProperty(propertyIdentifier, propertyArrayIndex) if _debug: ReadPropertyToAny._debug(" - value: %r", value) if value is None: raise ExecutionError(errorClass='property', errorCode='unknownProperty') # change atomic values into something encodeable if issubclass(datatype, Atomic): value = datatype(value) elif issubclass(datatype, Array) and (propertyArrayIndex is not None): if propertyArrayIndex == 0: value = Unsigned(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s and got %s" \ % (datatype.subtype.__name__, type(value).__name__)) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s and got %s" \ % (datatype.__name__, type(value).__name__)) if _debug: ReadPropertyToAny._debug(" - encodeable value: %r", value) # encode the value result = Any() result.cast_in(value) if _debug: ReadPropertyToAny._debug(" - result: %r", result) # return the object return result
def readProperty(self, request, address, invoke_key, device): # Read Property # TODO: add support for PropertyArrayIndex handling; for obj in device.objectList.value[2:]: if ( int(request.objectIdentifier[1]) == obj[1] and request.objectIdentifier[0] == obj[0] ): objName = self.objectIdentifier[obj].objectName for prop in self.objectIdentifier[obj].properties: if request.propertyIdentifier == prop.identifier: propName = prop.identifier propValue = prop.ReadProperty(self.objectIdentifier[obj]) propType = prop.datatype() self._response_service = "ComplexAckPDU" self._response = ReadPropertyACK() self._response.pduDestination = address self._response.apduInvokeID = invoke_key self._response.objectIdentifier = obj[1] self._response.objectName = objName self._response.propertyIdentifier = propName # get the property type for p in dir(sys.modules[propType.__module__]): _obj = getattr(sys.modules[propType.__module__], p) try: if type(propType) == _obj: break except TypeError: pass value = ast.literal_eval(propValue) self._response.propertyValue = Any(_obj(value)) # self._response.propertyValue.cast_in(objPropVal) # self._response.debug_contents() break else: logger.info( "Bacnet ReadProperty: object has no property %s", request.propertyIdentifier, ) self._response = ErrorPDU() self._response.pduDestination = address self._response.apduInvokeID = invoke_key self._response.apduService = 0x0C
def test_apdu_bad_reply(self): """Confirmed Request - Bad Reply""" if _debug: TestAPDUDecodingError._debug("test_apdu_bad_reply") # create a network anet = ApplicationNetwork("test_apdu_bad_reply") # make a bad value a = Any() a.tagList.append(OpeningTag(1)) # create a bad APDU to send back bad_apdu = ReadPropertyACK( objectIdentifier=("analogValue", 1), propertyIdentifier="presentValue", propertyValue=a, ) bad_apdu.pduDestination = anet.td.address bad_apdu.apduInvokeID = 1 # send a request to a non-existent device, get it rejected anet.td.start_state.doc("8-1-0") \ .send( ReadPropertyRequest( objectIdentifier=("analogValue", 1), propertyIdentifier="presentValue", destination=anet.ed.address, )).doc("8-1-1") \ .receive( Error, errorClass=7, # communication errorCode=57, # invalidTag ).doc("8-1-2") \ .success() # error device sends back a badly encoded response anet.ed.start_state.doc("8-2-0") \ .receive(APDU).doc("8-2-1") \ .send(bad_apdu).doc("8-2-2") \ .success() # run the group anet.run()
def set_state_async(self, bac_app, address, value): if not self.read_only: request = WritePropertyRequest( objectIdentifier=(self.object_type, self.instance_number), propertyIdentifier=self.property) # save the value if self.datatype is Integer: value = int(value) elif self.datatype is Real: value = float(value) bac_value = self.datatype(value) request.propertyValue = Any() request.propertyValue.cast_in(bac_value) request.pduDestination = address iocb = IOCB(request) bac_app.request(iocb) iocb.ioDefered.addCallback(self.set_state_async_callback, value) return iocb.ioDefered raise TypeError('This register is read only.')
def process_task(self): if _debug: PrairieDog._debug("process_task") global args, this_application if _debug: PrairieDog._debug(" - args.values: %r", args.values) # pick up the next value value = args.values.pop(0) args.values.append(value) # make a primitive value out of it value = Real(float(value)) # build a request request = WritePropertyRequest( destination=args.daddr, objectIdentifier=args.objid, propertyIdentifier=args.propid, ) # save the value, application tagged request.propertyValue = Any() request.propertyValue.cast_in(value) if _debug: PrairieDog._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) iocb.add_callback(self.write_complete) if _debug: PrairieDog._debug(" - iocb: %r", iocb) # give it to the application to process deferred(this_application.request_io, iocb)
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> <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> <objid> <prop> [ <indx> ]""" args = args.split() if _debug: WriteSomethingConsoleCmd._debug("do_write %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 = WritePropertyRequest( objectIdentifier=obj_id, propertyIdentifier=prop_id, ) request.pduDestination = Address(addr) if len(args) == 4: request.propertyArrayIndex = int(args[3]) # build a custom datastructure tag_list = TagList([ OpeningTag(1), ContextTag(0, xtob('9c40')), ContextTag(1, xtob('02')), ContextTag(2, xtob('02')), ClosingTag(1) ]) if _debug: WriteSomethingConsoleCmd._debug(" - tag_list: %r", tag_list) # stuff the tag list into an Any request.propertyValue = Any() request.propertyValue.decode(tag_list) if _debug: WriteSomethingConsoleCmd._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: WriteSomethingConsoleCmd._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: # should be an ack if not isinstance(iocb.ioResponse, SimpleAckPDU): if _debug: WriteSomethingConsoleCmd._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: WriteSomethingConsoleCmd._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 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)
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 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 do_write(self, args): """write <addr> <type> <inst> <prop> [ <indx> ]""" args = args.split() if _debug: WriteSomethingConsoleCmd._debug("do_write %r", args) try: addr = args[0] obj_type = 162 #int(obj_type) obj_inst = 1 #int(obj_inst) prop_id = 1034 #int(prop_id) idx = 2 # build a request request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id, ) request.pduDestination = Address(addr) if len(args) >= 5: request.propertyArrayIndex = 2 #int(args[4]) request.propertyArrayIndex = idx if len(args) == 6: #convert ip to byte array and then to hex string proxy = bytearray(args[5]) proxy_hex = str(proxy).encode('hex') # build a custom data structure... BACnet settings BCP object IP BBMD Foreign port eTCH 3.40 # Context #0 inside Opening tag #9 is the IP Type 00=Regular, 01=Foreign, 02=BBMD # Context #2 inside Opening tag #9 is the Foreign IP in hex # Context #4 inside Opening tag #9 is the Proxy IP in hex tag_list = TagList([ OpeningTag(0), ContextTag(0, xtob('19')), ContextTag(1, xtob('01')), ClosingTag(0), ContextTag(1, xtob('01')), ContextTag(2, xtob('00')), ContextTag(3, xtob('9c40')), ContextTag(4, xtob('00')), OpeningTag(5), ContextTag(0, xtob('00')), ContextTag(1, xtob('00')), ClosingTag(5), ContextTag(6, xtob('00')), ContextTag(7, xtob('00')), OpeningTag(8), ContextTag(0, xtob('00')), ContextTag(1, xtob('00')), ContextTag(2, xtob('00')), ContextTag(3, xtob('00')), ContextTag(4, xtob('00')), ContextTag(5, xtob('00')), ContextTag(6, xtob('00')), ContextTag(7, xtob('00')), ContextTag(8, xtob('ffffffff')), ClosingTag(8), OpeningTag(9), ContextTag(0, xtob('02')), ContextTag(1, xtob('bac0')), ContextTag(2, xtob('00')), ContextTag(3, xtob('3c')), ContextTag(4, xtob('480c600c')), ContextTag(5, xtob('00')), ContextTag(6, xtob('ffffffff')), ClosingTag(9), ContextTag(10, xtob('00')), ContextTag(11, xtob('00')), ContextTag(12, xtob('00')), ContextTag(13, xtob('00000000')) ]) if _debug: WriteSomethingConsoleCmd._debug(" - tag_list: %r", tag_list) # stuff the tag list into an Any request.propertyValue = Any() request.propertyValue.decode(tag_list) if _debug: WriteSomethingConsoleCmd._debug(" - request: %r", request) # make an IOCB iocb = IOCB(request) if _debug: WriteSomethingConsoleCmd._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: WriteSomethingConsoleCmd._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: WriteSomethingConsoleCmd._exception("exception: %r", error)