From 9b7bf47b5b9ec53872c44db21c77be7494f9df0e Mon Sep 17 00:00:00 2001 From: Ben Hutcheson Date: Sat, 6 Jan 2024 10:35:29 +0100 Subject: [PATCH] feat(plc4py): Code Gen Update (#1199) - Incremental update to python * feat(plc4y): Still getting the static parse code working * feat(plc4y): Start looking at testing generated code * feat(plc4y): Sorting out code gen issues * chore(plc4py): Update the generated code * chore(plc4py): Start writing modbus logic :) * chore(plc4py): Start writing modbus logic :) * chore(plc4py): Renamed Field -> Tag, fixed up tag handlers * chore(plc4py): Fixed build wrong import was used re.Pattern instead of typing.Pattern * chore(plc4py): Fixed Enums and working on DataIO template * chore(plc4py): Update the PlcValues and Data IO template * chore(plc4j): Accidentally pushed a change to the Java driver * fix(plc4py): Fix parsing of Enums * fix(plc4py): Fix license classifier to match a pypi classifier --- .../python/PythonLanguageTemplateHelper.java | 116 +-- .../python/complex-type-template.python.ftlh | 217 +++-- .../python/data-io-template.python.ftlh | 124 +-- .../python/enum-template.python.ftlh | 23 +- .../plc4py/api/exceptions/exceptions.py | 4 + .../plc4py/plc4py/api/messages/PlcField.py | 6 +- .../plc4py/plc4py/api/messages/PlcRequest.py | 16 +- .../plc4py/plc4py/api/messages/PlcResponse.py | 14 +- sandbox/plc4py/plc4py/api/value/PlcValue.py | 18 +- .../plc4py/drivers/mock/MockConnection.py | 65 +- .../drivers/mock/MockReadRequestBuilder.py | 23 +- .../PlcBOOL.py => drivers/mock/MockTag.py} | 16 +- .../drivers/modbus/ModbusConfiguration.py | 3 + .../plc4py/drivers/modbus/ModbusConnection.py | 48 +- .../plc4py/drivers/modbus/ModbusDevice.py | 152 ++++ .../plc4py/drivers/modbus/ModbusProtocol.py | 37 +- .../plc4py/plc4py/drivers/modbus/ModbusTag.py | 179 ++++ .../protocols/modbus/readwrite/DataItem.py | 769 ++++++++-------- .../protocols/modbus/readwrite/DriverType.py | 11 +- .../protocols/modbus/readwrite/ModbusADU.py | 123 +-- .../modbus/readwrite/ModbusAsciiADU.py | 98 ++- .../modbus/readwrite/ModbusConstants.py | 53 +- .../modbus/readwrite/ModbusDataType.py | 67 +- .../ModbusDeviceInformationConformityLevel.py | 11 +- .../readwrite/ModbusDeviceInformationLevel.py | 11 +- .../ModbusDeviceInformationMoreFollows.py | 11 +- .../ModbusDeviceInformationObject.py | 67 +- .../modbus/readwrite/ModbusErrorCode.py | 11 +- .../protocols/modbus/readwrite/ModbusPDU.py | 690 +++++++++++---- .../readwrite/ModbusPDUDiagnosticRequest.py | 68 +- .../readwrite/ModbusPDUDiagnosticResponse.py | 68 +- .../modbus/readwrite/ModbusPDUError.py | 69 +- .../ModbusPDUGetComEventCounterRequest.py | 50 +- .../ModbusPDUGetComEventCounterResponse.py | 72 +- .../ModbusPDUGetComEventLogRequest.py | 50 +- .../ModbusPDUGetComEventLogResponse.py | 101 ++- ...odbusPDUMaskWriteHoldingRegisterRequest.py | 87 +- ...dbusPDUMaskWriteHoldingRegisterResponse.py | 87 +- .../readwrite/ModbusPDUReadCoilsRequest.py | 72 +- .../readwrite/ModbusPDUReadCoilsResponse.py | 68 +- ...odbusPDUReadDeviceIdentificationRequest.py | 90 +- ...dbusPDUReadDeviceIdentificationResponse.py | 197 +++-- .../ModbusPDUReadDiscreteInputsRequest.py | 72 +- .../ModbusPDUReadDiscreteInputsResponse.py | 72 +- .../ModbusPDUReadExceptionStatusRequest.py | 54 +- .../ModbusPDUReadExceptionStatusResponse.py | 59 +- .../ModbusPDUReadFifoQueueRequest.py | 67 +- .../ModbusPDUReadFifoQueueResponse.py | 79 +- .../ModbusPDUReadFileRecordRequest.py | 75 +- .../ModbusPDUReadFileRecordRequestItem.py | 85 +- .../ModbusPDUReadFileRecordResponse.py | 75 +- .../ModbusPDUReadFileRecordResponseItem.py | 81 +- .../ModbusPDUReadHoldingRegistersRequest.py | 76 +- .../ModbusPDUReadHoldingRegistersResponse.py | 72 +- .../ModbusPDUReadInputRegistersRequest.py | 72 +- .../ModbusPDUReadInputRegistersResponse.py | 72 +- ...eadWriteMultipleHoldingRegistersRequest.py | 132 ++- ...adWriteMultipleHoldingRegistersResponse.py | 72 +- .../ModbusPDUReportServerIdRequest.py | 50 +- .../ModbusPDUReportServerIdResponse.py | 68 +- .../ModbusPDUWriteFileRecordRequest.py | 75 +- .../ModbusPDUWriteFileRecordRequestItem.py | 97 +- .../ModbusPDUWriteFileRecordResponse.py | 75 +- .../ModbusPDUWriteFileRecordResponseItem.py | 97 +- .../ModbusPDUWriteMultipleCoilsRequest.py | 94 +- .../ModbusPDUWriteMultipleCoilsResponse.py | 76 +- ...PDUWriteMultipleHoldingRegistersRequest.py | 96 +- ...DUWriteMultipleHoldingRegistersResponse.py | 78 +- .../ModbusPDUWriteSingleCoilRequest.py | 66 +- .../ModbusPDUWriteSingleCoilResponse.py | 66 +- .../ModbusPDUWriteSingleRegisterRequest.py | 70 +- .../ModbusPDUWriteSingleRegisterResponse.py | 70 +- .../modbus/readwrite/ModbusRtuADU.py | 96 +- .../modbus/readwrite/ModbusTcpADU.py | 134 +-- .../protocols/simulated/readwrite/DataItem.py | 830 ++++++++---------- .../protocols/simulated/readwrite/Dummy.py | 52 +- .../readwrite/SimulatedDataTypeSizes.py | 67 +- .../plc4py/spi/generation/ReadBuffer.py | 92 +- .../plc4py/spi/generation/WriteBuffer.py | 45 +- .../PlcINT.py => messages/PlcRequest.py} | 28 +- sandbox/plc4py/plc4py/spi/values/PlcValues.py | 182 ++++ sandbox/plc4py/plc4py/utils/GenericTypes.py | 21 + sandbox/plc4py/pom.xml | 142 +-- sandbox/plc4py/setup.py | 2 +- sandbox/plc4py/tests/test_plc4py.py | 8 +- .../tests/unit/plc4py/api/test_PlcRequest.py | 42 +- .../drivers/modbus/test_modbus_codegen.py | 55 ++ .../drivers/modbus/test_modbus_connection.py | 18 +- .../unit/plc4py/spi/test_write_buffer.py | 130 +-- 89 files changed, 4818 insertions(+), 3481 deletions(-) rename sandbox/plc4py/plc4py/{spi/values/PlcBOOL.py => drivers/mock/MockTag.py} (69%) create mode 100644 sandbox/plc4py/plc4py/drivers/modbus/ModbusDevice.py create mode 100644 sandbox/plc4py/plc4py/drivers/modbus/ModbusTag.py rename sandbox/plc4py/plc4py/spi/{values/PlcINT.py => messages/PlcRequest.py} (54%) create mode 100644 sandbox/plc4py/plc4py/spi/values/PlcValues.py create mode 100644 sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_codegen.py diff --git a/code-generation/language-python/src/main/java/org/apache/plc4x/language/python/PythonLanguageTemplateHelper.java b/code-generation/language-python/src/main/java/org/apache/plc4x/language/python/PythonLanguageTemplateHelper.java index 7d787e6f470..748392e9977 100644 --- a/code-generation/language-python/src/main/java/org/apache/plc4x/language/python/PythonLanguageTemplateHelper.java +++ b/code-generation/language-python/src/main/java/org/apache/plc4x/language/python/PythonLanguageTemplateHelper.java @@ -207,28 +207,29 @@ public String getFieldOptions(TypedField field, List parserArguments) final Optional encodingOptional = field.getEncoding(); if (encodingOptional.isPresent()) { final String encoding = toParseExpression(field, field.getType(), encodingOptional.get(), parserArguments); - sb.append(", WithOption.WithEncoding(").append(encoding).append(")"); + sb.append(", encoding='").append(encoding).append("'"); } final Optional byteOrderOptional = field.getByteOrder(); if (byteOrderOptional.isPresent()) { final String byteOrder = toParseExpression(field, field.getType(), byteOrderOptional.get(), parserArguments); - sb.append(", WithOption.WithByteOrder(").append(byteOrder).append(")"); + emitRequiredImport("from plc4py.utils.GenericTypes import ByteOrder"); + sb.append(", byte_order=ByteOrder.").append(byteOrder); } return sb.toString(); } public String getDataReaderCall(TypeReference typeReference) { - return getDataReaderCall(typeReference, "enumForValue"); + return getDataReaderCall(typeReference, "enumForValue", false); } - public String getDataReaderCall(TypeReference typeReference, String resolverMethod) { + public String getDataReaderCall(TypeReference typeReference, String resolverMethod, Boolean isArray) { if (typeReference.isEnumTypeReference()) { final String languageTypeName = getLanguageTypeNameForTypeReference(typeReference); final SimpleTypeReference enumBaseTypeReference = getEnumBaseTypeReference(typeReference); - return "DataReaderEnumDefault(" + languageTypeName + "." + resolverMethod + ", " + getDataReaderCall(enumBaseTypeReference) + ")"; + return "read_enum(read_function=" + languageTypeName + ","; } else if (typeReference.isArrayTypeReference()) { final ArrayTypeReference arrayTypeReference = typeReference.asArrayTypeReference().orElseThrow(); - return getDataReaderCall(arrayTypeReference.getElementTypeReference(), resolverMethod); + return getDataReaderCall(arrayTypeReference.getElementTypeReference(), resolverMethod, true); } else if (typeReference.isSimpleTypeReference()) { SimpleTypeReference simpleTypeReference = typeReference.asSimpleTypeReference().orElseThrow(IllegalStateException::new); return getDataReaderCall(simpleTypeReference); @@ -251,12 +252,15 @@ public String getDataReaderCall(TypeReference typeReference, String resolverMeth final TypeReference argumentType = getArgumentType(complexTypeReference, i); paramsString .append(", ") - .append(getLanguageTypeNameForTypeReference(argumentType, true)) - .append("(") .append(toParseExpression(null, argumentType, paramTerm, null)) - .append(")"); + .append("=") + .append(toParseExpression(null, argumentType, paramTerm, null)); + } + if (isArray) { + return parserCallString + ".static_parse, "; + } else { + return "read_complex(read_function=" + parserCallString + ".static_parse, "; } - return "DataReaderComplexDefault(" + parserCallString + ".static_parse(read_buffer" + paramsString + "), read_buffer)"; } else { throw new IllegalStateException("What is this type? " + typeReference); } @@ -270,9 +274,9 @@ public String getDataReaderCall(SimpleTypeReference simpleTypeReference) { case BYTE: return "read_byte"; case UINT: - if (sizeInBits <= 4) return "read_unsigned_byte"; - if (sizeInBits <= 8) return "read_unsigned_short"; - if (sizeInBits <= 16) return "read_unsigned_int"; + if (sizeInBits <= 8) return "read_unsigned_byte"; + if (sizeInBits <= 16) return "read_unsigned_short"; + if (sizeInBits <= 32) return "read_unsigned_int"; return "read_unsigned_long"; case INT: if (sizeInBits <= 8) return "read_signed_byte"; @@ -283,10 +287,10 @@ public String getDataReaderCall(SimpleTypeReference simpleTypeReference) { if (sizeInBits <= 32) return "read_float"; return "read_double"; case STRING: - return "read_string"; + return "read_str"; case VSTRING: VstringTypeReference vstringTypeReference = (VstringTypeReference) simpleTypeReference; - return "read_string"; + return "read_str"; case TIME: return "read_time"; case DATE: @@ -323,14 +327,14 @@ public String getEnumDataWriterCall(EnumTypeReference typeReference, String fiel } else { outputTypeReference = getEnumFieldSimpleTypeReference(typeReference.asNonSimpleTypeReference().orElseThrow(), attributeName); } - return "DataWriterEnumDefault(" + languageTypeName + "." + camelCaseToSnakeCase(attributeName) + ", " + languageTypeName + ".name, " + getDataWriterCall(outputTypeReference, fieldName) + ")"; + return getDataWriterCall(outputTypeReference, fieldName); } public String getDataWriterCall(SimpleTypeReference simpleTypeReference) { final int sizeInBits = simpleTypeReference.getSizeInBits(); switch (simpleTypeReference.getBaseType()) { case BIT: - return "write_boolean"; + return "write_bit"; case BYTE: return "write_byte"; case UINT: @@ -347,10 +351,10 @@ public String getDataWriterCall(SimpleTypeReference simpleTypeReference) { if (sizeInBits <= 32) return "write_float"; return "write_double"; case STRING: - return "write_string"; + return "write_str"; case VSTRING: VstringTypeReference vstringTypeReference = (VstringTypeReference) simpleTypeReference; - return "write_string"; + return "write_str"; case TIME: return "write_time"; case DATE: @@ -373,35 +377,45 @@ public String getPlcValueTypeForTypeReference(TypeReference typeReference) { SimpleTypeReference simpleTypeReference = (SimpleTypeReference) typeReference; switch (simpleTypeReference.getBaseType()) { case BIT: + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcBOOL"); return "PlcBOOL"; case BYTE: + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcSINT"); return "PlcSINT"; case UINT: IntegerTypeReference unsignedIntegerTypeReference = (IntegerTypeReference) simpleTypeReference; if (unsignedIntegerTypeReference.getSizeInBits() <= 4) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcUSINT"); return "PlcUSINT"; } if (unsignedIntegerTypeReference.getSizeInBits() <= 8) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcUINT"); return "PlcUINT"; } if (unsignedIntegerTypeReference.getSizeInBits() <= 16) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcUDINT"); return "PlcUDINT"; } if (unsignedIntegerTypeReference.getSizeInBits() <= 32) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcULINT"); return "PlcULINT"; } case INT: IntegerTypeReference integerTypeReference = (IntegerTypeReference) simpleTypeReference; if (integerTypeReference.getSizeInBits() <= 8) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcSINT"); return "PlcSINT"; } if (integerTypeReference.getSizeInBits() <= 16) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcINT"); return "PlcINT"; } if (integerTypeReference.getSizeInBits() <= 32) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcDINT"); return "PlcDINT"; } if (integerTypeReference.getSizeInBits() <= 64) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcLINT"); return "PlcLINT"; } @@ -410,17 +424,21 @@ public String getPlcValueTypeForTypeReference(TypeReference typeReference) { FloatTypeReference floatTypeReference = (FloatTypeReference) simpleTypeReference; int sizeInBits = floatTypeReference.getSizeInBits(); if (sizeInBits <= 32) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcREAL"); return "PlcREAL"; } if (sizeInBits <= 64) { + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcLREAL"); return "PlcLREAL"; } case STRING: case VSTRING: + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcSTRING"); return "PlcSTRING"; case TIME: case DATE: case DATETIME: + emitRequiredImport("from plc4py.spi.values.PlcValues import PlcTIME"); return "PlcTIME"; default: return ""; @@ -516,7 +534,7 @@ public String getReadBufferReadMethodCall(String logicalName, SimpleTypeReferenc } else if (unsignedIntegerTypeReference.getSizeInBits() <= 32) { unsignedIntegerType = "unsigned_long"; } else { - unsignedIntegerType = "unsigned_big_integer"; + unsignedIntegerType = "unsigned_long"; } return "read_buffer.read_" + unsignedIntegerType + "(" + simpleTypeReference.getSizeInBits() + ", logical_name=\"" + logicalName + "\")"; case INT: @@ -530,7 +548,7 @@ public String getReadBufferReadMethodCall(String logicalName, SimpleTypeReferenc } else if (simpleTypeReference.getSizeInBits() <= 64) { integerType = "long"; } else { - integerType = "big_integer"; + integerType = "long"; } return "read_buffer.read_" + integerType + "(" + simpleTypeReference.getSizeInBits() + ", logical_name=\"" + logicalName + "\")"; case FLOAT: @@ -538,7 +556,7 @@ public String getReadBufferReadMethodCall(String logicalName, SimpleTypeReferenc return "read_buffer.read_" + floatType + "(" + simpleTypeReference.getSizeInBits() + ", logical_name=\"" + logicalName + "\")"; case STRING: case VSTRING: - String stringType = "string"; + String stringType = "str"; final Term encodingTerm = field.getEncoding().orElse(new DefaultStringLiteral("UTF-8")); if (!(encodingTerm instanceof StringLiteral)) { throw new FreemarkerException("Encoding must be a quoted string value"); @@ -586,49 +604,49 @@ public String getWriteBufferWriteMethodCall(String logicalName, SimpleTypeRefere } switch (simpleTypeReference.getBaseType()) { case BIT: - return "writeBuffer.WriteBit(\"" + logicalName + "\", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_bit(" + fieldName + ", \"" + logicalName + "\"" + writerArgsString + ")"; case BYTE: - return "writeBuffer.WriteByte(\"" + logicalName + "\", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_byte(" + fieldName + ", \"" + logicalName + "\"" + writerArgsString + ")"; case UINT: IntegerTypeReference unsignedIntegerTypeReference = (IntegerTypeReference) simpleTypeReference; if (unsignedIntegerTypeReference.getSizeInBits() <= 8) { - return "writeBuffer.WriteUint8(\"" + logicalName + "\", " + unsignedIntegerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_byte(" + fieldName + ", " + unsignedIntegerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } if (unsignedIntegerTypeReference.getSizeInBits() <= 16) { - return "writeBuffer.WriteUint16(\"" + logicalName + "\", " + unsignedIntegerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_unsigned_short(" + fieldName + ", " + unsignedIntegerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } if (unsignedIntegerTypeReference.getSizeInBits() <= 32) { - return "writeBuffer.WriteUint32(\"" + logicalName + "\", " + unsignedIntegerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_unsigned_int(" + fieldName + ", " + unsignedIntegerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } if (unsignedIntegerTypeReference.getSizeInBits() <= 64) { - return "writeBuffer.WriteUint64(\"" + logicalName + "\", " + unsignedIntegerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_unsigned_long(" + fieldName + ", " + unsignedIntegerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } - return "writeBuffer.WriteBigInt(\"" + logicalName + "\", " + unsignedIntegerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_unsigned_long(" + fieldName + ", " + unsignedIntegerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; case INT: IntegerTypeReference integerTypeReference = (IntegerTypeReference) simpleTypeReference; if (integerTypeReference.getSizeInBits() <= 8) { - return "writeBuffer.WriteInt8(\"" + logicalName + "\", " + integerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_signed_byte(" + fieldName + ", " + integerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } if (integerTypeReference.getSizeInBits() <= 16) { - return "writeBuffer.WriteInt16(\"" + logicalName + "\", " + integerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_short(" + fieldName + ", " + integerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } if (integerTypeReference.getSizeInBits() <= 32) { - return "writeBuffer.WriteInt32(\"" + logicalName + "\", " + integerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_int(" + fieldName + ", " + integerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } if (integerTypeReference.getSizeInBits() <= 64) { - return "writeBuffer.WriteInt64(\"" + logicalName + "\", " + integerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_long(" + fieldName + ", " + integerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } - return "writeBuffer.WriteBigInt(\"" + logicalName + "\", " + integerTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_long(" + fieldName + ", " + integerTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; case FLOAT: case UFLOAT: FloatTypeReference floatTypeReference = (FloatTypeReference) simpleTypeReference; if (floatTypeReference.getSizeInBits() <= 32) { - return "writeBuffer.WriteFloat32(\"" + logicalName + "\", " + floatTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_float(" + fieldName + ", " + floatTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } if (floatTypeReference.getSizeInBits() <= 64) { - return "writeBuffer.WriteFloat64(\"" + logicalName + "\", " + floatTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_double(" + fieldName + ", " + floatTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; } - return "writeBuffer.WriteBigFloat(\"" + logicalName + "\", " + floatTypeReference.getSizeInBits() + ", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_double(" + fieldName + ", " + floatTypeReference.getSizeInBits() + ", \"" + logicalName + "\"" + writerArgsString + ")"; case STRING: { StringTypeReference stringTypeReference = (StringTypeReference) simpleTypeReference; final Term encodingTerm = field.getEncoding().orElse(new DefaultStringLiteral("UTF-8")); @@ -637,8 +655,8 @@ public String getWriteBufferWriteMethodCall(String logicalName, SimpleTypeRefere .asStringLiteral() .orElseThrow(() -> new FreemarkerException("Encoding must be a quoted string value")).getValue(); String length = Integer.toString(simpleTypeReference.getSizeInBits()); - return "writeBuffer.WriteString(\"" + logicalName + "\", uint32(" + length + "), \"" + - encoding + "\", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_str(" + fieldName + ", " + length + ", \"" + + encoding + "\", \"" + logicalName + "\"" + writerArgsString + ")"; } case VSTRING: { VstringTypeReference vstringTypeReference = (VstringTypeReference) simpleTypeReference; @@ -649,13 +667,13 @@ public String getWriteBufferWriteMethodCall(String logicalName, SimpleTypeRefere .orElseThrow(() -> new FreemarkerException("Encoding must be a quoted string value")).getValue(); String lengthExpression = toExpression(field, null, vstringTypeReference.getLengthExpression(), null, Collections.singletonList(new DefaultArgument("stringLength", new DefaultIntegerTypeReference(SimpleTypeReference.SimpleBaseType.INT, 32))), true, false); String length = Integer.toString(simpleTypeReference.getSizeInBits()); - return "writeBuffer.WriteString(\"" + logicalName + "\", uint32(" + lengthExpression + "), \"" + - encoding + "\", " + fieldName + writerArgsString + ")"; + return "write_buffer.write_str(" + fieldName + ", " + lengthExpression + ", \"" + + encoding + "\", \"" + logicalName + "\"" + writerArgsString + ")"; } case DATE: case TIME: case DATETIME: - return "writeBuffer.WriteUint32(\"" + logicalName + "\", uint32(" + fieldName + ")" + writerArgsString + ")"; + return "write_buffer.write_unsigned_int(uint32(" + fieldName + "), \"" + logicalName + "\")" + writerArgsString + ")"; default: throw new FreemarkerException("Unsupported base type " + simpleTypeReference.getBaseType()); } @@ -1026,7 +1044,7 @@ else if ((variableLiteral.getChild().isPresent()) && ((ComplexTypeDefinition) th if ((serializerArguments != null) && serializerArguments.stream() .anyMatch(argument -> argument.getName().equals(variableLiteralName)) && "stringLength".equals(variableLiteralName)) { tracer = tracer.dive("serialization argument"); - return tracer + variableLiteralName + + return tracer + camelCaseToSnakeCase(variableLiteralName) + variableLiteral.getChild() .map(child -> "." + camelCaseToSnakeCase(toVariableExpression(field, typeReference, child, parserArguments, serializerArguments, false, suppressPointerAccess, true))) .orElse(""); @@ -1041,7 +1059,7 @@ else if ((variableLiteral.getChild().isPresent()) && ((ComplexTypeDefinition) th if ((parserArguments != null) && parserArguments.stream() .anyMatch(argument -> argument.getName().equals(variableLiteralName))) { tracer = tracer.dive("parser argument"); - return tracer + variableLiteralName + + return tracer + camelCaseToSnakeCase(variableLiteralName) + variableLiteral.getChild() .map(child -> "." + camelCaseToSnakeCase(toVariableExpression(field, typeReference, child, parserArguments, serializerArguments, false, suppressPointerAccess, true))) .orElse(""); @@ -1058,7 +1076,7 @@ else if ((variableLiteral.getChild().isPresent()) && ((ComplexTypeDefinition) th if (isChild) { variableAccess = "get_" + camelCaseToSnakeCase(variableAccess) + "()"; } - return tracer + (serialize ? "self." + camelCaseToSnakeCase(variableLiteralName) + "" : variableAccess) + indexCall + + return tracer + (serialize ? "self." + camelCaseToSnakeCase(variableLiteralName) + "" : camelCaseToSnakeCase(variableAccess)) + indexCall + variableLiteral.getChild() .map(child -> "." + camelCaseToSnakeCase(toVariableExpression(field, typeReference, child, parserArguments, serializerArguments, false, suppressPointerAccess, true))) .orElse(""); @@ -1066,7 +1084,7 @@ else if ((variableLiteral.getChild().isPresent()) && ((ComplexTypeDefinition) th private String toUppercaseVariableExpression(Field field, TypeReference typeReference, VariableLiteral variableLiteral, List parserArguments, List serializerArguments, boolean serialize, boolean suppressPointerAccess, Tracer tracer) { tracer = tracer.dive("toUppercaseVariableExpression"); - StringBuilder sb = new StringBuilder("get_" + camelCaseToSnakeCase(variableLiteral.getName()) + "()"); + StringBuilder sb = new StringBuilder(variableLiteral.getName().toUpperCase()); if (variableLiteral.getArgs().isPresent()) { sb.append("("); boolean firstArg = true; @@ -1220,7 +1238,7 @@ else if (isTypeArg) { break; } } else { - sb.append("self." + toVariableExpression(field, typeReference, va, parserArguments, serializerArguments, serialize, suppressPointerAccess)); + sb.append(toVariableExpression(field, typeReference, va, parserArguments, serializerArguments, serialize, suppressPointerAccess)); } } else if (arg instanceof StringLiteral) { tracer = tracer.dive("StringLiteral"); @@ -1305,12 +1323,12 @@ private String toValueVariableExpression(Field field, TypeReference typeReferenc private String toLengthInBitsVariableExpression(TypeReference typeReference, boolean serialize, Tracer tracer) { tracer = tracer.dive("lengthInBits"); - return tracer + (serialize ? getCastExpressionForTypeReference(typeReference) + "(self.get" : "get") + "length_in_bits" + (serialize ? "(ctx))" : "(ctx)"); + return tracer + (serialize ? getCastExpressionForTypeReference(typeReference) + "(" : "") + "length_in_bits" + (serialize ? "())" : "()"); } private String toLengthInBytesVariableExpression(TypeReference typeReference, boolean serialize, Tracer tracer) { tracer = tracer.dive("lengthInBytes"); - return tracer + (serialize ? getCastExpressionForTypeReference(typeReference) + "(self.get" : "Get") + "length_in_bytes" + (serialize ? "(ctx))" : "(ctx)"); + return tracer + (serialize ? getCastExpressionForTypeReference(typeReference) + "(" : "") + "length_in_bytes" + (serialize ? "())" : "()"); } public String getSizeInBits(ComplexTypeDefinition complexTypeDefinition, List parserArguments) { diff --git a/code-generation/language-python/src/main/resources/templates/python/complex-type-template.python.ftlh b/code-generation/language-python/src/main/resources/templates/python/complex-type-template.python.ftlh index e74fa747218..fab78e3a73e 100644 --- a/code-generation/language-python/src/main/resources/templates/python/complex-type-template.python.ftlh +++ b/code-generation/language-python/src/main/resources/templates/python/complex-type-template.python.ftlh @@ -66,7 +66,7 @@ ${import} <@emitImport import="from plc4py.api.messages.PlcMessage import PlcMessage" /> <@emitImport import="from plc4py.spi.generation.WriteBuffer import WriteBuffer" /> @dataclass -class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if type.isDiscriminatedParentTypeDefinition()>ABC, <@emitImport import="from abc import ABC" />PlcMessage<#if type.parentType.isPresent()>,${type.parentType.orElseThrow().name}<@emitImport import="from plc4py.protocols.${protocolName}.${outputFlavor?replace('-', '')}.${type.parentType.orElseThrow().name} import ${type.parentType.orElseThrow().name}" />): +class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if type.isDiscriminatedParentTypeDefinition()>ABC, PlcMessage<@emitImport import="from abc import ABC" /><#if type.parentType.isPresent()>${type.parentType.orElseThrow().name}<@emitImport import="from plc4py.protocols.${protocolName}.${outputFlavor?replace('-', '')}.${type.parentType.orElseThrow().name} import ${type.parentType.orElseThrow().name}" />): <#if parserArguments?has_content> <#assign filteredParserArguments=parserArguments?filter(arg -> !type.isDiscriminatorField(arg.name) && !type.getPropertyFieldFromThisOrParentByName(arg.name).isPresent())> @@ -92,7 +92,7 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#-- If the current type contains "const" fields, generate some Python constants for holing their values --> <#if type.constFields?has_content> <#list type.constFields as field> - ${field.name?upper_case}: ${helper.getLanguageTypeNameForTypeReference(field.type)} = ${helper.toParseExpression(field, field.type, field.referenceValue, parserArguments)} + ${helper.camelCaseToSnakeCase(field.name)?upper_case}: ${helper.getLanguageTypeNameForTypeReference(field.type)} = ${helper.toParseExpression(field, field.type, field.referenceValue, parserArguments)} <#-- @@ -122,30 +122,6 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty - - <#-- getAllPropertyFields() returns not only the property fields of this type but also of it's parents --> - def __post_init__(self): - <@compress single_line=true> super().__init__( - <#if type.parentPropertyFields?has_content> - <#list type.parentPropertyFields as field> - self.${helper.camelCaseToSnakeCase(field.name)} - <#sep>, - - - <#if type.parentType.isPresent() && type.parentType.orElseThrow().allParserArguments.isPresent()> - <#assign filteredParentParserArguments = type.parentType.orElseThrow().allParserArguments.orElseThrow()?filter(arg -> !type.parentType.orElseThrow().asComplexTypeDefinition().orElseThrow().isDiscriminatorField(arg.name))> - <#if filteredParentParserArguments?has_content> - <#if type.parentPropertyFields?has_content>, - <#list filteredParentParserArguments as parserArgument> - self.${helper.camelCaseToSnakeCase(parserArgument.name)} - <#sep>, - - - - ) - - - <#-- If this is a discriminated parent type, we need to generate the abstract methods for accessing it's discriminator values instead. @@ -206,6 +182,7 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty def serialize(self, write_buffer: WriteBuffer): <#if helper.hasFieldOfType("unknown")> + <@emitImport import="from plc4py.api.exceptions.exceptions import SerializationException" /> raise SerializationException("Unknown field not serializable") <#else> <#if helper.requiresStartPos() || helper.requiresCurPos()> @@ -244,7 +221,7 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#assign namedField = field.asNamedField().orElseThrow()> # Const Field (${constField.name}) - <#if typedField.type.isEnumTypeReference()>write_buffer.${helper.getDataWriterCall(helper.getEnumBaseTypeReference(typedField.type), namedField.name)}(self.${helper.camelCaseToSnakeCase(namedField.name)}.value, logical_name="${constField.name}")<#else>write_buffer.${helper.getDataWriterCall(typedField.type, namedField.name)}(self.${helper.camelCaseToSnakeCase(namedField.name)}.value, logical_name="${constField.name}") + <#if typedField.type.isEnumTypeReference()>write_buffer.${helper.getDataWriterCall(helper.getEnumBaseTypeReference(typedField.type), namedField.name)}(self.${helper.camelCaseToSnakeCase(namedField.name)?upper_case}.value, logical_name="${constField.name}")<#else>write_buffer.${helper.getDataWriterCall(typedField.type, namedField.name)}(self.${helper.camelCaseToSnakeCase(namedField.name)?upper_case}, logical_name="${constField.name}") <#break> <#case "discriminator"> <#assign discriminatorField = field.asDiscriminatorField().orElseThrow()> @@ -253,9 +230,10 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty # Discriminator Field (${discriminatorField.name}) (Used as input to a switch field) <#if typedField.type.isEnumTypeReference()> - write_buffer.${helper.getEnumDataWriterCall(typedField.type, namedField.name, "value")}(self.${helper.camelCaseToSnakeCase(discriminatorField.name)}(), logical_name="${namedField.name}") + write_buffer.${helper.getEnumDataWriterCall(typedField.type, namedField.name, "value")}(self.${helper.camelCaseToSnakeCase(discriminatorField.name)}, logical_name="${namedField.name}", ${helper.getFieldOptions(typedField, parserArguments)}) <#else> - write_buffer.${helper.getDataWriterCall(typedField.type, namedField.name)}(self.${helper.camelCaseToSnakeCase(discriminatorField.name)}(), logical_name="${namedField.name}") + <#assign simpleTypeReference = discriminatorField.type.asSimpleTypeReference().orElseThrow()> + write_buffer.${helper.getDataWriterCall(typedField.type, namedField.name)}(self.${helper.camelCaseToSnakeCase(discriminatorField.name)}, logical_name="${namedField.name}", bit_length=${simpleTypeReference.sizeInBits}, ${helper.getFieldOptions(typedField, parserArguments)}) <#break> <#case "enum"> @@ -318,7 +296,7 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#assign typedField = field.asTypedField().orElseThrow()> # Reserved Field (reserved) - write_buffer.${helper.getDataWriterCall(typedField.type, "reserved")}(self.reserved_field_${reservedFieldIndex}!=None?self.reserved_field_${reservedFieldIndex}: ${helper.getReservedValue(reservedField)}, logical_name="reserved")<#assign reservedFieldIndex=reservedFieldIndex+1> + write_buffer.${helper.getDataWriterCall(typedField.type, "reserved")}(self.reserved_field_${reservedFieldIndex} if self.reserved_field_${reservedFieldIndex} is not None else ${helper.getReservedValue(reservedField)}, logical_name="reserved")<#assign reservedFieldIndex=reservedFieldIndex+1> <#break> <#case "simple"> <#assign simpleField = field.asSimpleField().orElseThrow()> @@ -357,10 +335,10 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <@emitImport import="import math" /> def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = <#if type.parentType.isPresent()>super().get_length_in_bits()<#else>0 + def length_in_bits(self) -> int: + length_in_bits: int = <#if type.parentType.isPresent()>super().length_in_bits()<#else>0 _value: ${type.name} = self <#list type.fields as field> <#switch field.typeName> @@ -369,20 +347,18 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#assign arrayElementTypeReference = arrayField.type.asArrayTypeReference().orElseThrow().getElementTypeReference()> # Array field - if self.${helper.camelCaseToSnakeCase(arrayField.name)} != None: + if self.${helper.camelCaseToSnakeCase(arrayField.name)} is not None: <#if arrayElementTypeReference.isSimpleTypeReference()> <#assign simpleTypeReference = arrayElementTypeReference.asSimpleTypeReference().orElseThrow()> length_in_bits += ${simpleTypeReference.sizeInBits} * len(self.${helper.camelCaseToSnakeCase(arrayField.name)}) <#elseif arrayField.isCountArrayField()> - i: int = 0 <#assign nonSimpleTypeReference = arrayElementTypeReference.asNonSimpleTypeReference().orElseThrow()> for element in self.${helper.camelCaseToSnakeCase(arrayField.name)}: - last: bool = ++i >= len(self.${helper.camelCaseToSnakeCase(arrayField.name)}) - length_in_bits += element.get_length_in_bits() + length_in_bits += element.length_in_bits() <#else> for element in self.${helper.camelCaseToSnakeCase(arrayField.name)}: - length_in_bits += element.get_length_in_bits() + length_in_bits += element.length_in_bits() @@ -422,7 +398,7 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#elseif helper.isEnumField(field)> length_in_bits += ${helper.getEnumBaseTypeReference(discriminatorField.type).sizeInBits} <#else> - length_in_bits += self.${helper.camelCaseToSnakeCase(discriminatorField.name)}.get_length_in_bits() + length_in_bits += self.${helper.camelCaseToSnakeCase(discriminatorField.name)}.length_in_bits() <#break> <#case "enum"> @@ -467,9 +443,9 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#elseif helper.isEnumField(field)> length_in_bits += ${helper.getEnumBaseTypeReference(optionalField.type).sizeInBits} <#elseif optionalField.type.isDataIoTypeReference()> - length_in_bits += ${optionalField.type.asComplexTypeReference().orElseThrow().name}.get_length_in_bits(self.${helper.camelCaseToSnakeCase(optionalField.name)}<#if optionalField.type.asComplexTypeReference().orElseThrow().params?has_content>, <#list optionalField.type.asComplexTypeReference().orElseThrow().params.orElseThrow() as param>${helper.toParseExpression(optionalField, helper.anyTypeReference, param, parserArguments)}<#sep>, ) + length_in_bits += ${optionalField.type.asComplexTypeReference().orElseThrow().name}.length_in_bits(self.${helper.camelCaseToSnakeCase(optionalField.name)}<#if optionalField.type.asComplexTypeReference().orElseThrow().params?has_content>, <#list optionalField.type.asComplexTypeReference().orElseThrow().params.orElseThrow() as param>${helper.toParseExpression(optionalField, helper.anyTypeReference, param, parserArguments)}<#sep>, ) <#else> - length_in_bits += self.${helper.camelCaseToSnakeCase(optionalField.name)}.get_length_in_bits() + length_in_bits += self.${helper.camelCaseToSnakeCase(optionalField.name)}.length_in_bits() <#break> @@ -506,9 +482,9 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#elseif helper.isEnumField(field)> length_in_bits += ${helper.getEnumBaseTypeReference(simpleField.type).sizeInBits} <#elseif simpleField.type.isDataIoTypeReference()> - length_in_bits += self.${helper.camelCaseToSnakeCase(simpleField.type.asComplexTypeReference().orElseThrow().name)}.get_length_in_bits(${simpleField.name}<#if simpleField.type.asComplexTypeReference().orElseThrow().params?has_content>, <#list simpleField.type.asComplexTypeReference().orElseThrow().params.orElseThrow() as param>${helper.toParseExpression(simpleField, helper.anyTypeReference, param, parserArguments)}<#sep>, ) + length_in_bits += self.${helper.camelCaseToSnakeCase(simpleField.type.asComplexTypeReference().orElseThrow().name)}.length_in_bits(${simpleField.name}<#if simpleField.type.asComplexTypeReference().orElseThrow().params?has_content>, <#list simpleField.type.asComplexTypeReference().orElseThrow().params.orElseThrow() as param>${helper.toParseExpression(simpleField, helper.anyTypeReference, param, parserArguments)}<#sep>, ) <#else> - length_in_bits += self.${helper.camelCaseToSnakeCase(simpleField.name)}.get_length_in_bits() + length_in_bits += self.${helper.camelCaseToSnakeCase(simpleField.name)}.length_in_bits() <#break> <#case "switch"> @@ -537,35 +513,36 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#-- The parse and serialize methods here are just proxies for forwardning the requests to static counterparts --> <#if !type.isDiscriminatedChildTypeDefinition()> <@emitImport import="from plc4py.spi.generation.ReadBuffer import ReadBuffer" /> - def static_parse(self, read_buffer: ReadBuffer , args): + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): <#if parserArguments?has_content> <@emitImport import="from plc4py.api.exceptions.exceptions import PlcRuntimeException" /> - if args is None: + + if kwargs is None: raise PlcRuntimeException("Wrong number of arguments, expected ${parserArguments?size}, but got None") - elif args.length != ${parserArguments?size}: - raise PlcRuntimeException("Wrong number of arguments, expected ${parserArguments?size}, but got " + str(len(args))) <#list parserArguments as parserArgument> <#assign languageName=helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)> - ${parserArgument.name}: ${languageName} = ${helper.getNullValueForTypeReference(parserArgument.type)} - if isinstance(args[${parserArgument?index}], ${languageName}): - ${parserArgument.name} = ${languageName}(args[${parserArgument?index}]) + ${helper.camelCaseToSnakeCase(parserArgument.name)}: ${languageName} = ${helper.getNullValueForTypeReference(parserArgument.type)} + if isinstance(kwargs.get("${parserArgument.name}"), ${languageName}): + ${helper.camelCaseToSnakeCase(parserArgument.name)} = ${languageName}(kwargs.get("${parserArgument.name}")) <#if parserArgument.type.isSimpleTypeReference() || parserArgument.type.isEnumTypeReference()> - elif isinstance(args[${parserArgument?index}], str): - ${parserArgument.name} = ${languageName}(str(args[${parserArgument?index}])) + elif isinstance(kwargs.get("${parserArgument.name}"), str): + ${helper.camelCaseToSnakeCase(parserArgument.name)} = ${languageName}(str(kwargs.get("${parserArgument.name}"))) else: - raise PlcRuntimeException("Argument ${parserArgument?index} expected to be of type ${languageName} or a string which is parseable but was " + args[${parserArgument?index}].getClass().getName()) + raise PlcRuntimeException("Argument ${parserArgument?index} expected to be of type ${languageName} or a string which is parseable but was " + kwargs.get("${parserArgument.name}").getClass().getName()) - return self.static_parse_context(read_buffer<#if parserArguments?has_content>, <#list parserArguments as parserArgument>${parserArgument.name}<#sep>, ) + return ${type.name}.static_parse_context(read_buffer<#if parserArguments?has_content>, <#list parserArguments as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}<#sep>, ) <#-- Here come the actual parse and serialize methods that actually do the parsing and serlaizing --> <#assign hasParserArguments=parserArguments?has_content/> <#assign parserArgumentList><#if hasParserArguments><#list parserArguments as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, + <#assign parsedList><#if hasParserArguments><#list parserArguments as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}=${helper.camelCaseToSnakeCase(parserArgument.name)}<#sep>, <@emitImport import="from plc4py.spi.generation.ReadBuffer import ReadBuffer" /> @staticmethod def <#if type.isDiscriminatedChildTypeDefinition()>static_parse_builder<#else>static_parse_context(read_buffer: ReadBuffer<#if hasParserArguments>, ${parserArgumentList}): @@ -588,21 +565,24 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty raise ParseException("array fields of type byte only support 'count' and 'length' loop-types.") <@emitImport import="from typing import List" /> - ${helper.camelCaseToSnakeCase(namedField.name)}: List[int] = read_buffer.read_byte_array("${namedField.name}", int(${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}) + <@emitImport import="from typing import Any" /> + ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field(logical_name="${arrayField.name}", read_function=<#if arrayElementTypeReference.isComplexTypeReference()><#else>read_buffer.${helper.getDataReaderCall(arrayField.type)}<#if arrayElementTypeReference.isComplexTypeReference()><#else>, count=${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#else> <#-- If this is a count array, we can directly initialize an array with the given size --> <#if field.isCountArrayField()> <@emitImport import="from typing import List" /> <@emitImport import="from typing import Any" /> - ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field("${arrayField.name}", read_buffer.${helper.getDataReaderCall(arrayField.type)}, count=${helper.camelCaseToSnakeCase(helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments))}${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field(logical_name="${arrayField.name}", read_function=<#if arrayElementTypeReference.isComplexTypeReference()><#else>read_buffer.${helper.getDataReaderCall(arrayField.type)}<#if arrayElementTypeReference.isComplexTypeReference()><#else>, count=${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#-- In all other cases do we have to work with a list, that is later converted to an array --> <#else> <#-- For a length array, we read data till the read position of the buffer reaches a given position --> + <@emitImport import="from typing import List" /> + <@emitImport import="from typing import Any" /> <#if field.isLengthArrayField()> - ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field("${arrayField.name}", read_buffer.${helper.getDataReaderCall(arrayField.type)}, length=${helper.camelCaseToSnakeCase(helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments))}${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field(logical_name="${arrayField.name}", read_function=<#if arrayElementTypeReference.isComplexTypeReference()><#else>read_buffer.${helper.getDataReaderCall(arrayField.type)}<#if arrayElementTypeReference.isComplexTypeReference()><#else>, length=${helper.camelCaseToSnakeCase(helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments))}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#-- A terminated array keeps on reading data as long as the termination expression evaluates to false --> <#elseif field.isTerminatedArrayField()> - ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field("${arrayField.name}", read_buffer.${helper.getDataReaderCall(arrayField.type)}, terminated=lambda : (c_bool(${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments)}))${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field(logical_name="${arrayField.name}", read_function=<#if arrayElementTypeReference.isComplexTypeReference()><#else>read_buffer.${helper.getDataReaderCall(arrayField.type)}<#if arrayElementTypeReference.isComplexTypeReference()><#else>, terminated=lambda : (c_bool(${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression, parserArguments)}))${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) @@ -612,42 +592,49 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}, (${helper.getLanguageTypeNameForField(field)}) (${helper.toParseExpression(assertField, assertField.type, assertField.conditionExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(assertField.type)}(logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "checksum"> <#assign checksumField = field.asChecksumField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> + <@emitImport import="from plc4py.protocols.${protocolName} import StaticHelper" /> - ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}, (${helper.getLanguageTypeNameForField(field)}) (${helper.toParseExpression(checksumField, checksumField.type, checksumField.checksumExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(checksumField.type)}(logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "const"> <#assign constField = field.asConstField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - self.${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}, ${type.name}.${namedField.name?upper_case}${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(namedField.name)?upper_case}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(constField.type)}(logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "discriminator"> <#assign discriminatorField = field.asDiscriminatorField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> + <#if typedField.type.isSimpleTypeReference()> + <#assign simpleTypeReference = typedField.type.asSimpleTypeReference().orElseThrow()> + ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(discriminatorField.type)}(logical_name="${namedField.name}", bit_length=${simpleTypeReference.sizeInBits}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) + <#else> + ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(discriminatorField.type)}(logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) + + - ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}${helper.getFieldOptions(typedField, parserArguments)}) <#break> <#case "enum"> <#assign enumField = field.asEnumField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - self.${helper.camelCaseToSnakeCase(namedField.name)} = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", "${enumField.type.asNonSimpleTypeReference().orElseThrow().typeDefinition.name}", readEnum(${enumField.type.asNonSimpleTypeReference().orElseThrow().typeDefinition.name}::firstEnumForField${enumField.fieldName?cap_first}, ${helper.getDataReaderCall(helper.getEnumFieldTypeReference(enumField.type, enumField.fieldName))})${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(namedField.name)} = read_buffer.${helper.getDataReaderCall(enumField.type)}(logical_name="${namedField.name}", readEnum(${enumField.type.asNonSimpleTypeReference().orElseThrow().typeDefinition.name}::firstEnumForField${enumField.fieldName?cap_first}, ${helper.getDataReaderCall(helper.getEnumFieldTypeReference(enumField.type, enumField.fieldName))}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "implicit"> <#assign implicitField = field.asImplicitField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(implicitField.type)}(logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "manualArray"> <#assign manualArrayField = field.asManualArrayField().orElseThrow()> @@ -657,9 +644,12 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#if arrayElementTypeReference.isByteBased()> <@emitImport import="from typing import List" /> - self.${helper.camelCaseToSnakeCase(namedField.name)} = read_manual_byte_array_field("${namedField.name}", read_buffer, lambda _values: bool(${helper.toParseExpression(manualArrayField, helper.boolTypeReference, manualArrayField.loopExpression, parserArguments)}), lambda : byte(${helper.toParseExpression(manualArrayField, manualArrayField.type, manualArrayField.parseExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}) + <@emitImport import="from typing import Any" /> + ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field(logical_name="${manualArrayField.name}", read_function=<#if manualArrayField.type.isComplexTypeReference()><#else>read_buffer.${helper.getDataReaderCall(manualArrayField.type)}manual_start = lambda _values: bool(${helper.toParseExpression(manualArrayField, helper.boolTypeReference, manualArrayField.loopExpression, parserArguments)}), manual_stop = lambda : byte(${helper.toParseExpression(manualArrayField, manualArrayField.type, manualArrayField.parseExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#else> - self.${helper.camelCaseToSnakeCase(namedField.name)} = read_manual_array_field("${namedField.name}", read_buffer, lambda _values: ${helper.getNonPrimitiveLanguageTypeNameForField(manualArrayField)} : bool(${helper.toParseExpression(manualArrayField, helper.boolTypeReference, manualArrayField.loopExpression, parserArguments)}), lambda : ${helper.getLanguageTypeNameForTypeReference(manualArrayField.type.elementTypeReference)}(${helper.toParseExpression(manualArrayField, manualArrayField.type, manualArrayField.parseExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}) + <@emitImport import="from typing import List" /> + <@emitImport import="from typing import Any" /> + ${helper.camelCaseToSnakeCase(arrayField.name)}: List[Any] = read_buffer.read_array_field(logical_name="${manualArrayField.name}", read_function=<#if manualArrayField.type.isComplexTypeReference()><#else>read_buffer.${helper.getDataReaderCall(manualArrayField.type)}manual_start = lambda _values: ${helper.getNonPrimitiveLanguageTypeNameForField(manualArrayField)} : bool(${helper.toParseExpression(manualArrayField, helper.boolTypeReference, manualArrayField.loopExpression, parserArguments)}), lambda : ${helper.getLanguageTypeNameForTypeReference(manualArrayField.type.elementTypeReference)}(${helper.toParseExpression(manualArrayField, manualArrayField.type, manualArrayField.parseExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "manual"> @@ -667,34 +657,41 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - self.${helper.camelCaseToSnakeCase(manualField.name)} = read_manual_field("${namedField.name}", read_buffer, lambda : ${helper.getLanguageTypeNameForField(manualField)}(${helper.toParseExpression(manualField, manualField.type, manualField.parseExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(manualField.name)} = read_buffer.${helper.getDataReaderCall(manualField.type)}(logical_name="${namedField.name}", read_buffer, lambda : ${helper.getLanguageTypeNameForField(manualField)}(${helper.toParseExpression(manualField, manualField.type, manualField.parseExpression, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "optional"> <#assign optionalField = field.asOptionalField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - self.${helper.camelCaseToSnakeCase(namedField.name)} = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}<#if optionalField.conditionExpression.present>, ${helper.toParseExpression(optionalField, helper.boolTypeReference, optionalField.conditionExpression.get(), parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}) + ${helper.camelCaseToSnakeCase(namedField.name)} = read_buffer.${helper.getDataReaderCall(optionalField.type)}(logical_name="${namedField.name}"<#if optionalField.conditionExpression.present>, ${helper.toParseExpression(optionalField, helper.boolTypeReference, optionalField.conditionExpression.get(), parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "padding"> <#assign paddingField = field.asPaddingField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign simpleTypeReference = paddingField.type.asSimpleTypeReference().orElseThrow()> - read_${helper.camelCaseToSnakeCase(field.typeName)}_field(${helper.getDataReaderCall(typedField.type)}, (int) (${helper.toParseExpression(paddingField, paddingField.type, paddingField.paddingCondition, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}) + read_buffer.${helper.getDataReaderCall(paddingField.type)}(int) (${helper.toParseExpression(paddingField, paddingField.type, paddingField.paddingCondition, parserArguments)})${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "reserved"> <#assign reservedField = field.asReservedField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> - reserved_field_${reservedFieldIndex}: ${helper.getLanguageTypeNameForTypeReference(reservedField.type, false)}<#assign reservedFieldIndex=reservedFieldIndex+1> = read_${helper.camelCaseToSnakeCase(field.typeName)}_field("reserved", ${helper.getDataReaderCall(typedField.type)}, ${helper.getReservedValue(reservedField)}${helper.getFieldOptions(typedField, parserArguments)}) + reserved_field_${reservedFieldIndex}: ${helper.getLanguageTypeNameForTypeReference(reservedField.type, false)}<#assign reservedFieldIndex=reservedFieldIndex+1> = read_buffer.${helper.getDataReaderCall(reservedField.type)}(logical_name="reserved"${helper.getReservedValue(reservedField)}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "simple"> <#assign simpleField = field.asSimpleField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - self.${helper.camelCaseToSnakeCase(namedField.name)}= <#if typedField.type.isEnumTypeReference()>read_enum_field("${namedField.name}", "${helper.getLanguageTypeNameForField(field)}", ${helper.getDataReaderCall(typedField.type)}${helper.getFieldOptions(typedField, parserArguments)})<#else>read_${helper.camelCaseToSnakeCase(field.typeName)}_field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}${helper.getFieldOptions(typedField, parserArguments)}) + <#if typedField.type.isSimpleTypeReference()> + <#assign simpleTypeReference = typedField.type.asSimpleTypeReference().orElseThrow()> + ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForTypeReference(simpleField.type, false)} = <#if typedField.type.isEnumTypeReference()>read_buffer.${helper.getDataReaderCall(simpleField.type)}bit_length=${simpleTypeReference.sizeInBits}, logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList})<#else><#if simpleField.type.isComplexTypeReference()>read_buffer.${helper.getDataReaderCall(simpleField.type)}logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList})<#else>read_buffer.${helper.getDataReaderCall(simpleField.type)}(logical_name="${namedField.name}", bit_length=${simpleTypeReference.sizeInBits}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) + <#else> + ${helper.camelCaseToSnakeCase(namedField.name)}: ${helper.getLanguageTypeNameForTypeReference(simpleField.type, false)} = <#if typedField.type.isEnumTypeReference()>read_buffer.${helper.getDataReaderCall(simpleField.type)}bit_length=${helper.getEnumBaseTypeReference(typedField.type).sizeInBits}, logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList})<#else><#if simpleField.type.isComplexTypeReference()>read_buffer.${helper.getDataReaderCall(simpleField.type)}logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList})<#else>read_buffer.${helper.getDataReaderCall(simpleField.type)}(logical_name="${namedField.name}"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) + + + <#break> <#case "switch"> <#assign switchField = field.asSwitchField().orElseThrow()> @@ -703,6 +700,7 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty builder: ${type.name}Builder = None <#list switchField.cases as case> <#if case.discriminatorValueTerms?has_content> + from plc4py.protocols.${protocolName}.${outputFlavor?replace('-', '')}.${case.name} import ${case.name} if <@compress single_line=true> <#list case.discriminatorValueTerms as discriminatorValueTerm> <#if helper.isWildcard(discriminatorValueTerm)> @@ -710,41 +708,41 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#else> <#assign discriminatorExpression=switchField.discriminatorExpressions[discriminatorValueTerm?index].asLiteral().orElseThrow().asVariableLiteral().orElseThrow()> <#assign discriminatorType=helper.getDiscriminatorTypes()[discriminatorExpression.discriminatorName]> - EvaluationHelper.equals( - ${helper.toParseExpression(switchField, discriminatorType, discriminatorExpression, parserArguments)}, + ${helper.toParseExpression(switchField, discriminatorType, discriminatorExpression, parserArguments)} == <#if discriminatorType.isEnumTypeReference()> ${helper.getLanguageTypeNameForTypeReference(discriminatorType)}.${helper.toParseExpression(switchField, discriminatorType, discriminatorValueTerm, parserArguments)} <#else> ${helper.getLanguageTypeNameForTypeReference(discriminatorType, true)}(${helper.toParseExpression(switchField, discriminatorType, discriminatorValueTerm, parserArguments)}) - <#sep>) and + <#sep> and - ): + : builder = <@compress single_line=true> <#assign hasCaseParseArguments=case.allParserArguments.isPresent() && case.allParserArguments.orElseThrow()?has_content> - <#assign caseParseArguments><#if hasCaseParseArguments><#list case.allParserArguments.orElseThrow() as parserArgument>${parserArgument.name}<#sep>, - ${case.name}.staticParseBuilder(read_buffer<#if hasCaseParseArguments>, ${tracer.dive("case parse arguments")} ${caseParseArguments}) + <#assign caseParseArguments><#if hasCaseParseArguments><#list case.allParserArguments.orElseThrow() as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}<#sep>, + ${case.name}.static_parse_builder(read_buffer<#if hasCaseParseArguments>, ${tracer.dive("case parse arguments")} ${caseParseArguments}) + <@emitImport import="from plc4py.api.exceptions.exceptions import ParseException" /> if builder is None: - raise ParseException("Unsupported case for discriminated type"<#if switchField.getDiscriminatorExpressions()?has_content>+" parameters ["<#list switchField.getDiscriminatorExpressions() as discriminatorExpression>+"${discriminatorExpression.stringRepresentation()}="+${helper.toParseExpression(null, null, discriminatorExpression, parserArguments)}<#sep>+" "+"]") + raise ParseException("Unsupported case for discriminated type"<#if switchField.getDiscriminatorExpressions()?has_content>+" parameters ["<#list switchField.getDiscriminatorExpressions() as discriminatorExpression>+"${discriminatorExpression.stringRepresentation()}="+str(${helper.toParseExpression(null, null, discriminatorExpression, parserArguments)})<#sep>+" "+"]") <#break> <#case "unknown"> <#assign unknownField = field.asUnknownField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> - read${field.typeName?cap_first}Field("unknown", ${helper.getDataReaderCall(typedField.type)}${helper.getFieldOptions(typedField, parserArguments)}) + read_buffer.${helper.getDataReaderCall(unknownField.type)}(logical_name="unknown"${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "virtual"> <#assign virtualField = field.asVirtualField().orElseThrow()> <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - ${namedField.name}: ${helper.getLanguageTypeNameForField(field)} = read${field.typeName?cap_first}Field("${namedField.name}", ${helper.getLanguageTypeNameForField(field)}.class, ${helper.toParseExpression(virtualField, virtualField.type, virtualField.valueExpression, parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}) + ${namedField.name}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(virtualField.type)}(logical_name="${namedField.name}", ${helper.getLanguageTypeNameForField(field)}.class, ${helper.toParseExpression(virtualField, virtualField.type, virtualField.valueExpression, parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> <#case "validation"> <#assign validationField = field.asValidationField().orElseThrow()> @@ -760,7 +758,7 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#assign typedField = field.asTypedField().orElseThrow()> <#assign namedField = field.asNamedField().orElseThrow()> - ${namedField.name}: ${helper.getLanguageTypeNameForField(field)} = read${field.typeName?cap_first}Field("${namedField.name}", ${helper.getDataReaderCall(typedField.type)}<#if peekField.offsetExpression.present>, ${helper.toParseExpression(peekField, helper.boolTypeReference, peekField.offsetExpression.get(), parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}) + ${namedField.name}: ${helper.getLanguageTypeNameForField(field)} = read_buffer.${helper.getDataReaderCall(peekField.type)}(logical_name="${namedField.name}"<#if peekField.offsetExpression.present>, ${helper.toParseExpression(peekField, helper.boolTypeReference, peekField.offsetExpression.get(), parserArguments)}${helper.getFieldOptions(typedField, parserArguments)}<#if hasParserArguments>, ${parsedList}) <#break> @@ -772,12 +770,6 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty <#list type.propertyFields as field> ${helper.camelCaseToSnakeCase(field.name)}<#sep>, - <#if filteredParserArguments?has_content> - <#if type.propertyFields?has_content>, - <#list filteredParserArguments as arg>${helper.camelCaseToSnakeCase(arg.name)}<#sep>, - - - <#if (type.propertyFields?has_content || filteredParentParserArguments?has_content) && reservedFields?has_content>, <#list reservedFields as reservedField> reserved_field_${reservedField?index}<#sep>, @@ -839,25 +831,28 @@ class ${type.name}<#if type.isDiscriminatedParentTypeDefinition()>(<#if ty def hash_code(self) -> int: return hash(self) + <@emitImport import="from plc4py.api.exceptions.exceptions import SerializationException" /> + <@emitImport import="from plc4py.api.exceptions.exceptions import PlcRuntimeException" /> def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + #write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + #try: + # write_buffer_box_based.writeSerializable(self) + #except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + #return "\n" + str(write_buffer_box_based.get_box()) + "\n" <#if type.isDiscriminatedParentTypeDefinition()> class ${type.name}Builder: <@compress single_line=true>def build(self, <#list type.propertyFields as field> - ${field.name}: ${helper.getLanguageTypeNameForField(field)}<#sep>, + ${helper.camelCaseToSnakeCase(field.name)}: ${helper.getLanguageTypeNameForField(field)}<#sep>, <#if filteredParserArguments?has_content> <#if type.propertyFields?has_content>, <#list filteredParserArguments as arg> - ${arg.name}: ${helper.getLanguageTypeNameForTypeReference(arg.type)}<#sep>, + ${helper.camelCaseToSnakeCase(arg.name)}: ${helper.getLanguageTypeNameForTypeReference(arg.type)}<#sep>, ) -> ${type.name}: @@ -871,42 +866,42 @@ class ${type.name}Builder: class ${type.name}Builder(${type.parentType.orElseThrow().name}Builder): <#if type.propertyFields?has_content> <#list type.propertyFields as field> - ${field.name}: ${helper.getLanguageTypeNameForField(field)} - - -<#if filteredParserArguments?has_content> - <#list filteredParserArguments as arg> - ${arg.name}: ${helper.getLanguageTypeNameForTypeReference(arg.type)} + ${helper.camelCaseToSnakeCase(field.name)}: ${helper.getLanguageTypeNameForField(field)} <#list reservedFields as reservedField> reservedField${reservedField?index}: ${helper.getLanguageTypeNameForTypeReference(reservedField.type, false)} - def __post_init__(self): - pass - def build(self,<@compress single_line=true> + <#if filteredParserArguments?has_content> + <#list filteredParserArguments as arg> + ${helper.camelCaseToSnakeCase(arg.name)}: ${helper.getLanguageTypeNameForTypeReference(arg.type)} + + , + <#list type.parentType.orElseThrow().asComplexTypeDefinition().orElseThrow().propertyFields as field> - ${field.name}: ${helper.getLanguageTypeNameForField(field)}<#sep>, + ${helper.camelCaseToSnakeCase(field.name)}: ${helper.getLanguageTypeNameForField(field)}<#sep>, <#if filteredParentParserArguments?has_content> <#if type.parentType.orElseThrow().asComplexTypeDefinition().orElseThrow().propertyFields?has_content>, <#list filteredParentParserArguments as arg> - ${arg.name}: ${helper.getLanguageTypeNameForTypeReference(arg.type)}<#sep>, + ${helper.camelCaseToSnakeCase(arg.name)}: ${helper.getLanguageTypeNameForTypeReference(arg.type)}<#sep>, ) -> ${type.name}: ${helper.camelCaseToSnakeCase(type.name)}: ${type.name} = ${type.name}(<@compress single_line=true> - <#list type.allPropertyFields as field> - self.${helper.camelCaseToSnakeCase(field.name)}<#sep>, - <#if filteredParserArguments?has_content> - <#if type.allPropertyFields?has_content>, <#list filteredParserArguments as arg> ${arg.name}<#sep>, - ) + + <#if filteredParserArguments?has_content>, + <#list type.allPropertyFields as field> + + self.${helper.camelCaseToSnakeCase(field.name)}<#sep>, + + ) <#list reservedFields as reservedField> ${helper.camelCaseToSnakeCase(type.name)}.reservedField${reservedField?index} = reservedField${reservedField?index} diff --git a/code-generation/language-python/src/main/resources/templates/python/data-io-template.python.ftlh b/code-generation/language-python/src/main/resources/templates/python/data-io-template.python.ftlh index cbd9274e49e..2f4b2dacf14 100644 --- a/code-generation/language-python/src/main/resources/templates/python/data-io-template.python.ftlh +++ b/code-generation/language-python/src/main/resources/templates/python/data-io-template.python.ftlh @@ -61,9 +61,7 @@ ${import} <#-- TODO: the code below implies that parserArguments will be null if not present... not pretty --> <#if type.parserArguments.isPresent()><#assign parserArguments=type.parserArguments.orElseThrow()> class ${type.name}: - <@emitImport import="from loguru import logging as log" /> - - <@emitImport import="from abc import staticmethod" /> + <@emitImport import="from plc4py.spi.generation.ReadBuffer import ReadBuffer" /> @staticmethod def static_parse(read_buffer: ReadBuffer<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, ): <#assign defaultCaseOutput=false> @@ -74,14 +72,12 @@ class ${type.name}: <#list case.discriminatorValueTerms as discriminatorValueTerm> <#assign discriminatorExpression=dataIoTypeDefinition.switchField.orElseThrow().discriminatorExpressions[discriminatorValueTerm?index].asLiteral().orElseThrow().asVariableLiteral().orElseThrow()> <#assign discriminatorType=helper.getDiscriminatorTypes()[discriminatorExpression.name]> - EvaluationHelper.equals( - ${helper.camelCaseToSnakeCase(helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorExpression, parserArguments))}, + ${helper.camelCaseToSnakeCase(helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorExpression, parserArguments))} == <#if discriminatorType.isEnumTypeReference()> ${helper.getLanguageTypeNameForTypeReference(discriminatorType)}.${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorValueTerm, parserArguments)} <#else> ${helper.camelCaseToSnakeCase(helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorValueTerm, parserArguments))} - ) <#sep> and : # ${case.name} @@ -102,10 +98,9 @@ class ${type.name}: <#-- If this is a count array, we can directly initialize an array with the given size --> <#if field.isCountArrayField()> # Count array - if ${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression,parserArguments)} > Integer.MAX_VALUE: - raise ParseException("Array count of " + (${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression,parserArguments)}) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - item_count: int = int(${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression,parserArguments)}) + <@emitImport import="from typing import List" /> + <@emitImport import="from plc4py.api.value.PlcValue import PlcValue" /> ${helper.camelCaseToSnakeCase(arrayField.name)}: List[PlcValue] = [] for cur_item in range(item_count): ${helper.camelCaseToSnakeCase(arrayField.name)}.append(${helper.getPlcValueTypeForTypeReference(elementTypeReference)}(${helper.getLanguageTypeNameForTypeReference(elementTypeReference, false)}(<#if elementTypeReference.isSimpleTypeReference()>${helper.getReadBufferReadMethodCall(elementTypeReference.asSimpleTypeReference().orElseThrow(), "", arrayField)})<#else>${elementTypeReference.asComplexTypeReference().orElseThrow().name}IO.static_parse(read_buffer<#if elementTypeReference.params.isPresent()>, <#list elementTypeReference.params.orElseThrow() as parserArgument>(${helper.getLanguageTypeNameForTypeReference(helper.getArgumentType(elementTypeReference, parserArgument?index), true)}) (${helper.toParseExpression(arrayField, elementTypeReference, parserArgument,parserArguments)})<#sep>, ))) @@ -117,6 +112,8 @@ class ${type.name}: # Length array _${helper.camelCaseToSnakeCase(arrayField.name)}_length: long = ${helper.toParseExpression(arrayField, helper.intTypeReference, arrayField.loopExpression,parserArguments)} ${helper.camelCaseToSnakeCase(arrayField.name)}_end_pos: long = read_buffer.get_pos() + _${helper.camelCaseToSnakeCase(arrayField.name)}_length + <@emitImport import="from typing import List" /> + <@emitImport import="from plc4py.api.value.PlcValue import PlcValue" /> value: List[PlcValue]= [] while read_buffer.get_pos() < ${helper.camelCaseToSnakeCase(arrayField.name)}_end_pos): value.append(<@compress single_line=true> @@ -158,6 +155,7 @@ class ${type.name}: # Const Field (${helper.camelCaseToSnakeCase(constField.name)}) ${helper.camelCaseToSnakeCase(constField.name)}: ${helper.getNonPrimitiveLanguageTypeNameForField(constField)} = ${helper.getReadBufferReadMethodCall(constField.type.asSimpleTypeReference().orElseThrow(), "", constField)} if ${helper.camelCaseToSnakeCase(constField.name)} != ${dataIoTypeDefinition.name}.${constField.name?upper_case}): + <@emitImport import="from plc4py.api.exceptions.exceptions import ParseException" /> raise ParseException("Expected constant value " + ${dataIoTypeDefinition.name}.${constField.name?upper_case} + " but got " + ${helper.camelCaseToSnakeCase(constField.name)}) <#if constField.name == "value"> @@ -188,7 +186,8 @@ class ${type.name}: # Reserved Field (Compartmentalized so the "reserved" variable can't leak) reserved: ${helper.getLanguageTypeNameForField(field)} = ${helper.getReadBufferReadMethodCall(reservedField.type.asSimpleTypeReference().orElseThrow(), "", reservedField)} if reserved != ${helper.getReservedValue(reservedField)}: - log.info("Expected constant value " + str(${reservedField.referenceValue}) + " but got " + reserved + " for reserved field.") + <@emitImport import="import logging" /> + logging.warning("Expected constant value " + str(${reservedField.referenceValue}) + " but got " + str(reserved) + " for reserved field.") <#break> <#case "simple"> <#assign simpleField=field.asSimpleField().orElseThrow()> @@ -214,51 +213,66 @@ class ${type.name}: <#if case.name == "Struct"> <#-- In this case we need to wrap each field in a PlcValue that matches it's natural type --> + <@emitImport import="from plc4py.api.value.PlcValue import PlcValue" /> _map: Dict[str, PlcValue] = {} <#list case.fields as field> <#if field.isArrayField()> <#assign field=field.asArrayField().orElseThrow()> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcList" /> _map["${field.name}"] = PlcList(${field.name}) <#elseif field.isPropertyField()> <#assign field=field.asPropertyField().orElseThrow()> <#switch helper.getLanguageTypeNameForTypeReference(field.type)> <#case "Boolean"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcBOOL" /> _map["${field.name}"] = PlcBOOL(${field.name}) <#break> <#case "Byte"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcSINT" /> _map["${field.name}"] = PlcSINT(${field.name}) <#break> <#case "Short"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcINT" /> _map["${field.name}"] = PlcINT(${field.name}) <#break> <#case "Integer"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcDINT" /> _map["${field.name}"] = PlcDINT(${field.name}) <#break> <#case "Long"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcLINT" /> _map["${field.name}"] = PlcLINT(${field.name}) <#break> <#case "BigInteger"> - _map["${field.name}"] = PlcBigInteger(${field.name}) + <@emitImport import="from plc4py.spi.values.PlcValues import PlcLINT" /> + _map["${field.name}"] = PlcLINT(${field.name}) <#break> <#case "Float"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcREAL" /> _map["${field.name}"] = PlcREAL(${field.name}) <#break> <#case "Double"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcLREAL" /> _map["${field.name}"] = PlcLREAL(${field.name}) <#break> <#case "BigDecimal"> - _map["${field.name}"] = PlcBigDecimal(${field.name}) + <@emitImport import="from plc4py.spi.values.PlcValues import PlcLREAL" /> + _map["${field.name}"] = PlcLREAL(${field.name}) <#break> <#case "String"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcSTRING" /> _map["${field.name}"] = PlcSTRING(${field.name}) <#break> <#case "LocalTime"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcTIME_OF_DAY" /> _map["${field.name}"] = PlcTIME_OF_DAY(${field.name}) <#break> <#case "LocalDate"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcDATE" /> _map["${field.name}"] = PlcDATE(${field.name}) <#break> <#case "LocalDateTime"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcDATE_AND_TIME" /> _map["${field.name}"] = PlcDATE_AND_TIME(${field.name}) <#break> @@ -270,12 +284,14 @@ class ${type.name}: <#if valueDefined> <#switch case.name> <#case "TIME"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcTIME" /> return PlcTIME(value) <#break> <#case "DATE"> <#if helper.hasFieldsWithNames(case.fields, "year", "month", "day")> value: LocalDate = LocalDate(int(year), (month == 0) ? 1 : int(month), (day == 0) ? 1 : int(day)) + <@emitImport import="from plc4py.spi.values.PlcValues import PlcDATE" /> return PlcDATE(value) <#break> <#case "TIME_OF_DAY"> @@ -284,6 +300,7 @@ class ${type.name}: <#elseif helper.hasFieldsWithNames(case.fields, "hour", "minutes", "seconds")> value: LocalTime = LocalTime(int(hour), int(minutes), int(seconds)) + <@emitImport import="from plc4py.spi.values.PlcValues import PlcTIME_OF_DAY" /> return PlcTIME_OF_DAY(value) <#break> <#case "DATE_AND_TIME"> @@ -294,15 +311,19 @@ class ${type.name}: <#elseif helper.hasFieldsWithNames(case.fields, "secondsSinceEpoch")> value: LocalDateTime = LocalDateTime.ofEpochSecond(secondsSinceEpoch, 0, ZoneOffset.UTC) + <@emitImport import="from plc4py.spi.values.PlcValues import PlcDATE_AND_TIME" /> return PlcDATE_AND_TIME(value) <#break> <#case "Struct"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcStruct" /> return PlcStruct(_map) <#break> <#case "List"> + <@emitImport import="from plc4py.spi.values.PlcValues import PlcList" /> return PlcList(value) <#break> <#default> + <@emitImport import="from plc4py.spi.values.PlcValues import Plc" + case.name /> return Plc${case.name}(value) @@ -312,14 +333,11 @@ class ${type.name}: <#if outputFlavor != "passive"> - <@emitImport import="from abc import staticmethod" /> + <@emitImport import="from plc4py.spi.generation.WriteBuffer import WriteBuffer" /> + <@emitImport import="from plc4py.api.value.PlcValue import PlcValue" /> + <@emitImport import="from plc4py.utils.GenericTypes import ByteOrder" /> @staticmethod - def static_serialize(writeBuffer: WriteBuffer, _value: PlcValue<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${parserArgument.name}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, ) -> None: - static_serialize(writeBuffer, _value<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${parserArgument.name}<#sep>, , ByteOrder.BIG_ENDIAN) - - <@emitImport import="from abc import staticmethod" /> - @staticmethod - def static_serialize(writeBuffer: WriteBuffer, _value: PlcValue<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${parserArgument.name}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, , byteOrder: ByteOrder) -> None: + def static_serialize(write_buffer: WriteBuffer, _value: PlcValue<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, , byte_order: ByteOrder) -> None: <#assign defaultCaseOutput=false> <#assign dataIoTypeDefinition=type.asDataIoTypeDefinition().orElseThrow()> <#list dataIoTypeDefinition.switchField.orElseThrow().cases as case> @@ -328,13 +346,12 @@ class ${type.name}: <#list case.discriminatorValueTerms as discriminatorValueTerm> <#assign discriminatorExpression=dataIoTypeDefinition.switchField.orElseThrow().discriminatorExpressions[discriminatorValueTerm?index].asLiteral().orElseThrow().asVariableLiteral().orElseThrow()> <#assign discriminatorType=helper.getDiscriminatorTypes()[discriminatorExpression.name]> - EvaluationHelper.equals( - ${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorExpression, parserArguments)}, + ${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorExpression, parserArguments)} == <#if discriminatorType.isEnumTypeReference()> ${helper.getLanguageTypeNameForTypeReference(discriminatorType)}.${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorValueTerm, parserArguments)} <#else> ${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorValueTerm, parserArguments)} - ) + <#sep> and : # ${case.name} @@ -350,28 +367,29 @@ class ${type.name}: values: PlcList = _value <#if case.name == "Struct"> - for val in values.getStruct().get("${arrayField.name}").getList(): + for val in values.getStruct().get("${arrayField.name}").get_list(): <#if elementTypeReference.isByteBased()> - value: ${helper.getLanguageTypeNameForField(arrayField)} = val.getRaw() - writeBuffer.writeByteArray("", value) + value: ${helper.getLanguageTypeNameForField(arrayField)} = val.get_raw() + write_buffer.write_byte_array("", value) <#else> - value: ${helper.getLanguageTypeNameForField(arrayField)} = val.get${helper.getLanguageTypeNameForField(arrayField)?cap_first}() + value: ${helper.getLanguageTypeNameForField(arrayField)} = val.get_${helper.camelCaseToSnakeCase(helper.getLanguageTypeNameForField(arrayField)?cap_first)}() ${helper.getWriteBufferWriteMethodCall(elementTypeReference.asSimpleTypeReference().orElseThrow(), "value", arrayField)} <#else> - for val in values.getList(): + for val in values.get_list(): <#if elementTypeReference.isByteBased()> - value: list[byte] = val.getRaw() - writeBuffer.writeByteArray("", value) + <@emitImport import="from typing import List" /> + value: list[byte] = val.get_raw() + write_buffer.write_byte_array("", value) <#else> - value: ${helper.getLanguageTypeNameForTypeReference(elementTypeReference)} = val.get${helper.getLanguageTypeNameForTypeReference(elementTypeReference)?cap_first}() + value: ${helper.getLanguageTypeNameForTypeReference(elementTypeReference)} = val.get_${helper.camelCaseToSnakeCase(helper.getLanguageTypeNameForTypeReference(elementTypeReference)?cap_first)}() ${helper.getWriteBufferWriteMethodCall(elementTypeReference.asSimpleTypeReference().orElseThrow(), "(" + arrayField.name + ")", arrayField)} <#if case.name == "BOOL"> - while writeBuffer.getPos() < len(writeBuffer.getData()): - writeBuffer.writeBit(false) + while write_buffer.getPos() < len(write_buffer.get_data()): + write_buffer.write_bit(false) <#break> <#case "const"> @@ -382,8 +400,8 @@ class ${type.name}: <#case "enum"> <#assign enumField=field.asEnumField().orElseThrow()> # Enum field (${enumField.name}) - ${enumField.name}: ${helper.getLanguageTypeNameForField(field)} = _value.get${enumField.name?cap_first}() - ${helper.getWriteBufferWriteMethodCall(helper.getEnumBaseTypeReference(field.asTypedField().orElseThrow().type), "(" + enumField.name + ".getValue())", enumField)} + ${enumField.name}: ${helper.getLanguageTypeNameForField(field)} = _value.get_${helper.camelCaseToSnakeCase(enumField.name?cap_first)}() + ${helper.getWriteBufferWriteMethodCall(helper.getEnumBaseTypeReference(field.asTypedField().orElseThrow().type), "(" + enumField.name + ".value)", enumField)} <#break> <#case "manual"> <#assign manualField=field.asManualField().orElseThrow()> @@ -399,12 +417,12 @@ class ${type.name}: <#assign simpleField=field.asSimpleField().orElseThrow()> # Simple Field (${simpleField.name}) <#if case.name == "Struct"> - ${simpleField.name}: ${helper.getLanguageTypeNameForField(simpleField)} = _value.getStruct().get("${simpleField.name}").get${helper.getLanguageTypeNameForField(simpleField)?cap_first}() + ${simpleField.name}: ${helper.getLanguageTypeNameForField(simpleField)} = _value.get_struct().get("${simpleField.name}").get${helper.getLanguageTypeNameForField(simpleField)?cap_first}() <#else> <#if simpleField.name == "value"> - ${simpleField.name}: ${helper.getLanguageTypeNameForField(simpleField)} = _value.get${helper.getLanguageTypeNameForField(simpleField)?cap_first}() + ${simpleField.name}: ${helper.getLanguageTypeNameForField(simpleField)} = _value.get_${helper.camelCaseToSnakeCase(helper.getLanguageTypeNameForField(simpleField)?cap_first)}() <#elseif simpleField.name == "secondsSinceEpoch"> - ${simpleField.name}: ${helper.getLanguageTypeNameForField(simpleField)} = _value.get${helper.getLanguageTypeNameForField(simpleField)?cap_first}() + ${simpleField.name}: ${helper.getLanguageTypeNameForField(simpleField)} = _value.get_${helper.camelCaseToSnakeCase(helper.getLanguageTypeNameForField(simpleField)?cap_first)}() <#else> <#-- Just for now --> ${simpleField.name}: ${helper.getLanguageTypeNameForField(simpleField)} = ${helper.getNullValueForTypeReference(simpleField.type)} @@ -413,7 +431,7 @@ class ${type.name}: <#if simpleField.type.isSimpleTypeReference()> ${helper.getWriteBufferWriteMethodCall(simpleField.type.asSimpleTypeReference().orElseThrow(), "(" + simpleField.name + ")", simpleField)} <#else> - ${simpleField.type.asComplexTypeReference().orElseThrow().name}IO.staticSerialize(writeBuffer, ${simpleField.name}) + ${simpleField.type.asComplexTypeReference().orElseThrow().name}IO.static_serialize(write_buffer, ${helper.camelCaseToSnakeCase(simpleField.name)}) <#break> @@ -421,17 +439,17 @@ class ${type.name}: <#sep> - <@emitImport import="from abc import staticmethod" /> <@emitImport import="import math" /> + <@emitImport import="from plc4py.api.value.PlcValue import PlcValue" /> @staticmethod - def get_length_in_bytes(_value: PlcValue<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${parserArgument.name}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, ) -> int: - return int(math.ceil(float(getLengthInBits(_value<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${parserArgument.name}<#sep>, )) / 8.0)) + def get_length_in_bytes(_value: PlcValue<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, ) -> int: + return int(math.ceil(float(${type.name}.get_length_in_bits(_value<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}<#sep>, )) / 8.0)) - <@emitImport import="from abc import staticmethod" /> + <@emitImport import="from plc4py.api.value.PlcValue import PlcValue" /> @staticmethod - def get_length_in_bits(_value: PlcValue<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${parserArgument.name}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, ) -> int: - sizeInBits: int = 0 + def get_length_in_bits(_value: PlcValue<#if type.parserArguments.isPresent()>, <#list type.parserArguments.orElseThrow() as parserArgument>${helper.camelCaseToSnakeCase(parserArgument.name)}: ${helper.getLanguageTypeNameForTypeReference(parserArgument.type, false)}<#sep>, ) -> int: + size_in_bits: int = 0 <#assign defaultCaseOutput=false> <#assign dataIoTypeDefinition=type.asDataIoTypeDefinition().orElseThrow()> <#list dataIoTypeDefinition.switchField.orElseThrow().cases as case> @@ -440,14 +458,12 @@ class ${type.name}: <#list case.discriminatorValueTerms as discriminatorValueTerm> <#assign discriminatorExpression=dataIoTypeDefinition.switchField.orElseThrow().discriminatorExpressions[discriminatorValueTerm?index].asLiteral().orElseThrow().asVariableLiteral().orElseThrow()> <#assign discriminatorType=helper.getDiscriminatorTypes()[discriminatorExpression.name]> - EvaluationHelper.equals( - ${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorExpression, parserArguments)}, + ${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorExpression, parserArguments)} == <#if discriminatorType.isEnumTypeReference()> ${helper.getLanguageTypeNameForTypeReference(discriminatorType)}.${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorValueTerm, parserArguments)} <#else> ${helper.toParseExpression(dataIoTypeDefinition.switchField.orElseThrow(), discriminatorType, discriminatorValueTerm, parserArguments)} - ) <#sep> and : # ${case.name} @@ -465,39 +481,39 @@ class ${type.name}: <#elseif elementTypeReference.isComplexTypeReference()> # TODO: Finish this! <#else> - sizeInBits += values.getList().size() * ${elementTypeReference.asSimpleTypeReference().orElseThrow().sizeInBits} + size_in_bits += len(values.get_list()) * ${elementTypeReference.asSimpleTypeReference().orElseThrow().sizeInBits} <#break> <#case "const"> <#assign constField=field.asConstField().orElseThrow()> # Const Field (${constField.name}) <#-- const fields are only simple type --> - sizeInBits += ${constField.type.asSimpleTypeReference().orElseThrow().sizeInBits} + size_in_bits += ${constField.type.asSimpleTypeReference().orElseThrow().sizeInBits} <#break> <#case "enum"> <#assign enumField=field.asEnumField().orElseThrow()> # Enum field (${enumField.name}) - sizeInBits += ${helper.getEnumFieldSimpleTypeReference(enumField.type, enumField.fieldName).sizeInBits} + size_in_bits += ${helper.getEnumFieldSimpleTypeReference(enumField.type, enumField.fieldName).sizeInBits} <#break> <#case "manual"> <#assign manualField=field.asManualField().orElseThrow()> # Manual Field (${manualField.name}) - sizeInBits += ${helper.toSerializationExpression(manualField, helper.intTypeReference, manualField.lengthExpression, type.parserArguments.orElse(null))} + size_in_bits += ${helper.toSerializationExpression(manualField, helper.intTypeReference, manualField.lengthExpression, type.parserArguments.orElse(null))} <#break> <#case "reserved"> <#assign reservedField=field.asReservedField().orElseThrow()> # Reserved Field - sizeInBits += ${reservedField.type.asSimpleTypeReference().orElseThrow().sizeInBits} + size_in_bits += ${reservedField.type.asSimpleTypeReference().orElseThrow().sizeInBits} <#break> <#case "simple"> <#assign simpleField=field.asSimpleField().orElseThrow()> # Simple Field (${simpleField.name}) - sizeInBits += ${simpleField.type.asSimpleTypeReference().orElseThrow().sizeInBits} + size_in_bits += ${simpleField.type.asSimpleTypeReference().orElseThrow().sizeInBits} <#break> <#sep> - return sizeInBits + return size_in_bits diff --git a/code-generation/language-python/src/main/resources/templates/python/enum-template.python.ftlh b/code-generation/language-python/src/main/resources/templates/python/enum-template.python.ftlh index e14eb49d4ae..a82bf2438af 100644 --- a/code-generation/language-python/src/main/resources/templates/python/enum-template.python.ftlh +++ b/code-generation/language-python/src/main/resources/templates/python/enum-template.python.ftlh @@ -58,13 +58,14 @@ ${import} <#macro emitImport import>${helper.emitRequiredImport(import)} <@importSectionWithContentBelow> -<@emitImport import="from enum import IntEnum" /> +<@emitImport import="from aenum import AutoNumberEnum" /> -class ${type.name}(IntEnum): +class ${type.name}(AutoNumberEnum): + <#if type.constantNames?has_content>_init_ = "value, <#list type.constantNames as constantName>${helper.camelCaseToSnakeCase(constantName)}<#sep>, " <#list type.enumValues as enumValue> - ${enumValue.name}: <@compress single_line=true> + ${enumValue.name}<#if !type.constantNames?has_content>: <@compress single_line=true> <#if type.type.isPresent()> - ${helper.getLanguageTypeNameForTypeReference(type.type.orElseThrow(), true)} + <#if !type.constantNames?has_content>${helper.getLanguageTypeNameForTypeReference(type.type.orElseThrow(), true)} <#if type.type.orElseThrow().isNonSimpleTypeReference()> <#if type.type.orElseThrow().isEnumTypeReference()> = <#if type.constantNames?has_content>(${helper.getLanguageTypeNameForTypeReference(type.type.orElseThrow(), true)}.${enumValue.value} @@ -92,20 +93,6 @@ class ${type.name}(IntEnum): - <#if type.constantNames?has_content> - def __new__(cls, value, <@compress single_line=true> - <#list type.constantNames as constantName> - ${helper.camelCaseToSnakeCase(constantName)} - <#sep>, - ): - - - obj = object.__new__(cls) - obj._value_ = value - <#list type.constantNames as constantName>obj.${constantName} = ${constantName} - return obj - - diff --git a/sandbox/plc4py/plc4py/api/exceptions/exceptions.py b/sandbox/plc4py/plc4py/api/exceptions/exceptions.py index 6fa82ded1b9..8029653a035 100644 --- a/sandbox/plc4py/plc4py/api/exceptions/exceptions.py +++ b/sandbox/plc4py/plc4py/api/exceptions/exceptions.py @@ -41,3 +41,7 @@ class PlcNotImplementedException(Exception): class SerializationException(Exception): pass + + +class ParseException(Exception): + pass diff --git a/sandbox/plc4py/plc4py/api/messages/PlcField.py b/sandbox/plc4py/plc4py/api/messages/PlcField.py index 13db3779801..9a458e43896 100644 --- a/sandbox/plc4py/plc4py/api/messages/PlcField.py +++ b/sandbox/plc4py/plc4py/api/messages/PlcField.py @@ -20,7 +20,7 @@ @dataclass -class PlcField: +class PlcTag: """ Base type for all field types. Typically every driver provides an implementation of this interface in order @@ -31,7 +31,7 @@ class PlcField: In order to stay platform and protocol independent every driver connection implementation provides a prepareField(String) method that is able to parse a string representation of a resource into it's individual field type. Manually constructing PlcField objects - manually makes the solution less independent from the protocol, but might be faster. + manually makes the solution less independent of the protocol, but might be faster. """ - name: str + address: str diff --git a/sandbox/plc4py/plc4py/api/messages/PlcRequest.py b/sandbox/plc4py/plc4py/api/messages/PlcRequest.py index 6bca13c14f1..89fce22b772 100644 --- a/sandbox/plc4py/plc4py/api/messages/PlcRequest.py +++ b/sandbox/plc4py/plc4py/api/messages/PlcRequest.py @@ -18,9 +18,9 @@ # from abc import abstractmethod from dataclasses import dataclass, field -from typing import Union, List +from typing import Union, List, Dict -from plc4py.api.messages.PlcField import PlcField +from plc4py.api.messages.PlcField import PlcTag from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.utils.GenericTypes import GenericGenerator @@ -32,16 +32,16 @@ class PlcRequest(PlcMessage): @dataclass -class PlcFieldRequest(PlcRequest): - fields: List[PlcField] = field(default_factory=lambda: []) +class PlcTagRequest(PlcRequest): + tags: Dict[str, PlcTag] = field(default_factory=lambda: {}) @property - def field_names(self): - return [field.name for field in self.fields] + def tag_names(self): + return [tag_name for tag_name in self.tags.keys()] @dataclass -class PlcReadRequest(PlcFieldRequest): +class PlcReadRequest(PlcTagRequest): """ Base type for all messages sent from the plc4x system to a connected plc. """ @@ -53,5 +53,5 @@ def build(self) -> PlcReadRequest: pass @abstractmethod - def add_item(self, field_query: Union[str, PlcField]) -> None: + def add_item(self, tag_name: str, address_string: str) -> None: pass diff --git a/sandbox/plc4py/plc4py/api/messages/PlcResponse.py b/sandbox/plc4py/plc4py/api/messages/PlcResponse.py index 79eef53f82e..f7d899faae8 100644 --- a/sandbox/plc4py/plc4py/api/messages/PlcResponse.py +++ b/sandbox/plc4py/plc4py/api/messages/PlcResponse.py @@ -19,7 +19,7 @@ from dataclasses import dataclass from typing import cast, List, Dict -from plc4py.api.messages.PlcField import PlcField +from plc4py.api.messages.PlcField import PlcTag from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.api.value.PlcValue import PlcValue, PlcResponseCode from plc4py.spi.messages.utils.ResponseItem import ResponseItem @@ -36,25 +36,23 @@ class PlcResponse(PlcMessage): @dataclass -class PlcFieldResponse(PlcResponse): - fields: List[PlcField] +class PlcTagResponse(PlcResponse): + values: Dict[str, List[ResponseItem[PlcValue]]] @property - def field_names(self): - return [fld.name for fld in self.fields] + def tag_names(self): + return [tag_name for tag_name in self.values.keys()] def response_code(self, name: str) -> PlcResponseCode: pass @dataclass -class PlcReadResponse(PlcFieldResponse): +class PlcReadResponse(PlcTagResponse): """ Response to a {@link PlcReadRequest}. """ - values: Dict[str, List[ResponseItem[PlcValue]]] - def get_plc_value(self, name: str, index: int = 0) -> PlcValue: return self.values[name][index].value diff --git a/sandbox/plc4py/plc4py/api/value/PlcValue.py b/sandbox/plc4py/plc4py/api/value/PlcValue.py index 189ceb0b46e..b154a48ffd8 100644 --- a/sandbox/plc4py/plc4py/api/value/PlcValue.py +++ b/sandbox/plc4py/plc4py/api/value/PlcValue.py @@ -19,7 +19,7 @@ from abc import ABC from dataclasses import dataclass from enum import auto, Enum -from typing import TypeVar, Generic +from typing import TypeVar, Generic, List T = TypeVar("T") @@ -28,10 +28,22 @@ class PlcValue(Generic[T], ABC): value: T - def get_bool(self): + def get_bool(self) -> bool: + return bool(self.value) + + def get_float(self) -> float: + return float(self.value) + + def get_str(self) -> str: + return str(self.value) + + def get_int(self) -> int: + return int(self.value) + + def get_list(self) -> List["PlcValue"]: return self.value - def get_int(self): + def get_raw(self): return self.value diff --git a/sandbox/plc4py/plc4py/drivers/mock/MockConnection.py b/sandbox/plc4py/plc4py/drivers/mock/MockConnection.py index 0e5e6f18820..9b6b1644c08 100644 --- a/sandbox/plc4py/plc4py/drivers/mock/MockConnection.py +++ b/sandbox/plc4py/plc4py/drivers/mock/MockConnection.py @@ -22,13 +22,17 @@ from dataclasses import dataclass, field from typing import Awaitable, Type, List, Dict +from plc4py.drivers.mock import MockTag +from plc4py.drivers.mock.MockTag import MockTagBuilder +from plc4py.spi.messages.PlcRequest import DefaultReadRequestBuilder + import plc4py from plc4py.api.PlcConnection import PlcConnection from plc4py.api.PlcDriver import PlcDriver from plc4py.api.authentication.PlcAuthentication import PlcAuthentication from plc4py.api.exceptions.exceptions import PlcFieldParseException -from plc4py.api.messages.PlcField import PlcField +from plc4py.api.messages.PlcField import PlcTag from plc4py.api.messages.PlcRequest import ( ReadRequestBuilder, PlcReadRequest, @@ -39,54 +43,22 @@ from plc4py.drivers.PlcDriverLoader import PlcDriverLoader from plc4py.spi.messages.PlcReader import PlcReader from plc4py.spi.messages.utils.ResponseItem import ResponseItem -from plc4py.spi.values.PlcBOOL import PlcBOOL -from plc4py.spi.values.PlcINT import PlcINT -from plc4py.drivers.mock.MockReadRequestBuilder import MockReadRequestBuilder - - -@dataclass -class MockPlcField(PlcField): - """ - Mock PLC Field type - """ - - datatype: str = "INT" - - -class MockPlcFieldHandler: - """ - Helper class to generate MockPlcField based on a fieldquery - """ - - @staticmethod - def of(fieldquery: str) -> MockPlcField: - """ - :param fieldquery: Field identifier string e.g. '1:BOOL' - :return: A MockPlcField with the datatype populated - """ - try: - datatype = fieldquery.split(":")[1] - return MockPlcField(fieldquery, datatype) - except IndexError: - raise PlcFieldParseException +from plc4py.spi.values.PlcValues import PlcBOOL +from plc4py.spi.values.PlcValues import PlcINT @dataclass class MockDevice: - fields: Dict[str, PlcValue] = field(default_factory=lambda: {}) - - def read(self, field: str) -> List[ResponseItem[PlcValue]]: + def read(self, tag: MockTag) -> List[ResponseItem[PlcValue]]: """ Reads one field from the Mock Device """ - logging.debug(f"Reading field {field} from Mock Device") - plc_field = MockPlcFieldHandler.of(field) - if plc_field.datatype == "BOOL": - self.fields[field] = PlcBOOL(False) - return [ResponseItem(PlcResponseCode.OK, self.fields[field])] - elif plc_field.datatype == "INT": - self.fields[field] = PlcINT(0) - return [ResponseItem(PlcResponseCode.OK, self.fields[field])] + logging.debug(f"Reading field {str(tag)} from Mock Device") + + if tag.data_type == "BOOL": + return [ResponseItem(PlcResponseCode.OK, PlcBOOL(False))] + elif tag.data_type == "INT": + return [ResponseItem(PlcResponseCode.OK, PlcINT(0))] else: raise PlcFieldParseException @@ -128,7 +100,7 @@ def read_request_builder(self) -> ReadRequestBuilder: """ :return: read request builder. """ - return MockReadRequestBuilder() + return DefaultReadRequestBuilder(MockTagBuilder) def execute(self, request: PlcRequest) -> Awaitable[PlcResponse]: """ @@ -156,13 +128,12 @@ async def _request(req, device) -> PlcReadResponse: try: response = PlcReadResponse( PlcResponseCode.OK, - req.fields, - {field: device.read(field) for field in req.field_names}, + {tag_name: device.read(tag) for tag_name, tag in req.tags.items()}, ) return response - except Exception: + except Exception as e: # TODO:- This exception is very general and probably should be replaced - return PlcReadResponse(PlcResponseCode.INTERNAL_ERROR, req.fields, {}) + return PlcReadResponse(PlcResponseCode.INTERNAL_ERROR, req.tags, {}) logging.debug("Sending read request to MockDevice") future = asyncio.ensure_future(_request(request, self.device)) diff --git a/sandbox/plc4py/plc4py/drivers/mock/MockReadRequestBuilder.py b/sandbox/plc4py/plc4py/drivers/mock/MockReadRequestBuilder.py index f4963981593..cb1cd089077 100644 --- a/sandbox/plc4py/plc4py/drivers/mock/MockReadRequestBuilder.py +++ b/sandbox/plc4py/plc4py/drivers/mock/MockReadRequestBuilder.py @@ -18,12 +18,12 @@ # from dataclasses import dataclass, field -from typing import Union, List +from typing import Union, List, Dict from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.api.messages.PlcRequest import ( ReadRequestBuilder, - PlcField, + PlcTag, PlcReadRequest, ) from plc4py.api.messages.PlcResponse import PlcReadResponse @@ -32,22 +32,3 @@ class MockPlcReadResponse(PlcReadResponse): def get_request(self) -> PlcMessage: return PlcMessage() - - -class MockPlcReadRequest(PlcReadRequest): - def __init__(self, fields: List[PlcField] = []): - super().__init__(fields) - - -@dataclass -class MockReadRequestBuilder(ReadRequestBuilder): - items: List[PlcField] = field(default_factory=lambda: []) - - def build(self) -> PlcReadRequest: - return MockPlcReadRequest(self.items) - - def add_item(self, field_query: Union[str, PlcField]) -> None: - field_temp: PlcField = ( - PlcField(field_query) if isinstance(field_query, str) else field_query - ) - self.items.append(field_temp) diff --git a/sandbox/plc4py/plc4py/spi/values/PlcBOOL.py b/sandbox/plc4py/plc4py/drivers/mock/MockTag.py similarity index 69% rename from sandbox/plc4py/plc4py/spi/values/PlcBOOL.py rename to sandbox/plc4py/plc4py/drivers/mock/MockTag.py index 3f4846162a0..73c8009bd01 100644 --- a/sandbox/plc4py/plc4py/spi/values/PlcBOOL.py +++ b/sandbox/plc4py/plc4py/drivers/mock/MockTag.py @@ -18,10 +18,18 @@ # from dataclasses import dataclass -from plc4py.api.value.PlcValue import PlcValue +from plc4py.api.messages.PlcField import PlcTag +from plc4py.spi.messages.PlcRequest import TagBuilder @dataclass -class PlcBOOL(PlcValue[bool]): - def get_bool(self): - return self.value +class MockTag(PlcTag): + address: str + data_type: str + + +class MockTagBuilder(TagBuilder): + @staticmethod + def create(address_string: str) -> MockTag: + address, data_type = address_string.split(":") + return MockTag(address, data_type) diff --git a/sandbox/plc4py/plc4py/drivers/modbus/ModbusConfiguration.py b/sandbox/plc4py/plc4py/drivers/modbus/ModbusConfiguration.py index 4b3c551a42d..25fc144cbee 100644 --- a/sandbox/plc4py/plc4py/drivers/modbus/ModbusConfiguration.py +++ b/sandbox/plc4py/plc4py/drivers/modbus/ModbusConfiguration.py @@ -28,3 +28,6 @@ def __init__(self, url): if self.port is None: self.port = 502 + + if "unit_identifier" not in self.parameters: + self.unit_identifier = 1 diff --git a/sandbox/plc4py/plc4py/drivers/modbus/ModbusConnection.py b/sandbox/plc4py/plc4py/drivers/modbus/ModbusConnection.py index 2eca71e3342..5330d95089f 100644 --- a/sandbox/plc4py/plc4py/drivers/modbus/ModbusConnection.py +++ b/sandbox/plc4py/plc4py/drivers/modbus/ModbusConnection.py @@ -17,17 +17,26 @@ # under the License. # import asyncio +import logging from typing import Type, Awaitable import plc4py from plc4py.api.PlcConnection import PlcConnection from plc4py.api.PlcDriver import PlcDriver from plc4py.api.authentication.PlcAuthentication import PlcAuthentication -from plc4py.api.messages.PlcResponse import PlcResponse -from plc4py.api.messages.PlcRequest import ReadRequestBuilder +from plc4py.api.messages.PlcResponse import PlcResponse, PlcReadResponse +from plc4py.api.messages.PlcRequest import ( + ReadRequestBuilder, + PlcRequest, + PlcReadRequest, +) +from plc4py.api.value.PlcValue import PlcResponseCode from plc4py.drivers.PlcDriverLoader import PlcDriverLoader from plc4py.drivers.modbus.ModbusConfiguration import ModbusConfiguration +from plc4py.drivers.modbus.ModbusDevice import ModbusDevice from plc4py.drivers.modbus.ModbusProtocol import ModbusProtocol +from plc4py.drivers.modbus.ModbusTag import ModbusTagBuilder +from plc4py.spi.messages.PlcRequest import DefaultReadRequestBuilder from plc4py.spi.transport.Plc4xBaseTransport import Plc4xBaseTransport from plc4py.spi.transport.TCPTransport import TCPTransport @@ -37,6 +46,7 @@ class ModbusConnection(PlcConnection): def __init__(self, config: ModbusConfiguration, transport: Plc4xBaseTransport): super().__init__(config) + self._device: ModbusDevice = ModbusDevice(self._configuration) self._transport: Plc4xBaseTransport = transport @staticmethod @@ -74,15 +84,41 @@ def read_request_builder(self) -> ReadRequestBuilder: """ :return: read request builder. """ - pass + return DefaultReadRequestBuilder(ModbusTagBuilder) - def execute(self, PlcRequest) -> Awaitable[PlcResponse]: + def execute(self, request: PlcRequest) -> Awaitable[PlcResponse]: """ Executes a PlcRequest as long as it's already connected - :param PlcRequest: Plc Request to execute + :param request: Plc Request to execute :return: The response from the Plc/Device """ - pass + if not self.is_connected(): + return self._default_failed_request(PlcResponseCode.NOT_CONNECTED) + + if isinstance(request, PlcReadRequest): + return self._read(request) + + return self._default_failed_request(PlcResponseCode.NOT_CONNECTED) + + def _read(self, request: PlcReadRequest) -> Awaitable[PlcReadResponse]: + """ + Executes a PlcReadRequest + """ + if self._device is None: + logging.error("No device is set in the modbus connection!") + return self._default_failed_request(PlcResponseCode.NOT_CONNECTED) + + async def _request(req, device) -> PlcReadResponse: + try: + response = await device.read(req, self._transport) + return response + except Exception as e: + # TODO:- This exception is very general and probably should be replaced + return PlcReadResponse(PlcResponseCode.INTERNAL_ERROR, {}) + + logging.debug("Sending read request to ModbusDevice") + future = asyncio.ensure_future(_request(request, self._device)) + return future class ModbusDriver(PlcDriver): diff --git a/sandbox/plc4py/plc4py/drivers/modbus/ModbusDevice.py b/sandbox/plc4py/plc4py/drivers/modbus/ModbusDevice.py new file mode 100644 index 00000000000..d1bba19b76b --- /dev/null +++ b/sandbox/plc4py/plc4py/drivers/modbus/ModbusDevice.py @@ -0,0 +1,152 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +import asyncio +import logging +from asyncio import Transport +from dataclasses import dataclass, field +from typing import Dict, List + +from bitarray import bitarray + +from plc4py.protocols.modbus.readwrite.DataItem import DataItem +from plc4py.protocols.modbus.readwrite.ModbusPDUError import ModbusPDUError +from plc4py.spi.generation.ReadBuffer import ReadBuffer, ReadBufferByteBased + +from plc4py.drivers.modbus.ModbusTag import ( + ModbusTagHoldingRegister, + ModbusTagCoil, + ModbusTagDiscreteInput, + ModbusTagInputRegister, +) + +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.drivers.modbus.ModbusConfiguration import ModbusConfiguration +from plc4py.protocols.modbus.readwrite.ModbusPDUReadCoilsRequest import ( + ModbusPDUReadCoilsRequest, +) +from plc4py.protocols.modbus.readwrite.ModbusPDUReadDiscreteInputsRequest import ( + ModbusPDUReadDiscreteInputsRequest, +) +from plc4py.protocols.modbus.readwrite.ModbusPDUReadInputRegistersRequest import ( + ModbusPDUReadInputRegistersRequest, +) +from plc4py.spi.generation.WriteBuffer import WriteBufferByteBased + +from plc4py.api.messages.PlcRequest import PlcReadRequest +from plc4py.api.messages.PlcResponse import PlcReadResponse +from plc4py.api.value.PlcValue import PlcValue, PlcResponseCode +from plc4py.protocols.modbus.readwrite.ModbusPDUReadHoldingRegistersRequest import ( + ModbusPDUReadHoldingRegistersRequest, +) +from plc4py.protocols.modbus.readwrite.ModbusTcpADU import ModbusTcpADU +from plc4py.spi.messages.utils.ResponseItem import ResponseItem +from plc4py.spi.values.PlcValues import PlcList, PlcNull +from plc4py.utils.GenericTypes import ByteOrder, AtomicInteger + + +@dataclass +class ModbusDevice: + _configuration: ModbusConfiguration + tags: Dict[str, PlcValue] = field(default_factory=lambda: {}) + + _transaction_generator: AtomicInteger = field( + default_factory=lambda: AtomicInteger() + ) + + async def read( + self, request: PlcReadRequest, transport: Transport + ) -> PlcReadResponse: + """ + Reads one field from the Mock Device + """ + if len(request.tags) > 1: + raise NotImplementedError( + "The Modbus driver only supports reading single tags at once" + ) + if len(request.tags) == 0: + raise PlcRuntimeException("No tags have been specified to read") + tag = request.tags[request.tag_names[0]] + logging.debug(f"Reading tag {str(tag)} from Modbus Device") + + # Create future to be returned when a value is returned + loop = asyncio.get_running_loop() + message_future = loop.create_future() + + if isinstance(tag, ModbusTagCoil): + pdu = ModbusPDUReadCoilsRequest(tag.address, tag.quantity) + elif isinstance(tag, ModbusTagDiscreteInput): + pdu = ModbusPDUReadDiscreteInputsRequest(tag.address, tag.quantity) + elif isinstance(tag, ModbusTagInputRegister): + pdu = ModbusPDUReadInputRegistersRequest(tag.address, tag.quantity) + elif isinstance(tag, ModbusTagHoldingRegister): + pdu = ModbusPDUReadHoldingRegistersRequest(tag.address, tag.quantity) + else: + raise NotImplementedError( + "Modbus tag type not implemented " + str(tag.__class__) + ) + + adu = ModbusTcpADU( + False, + self._transaction_generator.increment(), + self._configuration.unit_identifier, + pdu, + ) + write_buffer = WriteBufferByteBased(adu.length_in_bytes(), ByteOrder.BIG_ENDIAN) + adu.serialize(write_buffer) + + protocol = transport.protocol + protocol.write_wait_for_response( + write_buffer.get_bytes(), + transport, + adu.transaction_identifier, + message_future, + ) + + await message_future + result = message_future.result() + + if isinstance(result, ModbusPDUError): + response_items = [ResponseItem(PlcResponseCode.ACCESS_DENIED, PlcNull(result.exception_code))] + + response = PlcReadResponse( + PlcResponseCode.OK, {request.tag_names[0]: response_items} + ) + return response + + if isinstance(tag, ModbusTagCoil) or isinstance(tag, ModbusTagDiscreteInput): + a = bitarray() + a.frombytes(bytearray(result.value)) + a.bytereverse() + read_buffer = ReadBufferByteBased(bytearray(a), ByteOrder.BIG_ENDIAN) + else: + read_buffer = ReadBufferByteBased( + bytearray(result.value), ByteOrder.BIG_ENDIAN + ) + returned_value = DataItem.static_parse( + read_buffer, + request.tags[request.tag_names[0]].data_type, + request.tags[request.tag_names[0]].quantity, + ) + + response_items = [ResponseItem(PlcResponseCode.OK, returned_value)] + + response = PlcReadResponse( + PlcResponseCode.OK, {request.tag_names[0]: response_items} + ) + return response diff --git a/sandbox/plc4py/plc4py/drivers/modbus/ModbusProtocol.py b/sandbox/plc4py/plc4py/drivers/modbus/ModbusProtocol.py index 32c277ece8f..91c4072677e 100644 --- a/sandbox/plc4py/plc4py/drivers/modbus/ModbusProtocol.py +++ b/sandbox/plc4py/plc4py/drivers/modbus/ModbusProtocol.py @@ -16,16 +16,45 @@ # specific language governing permissions and limitations # under the License. # -from dataclasses import dataclass +import logging +from asyncio import Future +from dataclasses import dataclass, field +from typing import Dict, Awaitable +from plc4py.protocols.modbus.readwrite.DriverType import DriverType +from plc4py.spi.generation.ReadBuffer import ReadBufferByteBased + +from plc4py.protocols.modbus.readwrite.ModbusTcpADU import ModbusTcpADU from plc4py.spi.Plc4xBaseProtocol import Plc4xBaseProtocol +from plc4py.utils.GenericTypes import ByteOrder @dataclass class ModbusProtocol(Plc4xBaseProtocol): + messages: Dict[int, Future] = field(default_factory=lambda: {}) + def data_received(self, data): - # TODO:- Implement Protocol specific stuff - pass + """Unpack the adu and return the pdu""" + read_buffer = ReadBufferByteBased( + bytearray(data), byte_order=ByteOrder.BIG_ENDIAN + ) + adu: ModbusTcpADU = ModbusTcpADU.static_parse_builder( + read_buffer, DriverType.MODBUS_TCP, True + ).build(True) + if adu.transaction_identifier in self.messages: + self.messages[adu.transaction_identifier].set_result(adu.pdu) + else: + logging.error("Unsolicited message returned") + self.close() + + def write_wait_for_response(self, data, transport, transaction_id, message_future): + """Writes a message to the wire and records the identifier to identify and route the response""" + self.messages[transaction_id] = message_future + transport.write(data) def close(self): - pass + """Clean up the message which didn't receive a response""" + for key, message in self.messages.items: + logging.debug("Removing un-replied message with identifier " + str(key)) + message.set_result(None) + self.messages = None diff --git a/sandbox/plc4py/plc4py/drivers/modbus/ModbusTag.py b/sandbox/plc4py/plc4py/drivers/modbus/ModbusTag.py new file mode 100644 index 00000000000..a67c4197846 --- /dev/null +++ b/sandbox/plc4py/plc4py/drivers/modbus/ModbusTag.py @@ -0,0 +1,179 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +import re +from typing import AnyStr, Pattern + +from plc4py.api.exceptions.exceptions import PlcFieldParseException +from plc4py.api.messages.PlcField import PlcTag +from plc4py.protocols.modbus.readwrite.ModbusDataType import ModbusDataType +from plc4py.spi.messages.PlcRequest import TagBuilder + + +class ModbusTag(PlcTag): + _ADDRESS_PATTERN: str = ( + "(?P
\d+)(:(?P[a-zA-Z_]+))?(\[(?P\d+)\])?" + ) + _FIXED_DIGIT_MODBUS_PATTERN: str = ( + "(?P
\d{4,5})?(:(?P[a-zA-Z_]+))?(\[(?P\d+)\])?" + ) + _PROTOCOL_ADDRESS_OFFSET: int = 1 + _REGISTER_MAX_ADDRESS: int = 65535 + + _ADDRESS_SHORTER_PATTERN: Pattern[AnyStr] = re.compile(_FIXED_DIGIT_MODBUS_PATTERN) + _ADDRESS_SHORT_PATTERN: Pattern[AnyStr] = re.compile(_FIXED_DIGIT_MODBUS_PATTERN) + _DEFAULT_DATA_TYPE: ModbusDataType = ModbusDataType.INT + + _QUANTITY_MAX: int = 120 + + def __init__(self, address: int, quantity: int, data_type: ModbusDataType): + self.address: int = address + self.quantity: int = quantity + self.data_type: ModbusDataType = data_type + + @classmethod + def matches(cls, address_string: str): + return ( + cls._ADDRESS_PATTERN.match(address_string) is not None + or cls._ADDRESS_SHORTER_PATTERN.match(address_string) is not None + or cls._ADDRESS_SHORT_PATTERN.match(address_string) is not None + ) + + @classmethod + def _matcher(cls, address_string): + match = cls._ADDRESS_PATTERN.match(address_string) + if match is not None: + return match + match = cls._ADDRESS_SHORT_PATTERN.match(address_string) + if match is not None: + return match + match = cls._ADDRESS_SHORTER_PATTERN.match(address_string) + if match is not None: + return match + + @classmethod + def create(cls, address_string): + matcher = cls._matcher(address_string) + address: int = ( + int(matcher.group("address")) - ModbusTag._PROTOCOL_ADDRESS_OFFSET + ) + if address > cls._REGISTER_MAX_ADDRESS: + raise PlcFieldParseException( + "Address must be less than or equal to " + + str(cls._REGISTER_MAX_ADDRESS) + + ". Was " + + str(address + cls._PROTOCOL_ADDRESS_OFFSET) + ) + + quantity: int = ( + int(matcher.group("quantity")) + if "quantity" in matcher.groupdict() + and matcher.group("quantity") is not None + else 1 + ) + if (address + quantity) > cls._REGISTER_MAX_ADDRESS: + raise PlcFieldParseException( + "Last requested address is out of range, should be between " + + str(cls._PROTOCOL_ADDRESS_OFFSET) + + " and " + + str(cls._REGISTER_MAX_ADDRESS) + + ". Was " + + str(address + cls._PROTOCOL_ADDRESS_OFFSET + (quantity - 1)) + ) + + if quantity > cls._QUANTITY_MAX: + raise PlcFieldParseException( + "quantity may not be larger than 2000. Was " + str(quantity) + ) + + data_type = ( + ModbusDataType(matcher.group("datatype")) + if "datatype" in matcher.groupdict() + and matcher.group("datatype") is not None + else cls._DEFAULT_DATA_TYPE + ) + return cls(address, quantity, data_type) + + +class ModbusTagCoil(ModbusTag): + _ADDRESS_PREFIX: str = "0x" + _ADDRESS_PATTERN: Pattern[AnyStr] = re.compile("coil:" + ModbusTag._ADDRESS_PATTERN) + _ADDRESS_SHORTER_PATTERN: Pattern[AnyStr] = re.compile( + "0" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + _ADDRESS_SHORT_PATTERN: Pattern[AnyStr] = re.compile( + "0x" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + _DEFAULT_DATA_TYPE: ModbusDataType = ModbusDataType.BOOL + _QUANTITY_MAX: int = 2000 + + +class ModbusTagDiscreteInput(ModbusTag): + _ADDRESS_PREFIX: str = "1x" + _ADDRESS_PATTERN: Pattern[AnyStr] = re.compile( + "discrete-input:" + ModbusTag._ADDRESS_PATTERN + ) + _ADDRESS_SHORTER_PATTERN: Pattern[AnyStr] = re.compile( + "1" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + _ADDRESS_SHORT_PATTERN: Pattern[AnyStr] = re.compile( + "1x" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + _DEFAULT_DATA_TYPE: ModbusDataType = ModbusDataType.BOOL + _QUANTITY_MAX: int = 2000 + + +class ModbusTagInputRegister(ModbusTag): + _ADDRESS_PREFIX: str = "3x" + _ADDRESS_PATTERN: Pattern[AnyStr] = re.compile( + "input-register:" + ModbusTag._ADDRESS_PATTERN + ) + _ADDRESS_SHORTER_PATTERN: Pattern[AnyStr] = re.compile( + "3" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + _ADDRESS_SHORT_PATTERN: Pattern[AnyStr] = re.compile( + "3x" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + + +class ModbusTagHoldingRegister(ModbusTag): + _ADDRESS_PREFIX: str = "4x" + _ADDRESS_PATTERN: Pattern[AnyStr] = re.compile( + "holding-register:" + ModbusTag._ADDRESS_PATTERN + ) + _ADDRESS_SHORTER_PATTERN: Pattern[AnyStr] = re.compile( + "4" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + _ADDRESS_SHORT_PATTERN: Pattern[AnyStr] = re.compile( + "4x" + ModbusTag._FIXED_DIGIT_MODBUS_PATTERN + ) + + +class ModbusTagBuilder(TagBuilder): + @staticmethod + def create(address_string: str) -> ModbusTag: + if ModbusTagCoil.matches(address_string): + return ModbusTagCoil.create(address_string) + elif ModbusTagDiscreteInput.matches(address_string): + return ModbusTagDiscreteInput.create(address_string) + elif ModbusTagInputRegister.matches(address_string): + return ModbusTagInputRegister.create(address_string) + elif ModbusTagHoldingRegister.matches(address_string): + return ModbusTagHoldingRegister.create(address_string) + else: + raise PlcFieldParseException("Unable to parse address: " + address_string) diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DataItem.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DataItem.py index 92e25538903..189fcd327d6 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DataItem.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DataItem.py @@ -17,645 +17,616 @@ # under the License. # -from abc import staticmethod -from loguru import logging as log +from plc4py.api.value.PlcValue import PlcValue from plc4py.protocols.modbus.readwrite.ModbusDataType import ModbusDataType +from plc4py.spi.generation.ReadBuffer import ReadBuffer +from plc4py.spi.generation.WriteBuffer import WriteBuffer +from plc4py.spi.values.PlcValues import PlcBOOL +from plc4py.spi.values.PlcValues import PlcBYTE +from plc4py.spi.values.PlcValues import PlcCHAR +from plc4py.spi.values.PlcValues import PlcDINT +from plc4py.spi.values.PlcValues import PlcDWORD +from plc4py.spi.values.PlcValues import PlcINT +from plc4py.spi.values.PlcValues import PlcLINT +from plc4py.spi.values.PlcValues import PlcLREAL +from plc4py.spi.values.PlcValues import PlcLWORD +from plc4py.spi.values.PlcValues import PlcList +from plc4py.spi.values.PlcValues import PlcREAL +from plc4py.spi.values.PlcValues import PlcSINT +from plc4py.spi.values.PlcValues import PlcSTRING +from plc4py.spi.values.PlcValues import PlcUDINT +from plc4py.spi.values.PlcValues import PlcUINT +from plc4py.spi.values.PlcValues import PlcULINT +from plc4py.spi.values.PlcValues import PlcUSINT +from plc4py.spi.values.PlcValues import PlcWCHAR +from plc4py.spi.values.PlcValues import PlcWORD +from plc4py.utils.GenericTypes import ByteOrder +from typing import List +import logging import math - -class DataItem: +class DataItem: @staticmethod - def static_parse(read_buffer: ReadBuffer, data_type: ModbusDataType, number_of_values: int): - if EvaluationHelper.equals( data_type, ModbusDataType.get_bool() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # BOOL - + def static_parse( + read_buffer: ReadBuffer, data_type: ModbusDataType, number_of_values: int + ): + if data_type == ModbusDataType.BOOL and number_of_values == int(1): # BOOL # Reserved Field (Compartmentalized so the "reserved" variable can't leak) reserved: int = read_buffer.read_unsigned_int(15, logical_name="") if reserved != int(0x0000): - log.info("Expected constant value " + str(0x0000) + " but got " + reserved + " for reserved field.") + logging.warning( + "Expected constant value " + + str(0x0000) + + " but got " + + str(reserved) + + " for reserved field." + ) # Simple Field (value) value: bool = read_buffer.read_bit("") return PlcBOOL(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_bool() ) : # List + if data_type == ModbusDataType.BOOL: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcBOOL(bool(read_buffer.read_bit("")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_byte() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # BYTE - + if data_type == ModbusDataType.BYTE and number_of_values == int(1): # BYTE # Reserved Field (Compartmentalized so the "reserved" variable can't leak) reserved: int = read_buffer.read_unsigned_short(8, logical_name="") if reserved != int(0x00): - log.info("Expected constant value " + str(0x00) + " but got " + reserved + " for reserved field.") + logging.warning( + "Expected constant value " + + str(0x00) + + " but got " + + str(reserved) + + " for reserved field." + ) # Simple Field (value) value: int = read_buffer.read_unsigned_short(8, logical_name="") return PlcBYTE(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_byte() ) : # List + if data_type == ModbusDataType.BYTE: # List # Array field (value) # Count array - if numberOfValues* int(8) > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues* int(8)) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues* int(8)) + item_count: int = int(number_of_values * int(8)) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcBOOL(bool(read_buffer.read_bit("")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_word() ) : # WORD - + if data_type == ModbusDataType.WORD: # WORD # Simple Field (value) value: int = read_buffer.read_unsigned_int(16, logical_name="") return PlcWORD(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_dword() ) : # DWORD - + if data_type == ModbusDataType.DWORD: # DWORD # Simple Field (value) value: int = read_buffer.read_unsigned_long(32, logical_name="") return PlcDWORD(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_lword() ) : # LWORD - + if data_type == ModbusDataType.LWORD: # LWORD # Simple Field (value) - value: int = read_buffer.read_unsigned_big_integer(64, logical_name="") + value: int = read_buffer.read_unsigned_long(64, logical_name="") return PlcLWORD(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_sint() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # SINT - + if data_type == ModbusDataType.SINT and number_of_values == int(1): # SINT # Reserved Field (Compartmentalized so the "reserved" variable can't leak) reserved: int = read_buffer.read_unsigned_short(8, logical_name="") if reserved != int(0x00): - log.info("Expected constant value " + str(0x00) + " but got " + reserved + " for reserved field.") + logging.warning( + "Expected constant value " + + str(0x00) + + " but got " + + str(reserved) + + " for reserved field." + ) # Simple Field (value) value: int = read_buffer.read_signed_byte(8, logical_name="") return PlcSINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_sint() ) : # List + if data_type == ModbusDataType.SINT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcSINT(int(read_buffer.read_signed_byte(8, logical_name="")))) - + value.append( + PlcSINT(int(read_buffer.read_signed_byte(8, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_int() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # INT - + if data_type == ModbusDataType.INT and number_of_values == int(1): # INT # Simple Field (value) value: int = read_buffer.read_short(16, logical_name="") return PlcINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_int() ) : # List + if data_type == ModbusDataType.INT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcINT(int(read_buffer.read_short(16, logical_name="")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_dint() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # DINT - + if data_type == ModbusDataType.DINT and number_of_values == int(1): # DINT # Simple Field (value) value: int = read_buffer.read_int(32, logical_name="") return PlcDINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_dint() ) : # List + if data_type == ModbusDataType.DINT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcDINT(int(read_buffer.read_int(32, logical_name="")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_lint() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # LINT - + if data_type == ModbusDataType.LINT and number_of_values == int(1): # LINT # Simple Field (value) value: int = read_buffer.read_long(64, logical_name="") return PlcLINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_lint() ) : # List + if data_type == ModbusDataType.LINT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcLINT(int(read_buffer.read_long(64, logical_name="")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_usint() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # USINT - + if data_type == ModbusDataType.USINT and number_of_values == int(1): # USINT # Reserved Field (Compartmentalized so the "reserved" variable can't leak) reserved: int = read_buffer.read_unsigned_short(8, logical_name="") if reserved != int(0x00): - log.info("Expected constant value " + str(0x00) + " but got " + reserved + " for reserved field.") + logging.warning( + "Expected constant value " + + str(0x00) + + " but got " + + str(reserved) + + " for reserved field." + ) # Simple Field (value) value: int = read_buffer.read_unsigned_short(8, logical_name="") return PlcUSINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_usint() ) : # List + if data_type == ModbusDataType.USINT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcUINT(int(read_buffer.read_unsigned_short(8, logical_name="")))) - + value.append( + PlcUINT(int(read_buffer.read_unsigned_short(8, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_uint() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # UINT - + if data_type == ModbusDataType.UINT and number_of_values == int(1): # UINT # Simple Field (value) value: int = read_buffer.read_unsigned_int(16, logical_name="") return PlcUINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_uint() ) : # List + if data_type == ModbusDataType.UINT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcUDINT(int(read_buffer.read_unsigned_int(16, logical_name="")))) - + value.append( + PlcUDINT(int(read_buffer.read_unsigned_int(16, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_udint() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # UDINT - + if data_type == ModbusDataType.UDINT and number_of_values == int(1): # UDINT # Simple Field (value) value: int = read_buffer.read_unsigned_long(32, logical_name="") return PlcUDINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_udint() ) : # List + if data_type == ModbusDataType.UDINT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcULINT(int(read_buffer.read_unsigned_long(32, logical_name="")))) - + value.append( + PlcULINT(int(read_buffer.read_unsigned_long(32, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_ulint() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # ULINT - + if data_type == ModbusDataType.ULINT and number_of_values == int(1): # ULINT # Simple Field (value) - value: int = read_buffer.read_unsigned_big_integer(64, logical_name="") + value: int = read_buffer.read_unsigned_long(64, logical_name="") return PlcULINT(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_ulint() ) : # List + if data_type == ModbusDataType.ULINT: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcLINT(int(read_buffer.read_unsigned_big_integer(64, logical_name="")))) - + value.append( + PlcLINT(int(read_buffer.read_unsigned_long(64, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_real() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # REAL - + if data_type == ModbusDataType.REAL and number_of_values == int(1): # REAL # Simple Field (value) value: float = read_buffer.read_float(32, logical_name="") return PlcREAL(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_real() ) : # List + if data_type == ModbusDataType.REAL: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcREAL(float(read_buffer.read_float(32, logical_name="")))) - + value.append( + PlcREAL(float(read_buffer.read_float(32, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_lreal() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # LREAL - + if data_type == ModbusDataType.LREAL and number_of_values == int(1): # LREAL # Simple Field (value) value: float = read_buffer.read_double(64, logical_name="") return PlcLREAL(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_lreal() ) : # List + if data_type == ModbusDataType.LREAL: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcLREAL(float(read_buffer.read_double(64, logical_name="")))) - + value.append( + PlcLREAL(float(read_buffer.read_double(64, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_char() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # CHAR - + if data_type == ModbusDataType.CHAR and number_of_values == int(1): # CHAR # Simple Field (value) - value: str = read_buffer.read_string(8, logical_name="", encoding="") + value: str = read_buffer.read_str(8, logical_name="", encoding="") return PlcCHAR(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_char() ) : # List + if data_type == ModbusDataType.CHAR: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcSTRING(str(read_buffer.read_string(8, logical_name="", encoding="")))) - + value.append( + PlcSTRING( + str(read_buffer.read_str(8, logical_name="", encoding="")) + ) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_wchar() ) and EvaluationHelper.equals( number_of_values, int(1) ) : # WCHAR - + if data_type == ModbusDataType.WCHAR and number_of_values == int(1): # WCHAR # Simple Field (value) - value: str = read_buffer.read_string(16, logical_name="", encoding="") + value: str = read_buffer.read_str(16, logical_name="", encoding="") return PlcWCHAR(value) - if EvaluationHelper.equals( data_type, ModbusDataType.get_wchar() ) : # List + if data_type == ModbusDataType.WCHAR: # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcSTRING(str(read_buffer.read_string(16, logical_name="", encoding="")))) - + value.append( + PlcSTRING( + str(read_buffer.read_str(16, logical_name="", encoding="")) + ) + ) return PlcList(value) return None @staticmethod - def static_serialize(writeBuffer: WriteBuffer, _value: PlcValue, dataType: ModbusDataType, numberOfValues: int) -> None: - static_serialize(writeBuffer, _value, dataType, numberOfValues, ByteOrder.BIG_ENDIAN) - - @staticmethod - def static_serialize(writeBuffer: WriteBuffer, _value: PlcValue, dataType: ModbusDataType, numberOfValues: int, byteOrder: ByteOrder) -> None: - if EvaluationHelper.equals( dataType, ModbusDataType.get_bool() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # BOOL - + def static_serialize( + write_buffer: WriteBuffer, + _value: PlcValue, + data_type: ModbusDataType, + number_of_values: int, + byte_order: ByteOrder, + ) -> None: + if data_type == ModbusDataType.BOOL and number_of_values == int(1): # BOOL # Reserved Field - writeBuffer.WriteUint16("int0x0000", 15, int(0x0000)) + write_buffer.write_unsigned_short(int(0x0000), 15, "int0x0000") # Simple Field (value) - value: bool = _value.getBool() - writeBuffer.WriteBit("value", (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_bool() ) : # List - + value: bool = _value.get_bool() + write_buffer.write_bit((value), "value") + if data_type == ModbusDataType.BOOL: # List values: PlcList = _value - for val in values.getList(): - value: bool = val.getBool() - writeBuffer.WriteBit("value", (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_byte() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # BYTE + for val in values.get_list(): + value: bool = val.get_bool() + write_buffer.write_bit((value), "value") + if data_type == ModbusDataType.BYTE and number_of_values == int(1): # BYTE # Reserved Field - writeBuffer.WriteUint8("int0x00", 8, int(0x00)) + write_buffer.write_byte(int(0x00), 8, "int0x00") # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint8("value", 8, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_byte() ) : # List - + value: int = _value.get_int() + write_buffer.write_byte((value), 8, "value") + if data_type == ModbusDataType.BYTE: # List values: PlcList = _value - for val in values.getList(): - value: bool = val.getBool() - writeBuffer.WriteBit("value", (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_word() ) : # WORD + for val in values.get_list(): + value: bool = val.get_bool() + write_buffer.write_bit((value), "value") + if data_type == ModbusDataType.WORD: # WORD # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint16("value", 16, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_dword() ) : # DWORD - + value: int = _value.get_int() + write_buffer.write_unsigned_short((value), 16, "value") + if data_type == ModbusDataType.DWORD: # DWORD # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint32("value", 32, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_lword() ) : # LWORD - + value: int = _value.get_int() + write_buffer.write_unsigned_int((value), 32, "value") + if data_type == ModbusDataType.LWORD: # LWORD # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint64("value", 64, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_sint() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # SINT - + value: int = _value.get_int() + write_buffer.write_unsigned_long((value), 64, "value") + if data_type == ModbusDataType.SINT and number_of_values == int(1): # SINT # Reserved Field - writeBuffer.WriteUint8("int0x00", 8, int(0x00)) + write_buffer.write_byte(int(0x00), 8, "int0x00") # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt8("value", 8, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_sint() ) : # List - + value: int = _value.get_int() + write_buffer.write_signed_byte((value), 8, "value") + if data_type == ModbusDataType.SINT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt8("value", 8, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_int() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # INT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_signed_byte((value), 8, "value") + if data_type == ModbusDataType.INT and number_of_values == int(1): # INT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt16("value", 16, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_int() ) : # List - + value: int = _value.get_int() + write_buffer.write_short((value), 16, "value") + if data_type == ModbusDataType.INT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt16("value", 16, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_dint() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # DINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_short((value), 16, "value") + if data_type == ModbusDataType.DINT and number_of_values == int(1): # DINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt32("value", 32, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_dint() ) : # List - + value: int = _value.get_int() + write_buffer.write_int((value), 32, "value") + if data_type == ModbusDataType.DINT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt32("value", 32, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_lint() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # LINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_int((value), 32, "value") + if data_type == ModbusDataType.LINT and number_of_values == int(1): # LINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt64("value", 64, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_lint() ) : # List - + value: int = _value.get_int() + write_buffer.write_long((value), 64, "value") + if data_type == ModbusDataType.LINT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt64("value", 64, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_usint() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # USINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_long((value), 64, "value") + if data_type == ModbusDataType.USINT and number_of_values == int(1): # USINT # Reserved Field - writeBuffer.WriteUint8("int0x00", 8, int(0x00)) + write_buffer.write_byte(int(0x00), 8, "int0x00") # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint8("value", 8, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_usint() ) : # List - + value: int = _value.get_int() + write_buffer.write_byte((value), 8, "value") + if data_type == ModbusDataType.USINT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint8("value", 8, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_uint() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # UINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_byte((value), 8, "value") + if data_type == ModbusDataType.UINT and number_of_values == int(1): # UINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint16("value", 16, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_uint() ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_short((value), 16, "value") + if data_type == ModbusDataType.UINT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint16("value", 16, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_udint() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # UDINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_short((value), 16, "value") + if data_type == ModbusDataType.UDINT and number_of_values == int(1): # UDINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint32("value", 32, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_udint() ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_int((value), 32, "value") + if data_type == ModbusDataType.UDINT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint32("value", 32, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_ulint() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # ULINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_int((value), 32, "value") + if data_type == ModbusDataType.ULINT and number_of_values == int(1): # ULINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint64("value", 64, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_ulint() ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_long((value), 64, "value") + if data_type == ModbusDataType.ULINT: # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint64("value", 64, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_real() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # REAL + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_long((value), 64, "value") + if data_type == ModbusDataType.REAL and number_of_values == int(1): # REAL # Simple Field (value) - value: float = _value.getFloat() - writeBuffer.WriteFloat32("value", 32, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_real() ) : # List - + value: float = _value.get_float() + write_buffer.write_float((value), 32, "value") + if data_type == ModbusDataType.REAL: # List values: PlcList = _value - for val in values.getList(): - value: float = val.getFloat() - writeBuffer.WriteFloat32("value", 32, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_lreal() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # LREAL + for val in values.get_list(): + value: float = val.get_float() + write_buffer.write_float((value), 32, "value") + if data_type == ModbusDataType.LREAL and number_of_values == int(1): # LREAL # Simple Field (value) - value: float = _value.getFloat() - writeBuffer.WriteFloat64("value", 64, (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_lreal() ) : # List - + value: float = _value.get_float() + write_buffer.write_double((value), 64, "value") + if data_type == ModbusDataType.LREAL: # List values: PlcList = _value - for val in values.getList(): - value: float = val.getFloat() - writeBuffer.WriteFloat64("value", 64, (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_char() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # CHAR + for val in values.get_list(): + value: float = val.get_float() + write_buffer.write_double((value), 64, "value") + if data_type == ModbusDataType.CHAR and number_of_values == int(1): # CHAR # Simple Field (value) - value: str = _value.getStr() - writeBuffer.WriteString("value", uint32(8), "UTF-8", (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_char() ) : # List - + value: str = _value.get_str() + write_buffer.write_str((value), 8, "UTF-8", "value") + if data_type == ModbusDataType.CHAR: # List values: PlcList = _value - for val in values.getList(): - value: str = val.getStr() - writeBuffer.WriteString("value", uint32(8), "UTF-8", (value)) - - if EvaluationHelper.equals( dataType, ModbusDataType.get_wchar() ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # WCHAR + for val in values.get_list(): + value: str = val.get_str() + write_buffer.write_str((value), 8, "UTF-8", "value") + if data_type == ModbusDataType.WCHAR and number_of_values == int(1): # WCHAR # Simple Field (value) - value: str = _value.getStr() - writeBuffer.WriteString("value", uint32(16), "UTF-16", (value)) - if EvaluationHelper.equals( dataType, ModbusDataType.get_wchar() ) : # List - + value: str = _value.get_str() + write_buffer.write_str((value), 16, "UTF-16", "value") + if data_type == ModbusDataType.WCHAR: # List values: PlcList = _value - for val in values.getList(): - value: str = val.getStr() - writeBuffer.WriteString("value", uint32(16), "UTF-16", (value)) - + for val in values.get_list(): + value: str = val.get_str() + write_buffer.write_str((value), 16, "UTF-16", "value") @staticmethod - def get_length_in_bytes(_value: PlcValue, dataType: ModbusDataType, numberOfValues: int) -> int: - return int(math.ceil(float(getLengthInBits(_value, dataType, numberOfValues)) / 8.0)) - + def get_length_in_bytes( + _value: PlcValue, data_type: ModbusDataType, number_of_values: int + ) -> int: + return int( + math.ceil( + float(DataItem.get_length_in_bits(_value, data_type, number_of_values)) + / 8.0 + ) + ) @staticmethod - def get_length_in_bits(_value: PlcValue, dataType: ModbusDataType, numberOfValues: int) -> int: - sizeInBits: int = 0 - if EvaluationHelper.equals( dataType, ModbusDataType.get_bool() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # BOOL - # Reserved Field - sizeInBits += 15 - # Simple Field (value) - sizeInBits += 1 - if EvaluationHelper.equals( dataType, ModbusDataType.get_bool() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 1 - if EvaluationHelper.equals( dataType, ModbusDataType.get_byte() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # BYTE - # Reserved Field - sizeInBits += 8 - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, ModbusDataType.get_byte() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 1 - if EvaluationHelper.equals( dataType, ModbusDataType.get_word() ): # WORD - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, ModbusDataType.get_dword() ): # DWORD - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, ModbusDataType.get_lword() ): # LWORD - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, ModbusDataType.get_sint() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # SINT - # Reserved Field - sizeInBits += 8 - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, ModbusDataType.get_sint() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 8 - if EvaluationHelper.equals( dataType, ModbusDataType.get_int() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # INT - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, ModbusDataType.get_int() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 16 - if EvaluationHelper.equals( dataType, ModbusDataType.get_dint() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # DINT - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, ModbusDataType.get_dint() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 32 - if EvaluationHelper.equals( dataType, ModbusDataType.get_lint() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # LINT - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, ModbusDataType.get_lint() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 64 - if EvaluationHelper.equals( dataType, ModbusDataType.get_usint() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # USINT - # Reserved Field - sizeInBits += 8 - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, ModbusDataType.get_usint() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 8 - if EvaluationHelper.equals( dataType, ModbusDataType.get_uint() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # UINT - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, ModbusDataType.get_uint() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 16 - if EvaluationHelper.equals( dataType, ModbusDataType.get_udint() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # UDINT - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, ModbusDataType.get_udint() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 32 - if EvaluationHelper.equals( dataType, ModbusDataType.get_ulint() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # ULINT - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, ModbusDataType.get_ulint() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 64 - if EvaluationHelper.equals( dataType, ModbusDataType.get_real() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # REAL - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, ModbusDataType.get_real() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 32 - if EvaluationHelper.equals( dataType, ModbusDataType.get_lreal() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # LREAL - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, ModbusDataType.get_lreal() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 64 - if EvaluationHelper.equals( dataType, ModbusDataType.get_char() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # CHAR - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, ModbusDataType.get_char() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 8 - if EvaluationHelper.equals( dataType, ModbusDataType.get_wchar() ) and EvaluationHelper.equals( numberOfValues, int(1) ): # WCHAR - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, ModbusDataType.get_wchar() ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 16 - return sizeInBits - - - - + def get_length_in_bits( + _value: PlcValue, data_type: ModbusDataType, number_of_values: int + ) -> int: + size_in_bits: int = 0 + if data_type == ModbusDataType.BOOL and number_of_values == int(1): # BOOL + # Reserved Field + size_in_bits += 15 + # Simple Field (value) + size_in_bits += 1 + if data_type == ModbusDataType.BOOL: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 1 + if data_type == ModbusDataType.BYTE and number_of_values == int(1): # BYTE + # Reserved Field + size_in_bits += 8 + # Simple Field (value) + size_in_bits += 8 + if data_type == ModbusDataType.BYTE: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 1 + if data_type == ModbusDataType.WORD: # WORD + # Simple Field (value) + size_in_bits += 16 + if data_type == ModbusDataType.DWORD: # DWORD + # Simple Field (value) + size_in_bits += 32 + if data_type == ModbusDataType.LWORD: # LWORD + # Simple Field (value) + size_in_bits += 64 + if data_type == ModbusDataType.SINT and number_of_values == int(1): # SINT + # Reserved Field + size_in_bits += 8 + # Simple Field (value) + size_in_bits += 8 + if data_type == ModbusDataType.SINT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 8 + if data_type == ModbusDataType.INT and number_of_values == int(1): # INT + # Simple Field (value) + size_in_bits += 16 + if data_type == ModbusDataType.INT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 16 + if data_type == ModbusDataType.DINT and number_of_values == int(1): # DINT + # Simple Field (value) + size_in_bits += 32 + if data_type == ModbusDataType.DINT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 32 + if data_type == ModbusDataType.LINT and number_of_values == int(1): # LINT + # Simple Field (value) + size_in_bits += 64 + if data_type == ModbusDataType.LINT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 64 + if data_type == ModbusDataType.USINT and number_of_values == int(1): # USINT + # Reserved Field + size_in_bits += 8 + # Simple Field (value) + size_in_bits += 8 + if data_type == ModbusDataType.USINT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 8 + if data_type == ModbusDataType.UINT and number_of_values == int(1): # UINT + # Simple Field (value) + size_in_bits += 16 + if data_type == ModbusDataType.UINT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 16 + if data_type == ModbusDataType.UDINT and number_of_values == int(1): # UDINT + # Simple Field (value) + size_in_bits += 32 + if data_type == ModbusDataType.UDINT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 32 + if data_type == ModbusDataType.ULINT and number_of_values == int(1): # ULINT + # Simple Field (value) + size_in_bits += 64 + if data_type == ModbusDataType.ULINT: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 64 + if data_type == ModbusDataType.REAL and number_of_values == int(1): # REAL + # Simple Field (value) + size_in_bits += 32 + if data_type == ModbusDataType.REAL: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 32 + if data_type == ModbusDataType.LREAL and number_of_values == int(1): # LREAL + # Simple Field (value) + size_in_bits += 64 + if data_type == ModbusDataType.LREAL: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 64 + if data_type == ModbusDataType.CHAR and number_of_values == int(1): # CHAR + # Simple Field (value) + size_in_bits += 8 + if data_type == ModbusDataType.CHAR: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 8 + if data_type == ModbusDataType.WCHAR and number_of_values == int(1): # WCHAR + # Simple Field (value) + size_in_bits += 16 + if data_type == ModbusDataType.WCHAR: # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 16 + return size_in_bits diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DriverType.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DriverType.py index 887f425623e..461213ba2a5 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DriverType.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/DriverType.py @@ -18,13 +18,10 @@ # # Code generated by code-generation. DO NOT EDIT. -from enum import IntEnum - -class DriverType(IntEnum): +from aenum import AutoNumberEnum + + +class DriverType(AutoNumberEnum): MODBUS_TCP: int = 0x01 MODBUS_RTU: int = 0x02 MODBUS_ASCII: int = 0x03 - - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusADU.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusADU.py index 6646847c8f6..e0a3c5f8923 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusADU.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusADU.py @@ -21,29 +21,27 @@ from abc import ABC from abc import abstractmethod +from plc4py.api.exceptions.exceptions import ParseException from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.DriverType import DriverType from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass class ModbusADU(ABC, PlcMessage): # Arguments. response: bool - - def __post_init__(self): - super().__init__( ) - # Abstract accessors for discriminator values. @property @abstractmethod def driver_type(self) -> DriverType: pass - @abstractmethod def serialize_modbus_adu_child(self, write_buffer: WriteBuffer) -> None: pass @@ -56,11 +54,10 @@ def serialize(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusADU") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusADU = self @@ -68,57 +65,77 @@ def get_length_in_bits(self) -> int: return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - if args is None: - raise PlcRuntimeException("Wrong number of arguments, expected 2, but got None") - elif args.length != 2: - raise PlcRuntimeException("Wrong number of arguments, expected 2, but got " + str(len(args))) - - driverType: DriverType = 0 - if isinstance(args[0], DriverType): - driverType = DriverType(args[0]) - elif isinstance(args[0], str): - driverType = DriverType(str(args[0])) + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + if kwargs is None: + raise PlcRuntimeException( + "Wrong number of arguments, expected 2, but got None" + ) + + driver_type: DriverType = 0 + if isinstance(kwargs.get("driverType"), DriverType): + driver_type = DriverType(kwargs.get("driverType")) + elif isinstance(kwargs.get("driverType"), str): + driver_type = DriverType(str(kwargs.get("driverType"))) else: - raise PlcRuntimeException("Argument 0 expected to be of type DriverType or a string which is parseable but was " + args[0].getClass().getName()) + raise PlcRuntimeException( + "Argument 0 expected to be of type DriverType or a string which is parseable but was " + + kwargs.get("driverType").getClass().getName() + ) response: bool = False - if isinstance(args[1], bool): - response = bool(args[1]) - elif isinstance(args[1], str): - response = bool(str(args[1])) + if isinstance(kwargs.get("response"), bool): + response = bool(kwargs.get("response")) + elif isinstance(kwargs.get("response"), str): + response = bool(str(kwargs.get("response"))) else: - raise PlcRuntimeException("Argument 1 expected to be of type bool or a string which is parseable but was " + args[1].getClass().getName()) - - return self.static_parse_context(read_buffer, driverType, response) + raise PlcRuntimeException( + "Argument 1 expected to be of type bool or a string which is parseable but was " + + kwargs.get("response").getClass().getName() + ) + return ModbusADU.static_parse_context(read_buffer, driver_type, response) @staticmethod - def static_parse_context(read_buffer: ReadBuffer, driver_type: DriverType, response: bool): + def static_parse_context( + read_buffer: ReadBuffer, driver_type: DriverType, response: bool + ): read_buffer.push_context("ModbusADU") # Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type) builder: ModbusADUBuilder = None - if EvaluationHelper.equals( driverType, DriverType.get_modbu_s__tcp() ): - - builder = ModbusTcpADU.staticParseBuilder(read_buffer, driverType, response) - if EvaluationHelper.equals( driverType, DriverType.get_modbu_s__rtu() ): - - builder = ModbusRtuADU.staticParseBuilder(read_buffer, driverType, response) - if EvaluationHelper.equals( driverType, DriverType.get_modbu_s__ascii() ): - - builder = ModbusAsciiADU.staticParseBuilder(read_buffer, driverType, response) + from plc4py.protocols.modbus.readwrite.ModbusTcpADU import ModbusTcpADU + + if driver_type == DriverType.MODBUS_TCP: + builder = ModbusTcpADU.static_parse_builder( + read_buffer, driver_type, response + ) + from plc4py.protocols.modbus.readwrite.ModbusRtuADU import ModbusRtuADU + + if driver_type == DriverType.MODBUS_RTU: + builder = ModbusRtuADU.static_parse_builder( + read_buffer, driver_type, response + ) + from plc4py.protocols.modbus.readwrite.ModbusAsciiADU import ModbusAsciiADU + + if driver_type == DriverType.MODBUS_ASCII: + builder = ModbusAsciiADU.static_parse_builder( + read_buffer, driver_type, response + ) if builder is None: - raise ParseException("Unsupported case for discriminated type"+" parameters ["+"driverType="+driverType+"]") - + raise ParseException( + "Unsupported case for discriminated type" + + " parameters [" + + "driverType=" + + str(driver_type) + + "]" + ) read_buffer.pop_context("ModbusADU") # Create the instance - _modbus_adu: ModbusADU = builder.build(response ) + _modbus_adu: ModbusADU = builder.build(response) return _modbus_adu - def equals(self, o: object) -> bool: if self == o: return True @@ -133,18 +150,16 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - -class ModbusADUBuilder: - def build(self, response: bool ) -> ModbusADU: pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" - +class ModbusADUBuilder: + def build(self, response: bool) -> ModbusADU: + pass diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusAsciiADU.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusAsciiADU.py index 17b148c4d23..269fa5a9be5 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusAsciiADU.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusAsciiADU.py @@ -19,6 +19,8 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus import StaticHelper from plc4py.protocols.modbus.readwrite.DriverType import DriverType @@ -27,10 +29,12 @@ from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from plc4py.utils.GenericTypes import ByteOrder import math - + + @dataclass -class ModbusAsciiADU(PlcMessage,ModbusADU): +class ModbusAsciiADU(ModbusADU): address: int pdu: ModbusPDU # Arguments. @@ -38,12 +42,6 @@ class ModbusAsciiADU(PlcMessage,ModbusADU): # Accessors for discriminator values. driver_type: DriverType = DriverType.MODBUS_ASCII - - def __post_init__(self): - super().__init__( self.response ) - - - def serialize_modbus_adu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusAsciiADU") @@ -54,44 +52,62 @@ def serialize_modbus_adu_child(self, write_buffer: WriteBuffer): write_buffer.write_serializable(self.pdu, logical_name="pdu") # Checksum Field (checksum) (Calculated) - write_buffer.write_unsigned_byte(int(StaticHelper.ascii_lrc_check(self.address, self.pdu)), logical_name="crc") + write_buffer.write_unsigned_byte( + int(StaticHelper.ascii_lrc_check(address, pdu)), logical_name="crc" + ) write_buffer.pop_context("ModbusAsciiADU") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusAsciiADU = self # Simple field (address) length_in_bits += 8 # Simple field (pdu) - length_in_bits += self.pdu.get_length_in_bits() + length_in_bits += self.pdu.length_in_bits() # Checksum Field (checksum) length_in_bits += 8 return length_in_bits - @staticmethod - def static_parse_builder(read_buffer: ReadBuffer, driver_type: DriverType, response: bool): + def static_parse_builder( + read_buffer: ReadBuffer, driver_type: DriverType, response: bool + ): read_buffer.push_context("ModbusAsciiADU") - self.address= read_simple_field("address", read_unsigned_short, WithOption.WithByteOrder(get_bi_g__endian())) - - self.pdu= read_simple_field("pdu", DataReaderComplexDefault(ModbusPDU.static_parse(read_buffer, bool(response)), read_buffer), WithOption.WithByteOrder(get_bi_g__endian())) - - crc: int = read_checksum_field("crc", read_unsigned_short, (int) (ascii_lrc_check(self.address, self.pdu)), WithOption.WithByteOrder(get_bi_g__endian())) + address: int = read_buffer.read_unsigned_byte( + logical_name="address", + bit_length=8, + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + pdu: ModbusPDU = read_buffer.read_complex( + read_function=ModbusPDU.static_parse, + logical_name="pdu", + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + crc: int = read_buffer.read_unsigned_byte( + logical_name="crc", + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) read_buffer.pop_context("ModbusAsciiADU") # Create the instance - return ModbusAsciiADUBuilder(address, pdu , response ) - + return ModbusAsciiADUBuilder(address, pdu) def equals(self, o: object) -> bool: if self == o: @@ -101,33 +117,37 @@ def equals(self, o: object) -> bool: return False that: ModbusAsciiADU = ModbusAsciiADU(o) - return (self.address == that.address) and (self.pdu == that.pdu) and super().equals(that) and True + return ( + (self.address == that.address) + and (self.pdu == that.pdu) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusAsciiADUBuilder(ModbusADUBuilder): address: int pdu: ModbusPDU - response: bool - def __post_init__(self): - pass - - def build(self,response: bool ) -> ModbusAsciiADU: - modbus_ascii_adu: ModbusAsciiADU = ModbusAsciiADU(self.address, self.pdu , response ) + def build( + self, + response: bool, + ) -> ModbusAsciiADU: + modbus_ascii_adu: ModbusAsciiADU = ModbusAsciiADU( + response, self.address, self.pdu + ) return modbus_ascii_adu - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusConstants.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusConstants.py index 6ef27613155..56c576964c6 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusConstants.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusConstants.py @@ -19,34 +19,32 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - -@dataclass -class ModbusConstants(PlcMessage): - MODBUSTCPDEFAULTPORT: int = int(502) - - - def __post_init__(self): - super().__init__( ) +@dataclass +class ModbusConstants: + MODBUS_TCP_DEFAULT_PORT: int = int(502) def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusConstants") # Const Field (modbusTcpDefaultPort) - write_buffer.write_unsigned_short(self.modbus_tcp_default_port.value, logical_name="modbusTcpDefaultPort") + write_buffer.write_unsigned_short( + self.MODBUS_TCP_DEFAULT_PORT, logical_name="modbusTcpDefaultPort" + ) write_buffer.pop_context("ModbusConstants") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusConstants = self @@ -55,23 +53,23 @@ def get_length_in_bits(self) -> int: return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - return self.static_parse_context(read_buffer) - + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + return ModbusConstants.static_parse_context(read_buffer) @staticmethod def static_parse_context(read_buffer: ReadBuffer): read_buffer.push_context("ModbusConstants") - self.modbus_tcp_default_port: int = read_const_field("modbusTcpDefaultPort", read_unsigned_int, ModbusConstants.MODBUSTCPDEFAULTPORT) + MODBUS_TCP_DEFAULT_PORT: int = read_buffer.read_unsigned_short( + logical_name="modbusTcpDefaultPort" + ) read_buffer.pop_context("ModbusConstants") # Create the instance _modbus_constants: ModbusConstants = ModbusConstants() return _modbus_constants - def equals(self, o: object) -> bool: if self == o: return True @@ -86,14 +84,11 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - - - - + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDataType.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDataType.py index 30261667162..0ab173983c6 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDataType.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDataType.py @@ -18,42 +18,35 @@ # # Code generated by code-generation. DO NOT EDIT. -from enum import IntEnum - -class ModbusDataType(IntEnum): - BOOL: int = (1 , int(2) ) - BYTE: int = (2 , int(2) ) - WORD: int = (3 , int(2) ) - DWORD: int = (4 , int(4) ) - LWORD: int = (5 , int(8) ) - SINT: int = (6 , int(2) ) - INT: int = (7 , int(2) ) - DINT: int = (8 , int(4) ) - LINT: int = (9 , int(8) ) - USINT: int = (10 , int(2) ) - UINT: int = (11 , int(2) ) - UDINT: int = (12 , int(4) ) - ULINT: int = (13 , int(8) ) - REAL: int = (14 , int(4) ) - LREAL: int = (15 , int(8) ) - TIME: int = (16 , int(8) ) - LTIME: int = (17 , int(8) ) - DATE: int = (18 , int(8) ) - LDATE: int = (19 , int(8) ) - TIME_OF_DAY: int = (20 , int(8) ) - LTIME_OF_DAY: int = (21 , int(8) ) - DATE_AND_TIME: int = (22 , int(8) ) - LDATE_AND_TIME: int = (23 , int(8) ) - CHAR: int = (24 , int(1) ) - WCHAR: int = (25 , int(2) ) - STRING: int = (26 , int(1) ) - WSTRING: int = (27 , int(2) ) - - def __new__(cls, value, data_type_size ): - obj = object.__new__(cls) - obj._value_ = value - obj.dataTypeSize = dataTypeSize - return obj - +from aenum import AutoNumberEnum +class ModbusDataType(AutoNumberEnum): + _init_ = "value, data_type_size" + BOOL = (1, int(2)) + BYTE = (2, int(2)) + WORD = (3, int(2)) + DWORD = (4, int(4)) + LWORD = (5, int(8)) + SINT = (6, int(2)) + INT = (7, int(2)) + DINT = (8, int(4)) + LINT = (9, int(8)) + USINT = (10, int(2)) + UINT = (11, int(2)) + UDINT = (12, int(4)) + ULINT = (13, int(8)) + REAL = (14, int(4)) + LREAL = (15, int(8)) + TIME = (16, int(8)) + LTIME = (17, int(8)) + DATE = (18, int(8)) + LDATE = (19, int(8)) + TIME_OF_DAY = (20, int(8)) + LTIME_OF_DAY = (21, int(8)) + DATE_AND_TIME = (22, int(8)) + LDATE_AND_TIME = (23, int(8)) + CHAR = (24, int(1)) + WCHAR = (25, int(2)) + STRING = (26, int(1)) + WSTRING = (27, int(2)) diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationConformityLevel.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationConformityLevel.py index 922cdb6c6e5..5400f121441 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationConformityLevel.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationConformityLevel.py @@ -18,13 +18,10 @@ # # Code generated by code-generation. DO NOT EDIT. -from enum import IntEnum - -class ModbusDeviceInformationConformityLevel(IntEnum): +from aenum import AutoNumberEnum + + +class ModbusDeviceInformationConformityLevel(AutoNumberEnum): BASIC_STREAM_ONLY: int = 0x01 REGULAR_STREAM_ONLY: int = 0x02 EXTENDED_STREAM_ONLY: int = 0x03 - - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationLevel.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationLevel.py index 13e3e1495e9..7e05bccf303 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationLevel.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationLevel.py @@ -18,14 +18,11 @@ # # Code generated by code-generation. DO NOT EDIT. -from enum import IntEnum - -class ModbusDeviceInformationLevel(IntEnum): +from aenum import AutoNumberEnum + + +class ModbusDeviceInformationLevel(AutoNumberEnum): BASIC: int = 0x01 REGULAR: int = 0x02 EXTENDED: int = 0x03 INDIVIDUAL: int = 0x04 - - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationMoreFollows.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationMoreFollows.py index c984321d2f1..2c7fdd92b1b 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationMoreFollows.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationMoreFollows.py @@ -18,12 +18,9 @@ # # Code generated by code-generation. DO NOT EDIT. -from enum import IntEnum - -class ModbusDeviceInformationMoreFollows(IntEnum): - NO_MORE_OBJECTS_AVAILABLE: int = 0x00 - MORE_OBJECTS_AVAILABLE: int = 0xFF - - +from aenum import AutoNumberEnum +class ModbusDeviceInformationMoreFollows(AutoNumberEnum): + NO_MORE_OBJECTS_AVAILABLE: int = 0x00 + MORE_OBJECTS_AVAILABLE: int = 0xFF diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationObject.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationObject.py index 36eeb1694d5..1127f2747b8 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationObject.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusDeviceInformationObject.py @@ -19,23 +19,21 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusDeviceInformationObject(PlcMessage): +class ModbusDeviceInformationObject: object_id: int data: List[int] - - def __post_init__(self): - super().__init__( ) - - - def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusDeviceInformationObject") @@ -43,7 +41,7 @@ def serialize(self, write_buffer: WriteBuffer): write_buffer.write_unsigned_byte(self.object_id, logical_name="objectId") # Implicit Field (object_length) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - object_length: int = (int(len(self.data))) + object_length: int = int(len(self.data)) write_buffer.write_unsigned_byte(object_length, logical_name="objectLength") # Array Field (data) @@ -51,11 +49,10 @@ def serialize(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusDeviceInformationObject") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusDeviceInformationObject = self @@ -66,33 +63,38 @@ def get_length_in_bits(self) -> int: length_in_bits += 8 # Array field - if self.data != None: + if self.data is not None: length_in_bits += 8 * len(self.data) - return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - return self.static_parse_context(read_buffer) - + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + return ModbusDeviceInformationObject.static_parse_context(read_buffer) @staticmethod def static_parse_context(read_buffer: ReadBuffer): read_buffer.push_context("ModbusDeviceInformationObject") - self.object_id= read_simple_field("objectId", read_unsigned_short) + object_id: int = read_buffer.read_unsigned_byte( + logical_name="objectId", bit_length=8 + ) - object_length: int = read_implicit_field("objectLength", read_unsigned_short) + object_length: int = read_buffer.read_unsigned_byte(logical_name="objectLength") - data: List[int] = read_buffer.read_byte_array("data", int(object_length)) + data: List[Any] = read_buffer.read_array_field( + logical_name="data", + read_function=read_buffer.read_byte, + count=object_length, + ) read_buffer.pop_context("ModbusDeviceInformationObject") # Create the instance - _modbus_device_information_object: ModbusDeviceInformationObject = ModbusDeviceInformationObject(object_id, data ) + _modbus_device_information_object: ModbusDeviceInformationObject = ( + ModbusDeviceInformationObject(object_id, data) + ) return _modbus_device_information_object - def equals(self, o: object) -> bool: if self == o: return True @@ -107,14 +109,11 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - - - - + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusErrorCode.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusErrorCode.py index 4101a1e7365..d96d77e67bb 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusErrorCode.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusErrorCode.py @@ -18,9 +18,10 @@ # # Code generated by code-generation. DO NOT EDIT. -from enum import IntEnum - -class ModbusErrorCode(IntEnum): +from aenum import AutoNumberEnum + + +class ModbusErrorCode(AutoNumberEnum): ILLEGAL_FUNCTION: int = 1 ILLEGAL_DATA_ADDRESS: int = 2 ILLEGAL_DATA_VALUE: int = 3 @@ -31,7 +32,3 @@ class ModbusErrorCode(IntEnum): MEMORY_PARITY_ERROR: int = 8 GATEWAY_PATH_UNAVAILABLE: int = 10 GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND: int = 11 - - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDU.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDU.py index 375f8b0e760..d86e4600a61 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDU.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDU.py @@ -21,34 +21,33 @@ from abc import ABC from abc import abstractmethod +from plc4py.api.exceptions.exceptions import ParseException from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - -@dataclass -class ModbusPDU(ABC, PlcMessage): - def __post_init__(self): - super().__init__( ) - +@dataclass +class ModbusPDU(ABC, PlcMessage): # Abstract accessors for discriminator values. @property @abstractmethod def error_flag(self) -> bool: pass + @property @abstractmethod def function_flag(self) -> int: pass + @property @abstractmethod def response(self) -> bool: pass - @abstractmethod def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer) -> None: pass @@ -57,21 +56,28 @@ def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDU") # Discriminator Field (errorFlag) (Used as input to a switch field) - write_buffer.write_boolean(self.error_flag(), logical_name="errorFlag") + write_buffer.write_bit( + self.error_flag, + logical_name="errorFlag", + bit_length=1, + ) # Discriminator Field (functionFlag) (Used as input to a switch field) - write_buffer.write_unsigned_byte(self.function_flag(), logical_name="functionFlag") + write_buffer.write_unsigned_byte( + self.function_flag, + logical_name="functionFlag", + bit_length=7, + ) # Switch field (Serialize the sub-type) self.serialize_modbus_pdu_child(write_buffer) write_buffer.pop_context("ModbusPDU") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusPDU = self @@ -85,161 +91,527 @@ def get_length_in_bits(self) -> int: return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - if args is None: - raise PlcRuntimeException("Wrong number of arguments, expected 1, but got None") - elif args.length != 1: - raise PlcRuntimeException("Wrong number of arguments, expected 1, but got " + str(len(args))) + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + if kwargs is None: + raise PlcRuntimeException( + "Wrong number of arguments, expected 1, but got None" + ) response: bool = False - if isinstance(args[0], bool): - response = bool(args[0]) - elif isinstance(args[0], str): - response = bool(str(args[0])) + if isinstance(kwargs.get("response"), bool): + response = bool(kwargs.get("response")) + elif isinstance(kwargs.get("response"), str): + response = bool(str(kwargs.get("response"))) else: - raise PlcRuntimeException("Argument 0 expected to be of type bool or a string which is parseable but was " + args[0].getClass().getName()) - - return self.static_parse_context(read_buffer, response) + raise PlcRuntimeException( + "Argument 0 expected to be of type bool or a string which is parseable but was " + + kwargs.get("response").getClass().getName() + ) + return ModbusPDU.static_parse_context(read_buffer, response) @staticmethod def static_parse_context(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDU") + error_flag: bool = read_buffer.read_bit( + logical_name="errorFlag", bit_length=1, response=response + ) - error_flag: bool = read_discriminator_field("errorFlag", read_bit) - - function_flag: int = read_discriminator_field("functionFlag", read_unsigned_short) + function_flag: int = read_buffer.read_unsigned_byte( + logical_name="functionFlag", bit_length=7, response=response + ) # Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type) builder: ModbusPDUBuilder = None - if EvaluationHelper.equals( errorFlag, bool(True) ): - - builder = ModbusPDUError.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x02) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadDiscreteInputsRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x02) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadDiscreteInputsResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x01) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadCoilsRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x01) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadCoilsResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x05) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUWriteSingleCoilRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x05) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUWriteSingleCoilResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x0F) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUWriteMultipleCoilsRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x0F) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUWriteMultipleCoilsResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x04) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadInputRegistersRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x04) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadInputRegistersResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x03) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadHoldingRegistersRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x03) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadHoldingRegistersResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x06) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUWriteSingleRegisterRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x06) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUWriteSingleRegisterResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x10) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUWriteMultipleHoldingRegistersRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x10) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUWriteMultipleHoldingRegistersResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x17) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadWriteMultipleHoldingRegistersRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x17) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadWriteMultipleHoldingRegistersResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x16) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUMaskWriteHoldingRegisterRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x16) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUMaskWriteHoldingRegisterResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x18) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadFifoQueueRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x18) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadFifoQueueResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x14) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadFileRecordRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x14) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadFileRecordResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x15) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUWriteFileRecordRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x15) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUWriteFileRecordResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x07) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadExceptionStatusRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x07) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadExceptionStatusResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x08) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUDiagnosticRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x08) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUDiagnosticResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x0B) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUGetComEventCounterRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x0B) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUGetComEventCounterResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x0C) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUGetComEventLogRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x0C) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUGetComEventLogResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x11) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReportServerIdRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x11) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReportServerIdResponse.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x2B) ) and EvaluationHelper.equals( response, bool(False) ): - - builder = ModbusPDUReadDeviceIdentificationRequest.staticParseBuilder(read_buffer, response) - if EvaluationHelper.equals( errorFlag, bool(False) ) and EvaluationHelper.equals( functionFlag, int(0x2B) ) and EvaluationHelper.equals( response, bool(True) ): - - builder = ModbusPDUReadDeviceIdentificationResponse.staticParseBuilder(read_buffer, response) + from plc4py.protocols.modbus.readwrite.ModbusPDUError import ModbusPDUError + + if error_flag == bool(True): + builder = ModbusPDUError.static_parse_builder(read_buffer, response) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadDiscreteInputsRequest import ( + ModbusPDUReadDiscreteInputsRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x02) + and response == bool(False) + ): + builder = ModbusPDUReadDiscreteInputsRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadDiscreteInputsResponse import ( + ModbusPDUReadDiscreteInputsResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x02) + and response == bool(True) + ): + builder = ModbusPDUReadDiscreteInputsResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadCoilsRequest import ( + ModbusPDUReadCoilsRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x01) + and response == bool(False) + ): + builder = ModbusPDUReadCoilsRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadCoilsResponse import ( + ModbusPDUReadCoilsResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x01) + and response == bool(True) + ): + builder = ModbusPDUReadCoilsResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteSingleCoilRequest import ( + ModbusPDUWriteSingleCoilRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x05) + and response == bool(False) + ): + builder = ModbusPDUWriteSingleCoilRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteSingleCoilResponse import ( + ModbusPDUWriteSingleCoilResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x05) + and response == bool(True) + ): + builder = ModbusPDUWriteSingleCoilResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteMultipleCoilsRequest import ( + ModbusPDUWriteMultipleCoilsRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x0F) + and response == bool(False) + ): + builder = ModbusPDUWriteMultipleCoilsRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteMultipleCoilsResponse import ( + ModbusPDUWriteMultipleCoilsResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x0F) + and response == bool(True) + ): + builder = ModbusPDUWriteMultipleCoilsResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadInputRegistersRequest import ( + ModbusPDUReadInputRegistersRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x04) + and response == bool(False) + ): + builder = ModbusPDUReadInputRegistersRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadInputRegistersResponse import ( + ModbusPDUReadInputRegistersResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x04) + and response == bool(True) + ): + builder = ModbusPDUReadInputRegistersResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadHoldingRegistersRequest import ( + ModbusPDUReadHoldingRegistersRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x03) + and response == bool(False) + ): + builder = ModbusPDUReadHoldingRegistersRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadHoldingRegistersResponse import ( + ModbusPDUReadHoldingRegistersResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x03) + and response == bool(True) + ): + builder = ModbusPDUReadHoldingRegistersResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteSingleRegisterRequest import ( + ModbusPDUWriteSingleRegisterRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x06) + and response == bool(False) + ): + builder = ModbusPDUWriteSingleRegisterRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteSingleRegisterResponse import ( + ModbusPDUWriteSingleRegisterResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x06) + and response == bool(True) + ): + builder = ModbusPDUWriteSingleRegisterResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteMultipleHoldingRegistersRequest import ( + ModbusPDUWriteMultipleHoldingRegistersRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x10) + and response == bool(False) + ): + builder = ( + ModbusPDUWriteMultipleHoldingRegistersRequest.static_parse_builder( + read_buffer, response + ) + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteMultipleHoldingRegistersResponse import ( + ModbusPDUWriteMultipleHoldingRegistersResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x10) + and response == bool(True) + ): + builder = ( + ModbusPDUWriteMultipleHoldingRegistersResponse.static_parse_builder( + read_buffer, response + ) + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadWriteMultipleHoldingRegistersRequest import ( + ModbusPDUReadWriteMultipleHoldingRegistersRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x17) + and response == bool(False) + ): + builder = ( + ModbusPDUReadWriteMultipleHoldingRegistersRequest.static_parse_builder( + read_buffer, response + ) + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadWriteMultipleHoldingRegistersResponse import ( + ModbusPDUReadWriteMultipleHoldingRegistersResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x17) + and response == bool(True) + ): + builder = ( + ModbusPDUReadWriteMultipleHoldingRegistersResponse.static_parse_builder( + read_buffer, response + ) + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUMaskWriteHoldingRegisterRequest import ( + ModbusPDUMaskWriteHoldingRegisterRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x16) + and response == bool(False) + ): + builder = ModbusPDUMaskWriteHoldingRegisterRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUMaskWriteHoldingRegisterResponse import ( + ModbusPDUMaskWriteHoldingRegisterResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x16) + and response == bool(True) + ): + builder = ModbusPDUMaskWriteHoldingRegisterResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadFifoQueueRequest import ( + ModbusPDUReadFifoQueueRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x18) + and response == bool(False) + ): + builder = ModbusPDUReadFifoQueueRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadFifoQueueResponse import ( + ModbusPDUReadFifoQueueResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x18) + and response == bool(True) + ): + builder = ModbusPDUReadFifoQueueResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadFileRecordRequest import ( + ModbusPDUReadFileRecordRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x14) + and response == bool(False) + ): + builder = ModbusPDUReadFileRecordRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadFileRecordResponse import ( + ModbusPDUReadFileRecordResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x14) + and response == bool(True) + ): + builder = ModbusPDUReadFileRecordResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteFileRecordRequest import ( + ModbusPDUWriteFileRecordRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x15) + and response == bool(False) + ): + builder = ModbusPDUWriteFileRecordRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUWriteFileRecordResponse import ( + ModbusPDUWriteFileRecordResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x15) + and response == bool(True) + ): + builder = ModbusPDUWriteFileRecordResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadExceptionStatusRequest import ( + ModbusPDUReadExceptionStatusRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x07) + and response == bool(False) + ): + builder = ModbusPDUReadExceptionStatusRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadExceptionStatusResponse import ( + ModbusPDUReadExceptionStatusResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x07) + and response == bool(True) + ): + builder = ModbusPDUReadExceptionStatusResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUDiagnosticRequest import ( + ModbusPDUDiagnosticRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x08) + and response == bool(False) + ): + builder = ModbusPDUDiagnosticRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUDiagnosticResponse import ( + ModbusPDUDiagnosticResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x08) + and response == bool(True) + ): + builder = ModbusPDUDiagnosticResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUGetComEventCounterRequest import ( + ModbusPDUGetComEventCounterRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x0B) + and response == bool(False) + ): + builder = ModbusPDUGetComEventCounterRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUGetComEventCounterResponse import ( + ModbusPDUGetComEventCounterResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x0B) + and response == bool(True) + ): + builder = ModbusPDUGetComEventCounterResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUGetComEventLogRequest import ( + ModbusPDUGetComEventLogRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x0C) + and response == bool(False) + ): + builder = ModbusPDUGetComEventLogRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUGetComEventLogResponse import ( + ModbusPDUGetComEventLogResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x0C) + and response == bool(True) + ): + builder = ModbusPDUGetComEventLogResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReportServerIdRequest import ( + ModbusPDUReportServerIdRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x11) + and response == bool(False) + ): + builder = ModbusPDUReportServerIdRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReportServerIdResponse import ( + ModbusPDUReportServerIdResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x11) + and response == bool(True) + ): + builder = ModbusPDUReportServerIdResponse.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadDeviceIdentificationRequest import ( + ModbusPDUReadDeviceIdentificationRequest, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x2B) + and response == bool(False) + ): + builder = ModbusPDUReadDeviceIdentificationRequest.static_parse_builder( + read_buffer, response + ) + from plc4py.protocols.modbus.readwrite.ModbusPDUReadDeviceIdentificationResponse import ( + ModbusPDUReadDeviceIdentificationResponse, + ) + + if ( + error_flag == bool(False) + and function_flag == int(0x2B) + and response == bool(True) + ): + builder = ModbusPDUReadDeviceIdentificationResponse.static_parse_builder( + read_buffer, response + ) if builder is None: - raise ParseException("Unsupported case for discriminated type"+" parameters ["+"errorFlag="+errorFlag+" "+"functionFlag="+functionFlag+" "+"response="+response+"]") - + raise ParseException( + "Unsupported case for discriminated type" + + " parameters [" + + "errorFlag=" + + str(error_flag) + + " " + + "functionFlag=" + + str(function_flag) + + " " + + "response=" + + str(response) + + "]" + ) read_buffer.pop_context("ModbusPDU") # Create the instance _modbus_pdu: ModbusPDU = builder.build() return _modbus_pdu - def equals(self, o: object) -> bool: if self == o: return True @@ -254,18 +626,18 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - -class ModbusPDUBuilder: - def build(self, ) -> ModbusPDU: pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" - +class ModbusPDUBuilder: + def build( + self, + ) -> ModbusPDU: + pass diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticRequest.py index 71d7ae1d876..f5501d6e2c1 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUDiagnosticRequest(PlcMessage,ModbusPDU): +class ModbusPDUDiagnosticRequest(ModbusPDU): sub_function: int data: int # Accessors for discriminator values. @@ -35,12 +38,6 @@ class ModbusPDUDiagnosticRequest(PlcMessage,ModbusPDU): function_flag: int = 0x08 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUDiagnosticRequest") @@ -52,12 +49,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUDiagnosticRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUDiagnosticRequest = self # Simple field (subFunction) @@ -68,19 +64,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUDiagnosticRequest") - self.sub_function= read_simple_field("subFunction", read_unsigned_int) + sub_function: int = read_buffer.read_unsigned_short( + logical_name="subFunction", bit_length=16, response=response + ) - self.data= read_simple_field("data", read_unsigned_int) + data: int = read_buffer.read_unsigned_short( + logical_name="data", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUDiagnosticRequest") # Create the instance - return ModbusPDUDiagnosticRequestBuilder(sub_function, data ) - + return ModbusPDUDiagnosticRequestBuilder(sub_function, data) def equals(self, o: object) -> bool: if self == o: @@ -90,32 +88,36 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUDiagnosticRequest = ModbusPDUDiagnosticRequest(o) - return (self.sub_function == that.sub_function) and (self.data == that.data) and super().equals(that) and True + return ( + (self.sub_function == that.sub_function) + and (self.data == that.data) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUDiagnosticRequestBuilder(ModbusPDUBuilder): - subFunction: int + sub_function: int data: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUDiagnosticRequest: - modbus_pdu_diagnostic_request: ModbusPDUDiagnosticRequest = ModbusPDUDiagnosticRequest(self.sub_function, self.data ) + def build( + self, + ) -> ModbusPDUDiagnosticRequest: + modbus_pdu_diagnostic_request: ModbusPDUDiagnosticRequest = ( + ModbusPDUDiagnosticRequest(self.sub_function, self.data) + ) return modbus_pdu_diagnostic_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticResponse.py index 536c0f7e613..1c397f8a681 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUDiagnosticResponse.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUDiagnosticResponse(PlcMessage,ModbusPDU): +class ModbusPDUDiagnosticResponse(ModbusPDU): sub_function: int data: int # Accessors for discriminator values. @@ -35,12 +38,6 @@ class ModbusPDUDiagnosticResponse(PlcMessage,ModbusPDU): function_flag: int = 0x08 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUDiagnosticResponse") @@ -52,12 +49,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUDiagnosticResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUDiagnosticResponse = self # Simple field (subFunction) @@ -68,19 +64,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUDiagnosticResponse") - self.sub_function= read_simple_field("subFunction", read_unsigned_int) + sub_function: int = read_buffer.read_unsigned_short( + logical_name="subFunction", bit_length=16, response=response + ) - self.data= read_simple_field("data", read_unsigned_int) + data: int = read_buffer.read_unsigned_short( + logical_name="data", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUDiagnosticResponse") # Create the instance - return ModbusPDUDiagnosticResponseBuilder(sub_function, data ) - + return ModbusPDUDiagnosticResponseBuilder(sub_function, data) def equals(self, o: object) -> bool: if self == o: @@ -90,32 +88,36 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUDiagnosticResponse = ModbusPDUDiagnosticResponse(o) - return (self.sub_function == that.sub_function) and (self.data == that.data) and super().equals(that) and True + return ( + (self.sub_function == that.sub_function) + and (self.data == that.data) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUDiagnosticResponseBuilder(ModbusPDUBuilder): - subFunction: int + sub_function: int data: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUDiagnosticResponse: - modbus_pdu_diagnostic_response: ModbusPDUDiagnosticResponse = ModbusPDUDiagnosticResponse(self.sub_function, self.data ) + def build( + self, + ) -> ModbusPDUDiagnosticResponse: + modbus_pdu_diagnostic_response: ModbusPDUDiagnosticResponse = ( + ModbusPDUDiagnosticResponse(self.sub_function, self.data) + ) return modbus_pdu_diagnostic_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUError.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUError.py index bc5b34a0629..73eca46196a 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUError.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUError.py @@ -19,6 +19,8 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusErrorCode import ModbusErrorCode from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU @@ -26,36 +28,31 @@ from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUError(PlcMessage,ModbusPDU): +class ModbusPDUError(ModbusPDU): exception_code: ModbusErrorCode # Accessors for discriminator values. error_flag: bool = True function_flag: int = 0 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUError") # Simple Field (exceptionCode) - write_buffer.DataWriterEnumDefault(ModbusErrorCode.value, ModbusErrorCode.name, write_unsigned_byte)(self.exception_code, logical_name="exceptionCode") - + write_buffer.write_unsigned_byte( + self.exception_code, logical_name="exceptionCode" + ) write_buffer.pop_context("ModbusPDUError") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUError = self # Simple field (exceptionCode) @@ -63,17 +60,20 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUError") - self.exception_code= read_enum_field("exceptionCode", "ModbusErrorCode", DataReaderEnumDefault(ModbusErrorCode.enumForValue, read_unsigned_short)) + exception_code: ModbusErrorCode = read_buffer.read_enum( + read_function=ModbusErrorCode, + bit_length=8, + logical_name="exceptionCode", + response=response, + ) read_buffer.pop_context("ModbusPDUError") # Create the instance - return ModbusPDUErrorBuilder(exception_code ) - + return ModbusPDUErrorBuilder(exception_code) def equals(self, o: object) -> bool: if self == o: @@ -83,31 +83,32 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUError = ModbusPDUError(o) - return (self.exception_code == that.exception_code) and super().equals(that) and True + return ( + (self.exception_code == that.exception_code) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUErrorBuilder(ModbusPDUBuilder): - exceptionCode: ModbusErrorCode - - def __post_init__(self): - pass + exception_code: ModbusErrorCode - def build(self,) -> ModbusPDUError: - modbus_pdu_error: ModbusPDUError = ModbusPDUError(self.exception_code ) + def build( + self, + ) -> ModbusPDUError: + modbus_pdu_error: ModbusPDUError = ModbusPDUError(self.exception_code) return modbus_pdu_error - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterRequest.py index fa168e67756..f479f66c4cc 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterRequest.py @@ -19,42 +19,37 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUGetComEventCounterRequest(PlcMessage,ModbusPDU): +class ModbusPDUGetComEventCounterRequest(ModbusPDU): # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x0B response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUGetComEventCounterRequest") write_buffer.pop_context("ModbusPDUGetComEventCounterRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUGetComEventCounterRequest = self return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUGetComEventCounterRequest") @@ -63,7 +58,6 @@ def static_parse_builder(read_buffer: ReadBuffer, response: bool): # Create the instance return ModbusPDUGetComEventCounterRequestBuilder() - def equals(self, o: object) -> bool: if self == o: return True @@ -78,24 +72,22 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUGetComEventCounterRequestBuilder(ModbusPDUBuilder): - - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUGetComEventCounterRequest: - modbus_pdu_get_com_event_counter_request: ModbusPDUGetComEventCounterRequest = ModbusPDUGetComEventCounterRequest() + def build( + self, + ) -> ModbusPDUGetComEventCounterRequest: + modbus_pdu_get_com_event_counter_request: ModbusPDUGetComEventCounterRequest = ( + ModbusPDUGetComEventCounterRequest() + ) return modbus_pdu_get_com_event_counter_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterResponse.py index 2f936dfc8b1..4a949a8df4e 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventCounterResponse.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUGetComEventCounterResponse(PlcMessage,ModbusPDU): +class ModbusPDUGetComEventCounterResponse(ModbusPDU): status: int event_count: int # Accessors for discriminator values. @@ -35,12 +38,6 @@ class ModbusPDUGetComEventCounterResponse(PlcMessage,ModbusPDU): function_flag: int = 0x0B response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUGetComEventCounterResponse") @@ -52,12 +49,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUGetComEventCounterResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUGetComEventCounterResponse = self # Simple field (status) @@ -68,19 +64,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUGetComEventCounterResponse") - self.status= read_simple_field("status", read_unsigned_int) + status: int = read_buffer.read_unsigned_short( + logical_name="status", bit_length=16, response=response + ) - self.event_count= read_simple_field("eventCount", read_unsigned_int) + event_count: int = read_buffer.read_unsigned_short( + logical_name="eventCount", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUGetComEventCounterResponse") # Create the instance - return ModbusPDUGetComEventCounterResponseBuilder(status, event_count ) - + return ModbusPDUGetComEventCounterResponseBuilder(status, event_count) def equals(self, o: object) -> bool: if self == o: @@ -89,33 +87,39 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUGetComEventCounterResponse): return False - that: ModbusPDUGetComEventCounterResponse = ModbusPDUGetComEventCounterResponse(o) - return (self.status == that.status) and (self.event_count == that.event_count) and super().equals(that) and True + that: ModbusPDUGetComEventCounterResponse = ModbusPDUGetComEventCounterResponse( + o + ) + return ( + (self.status == that.status) + and (self.event_count == that.event_count) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUGetComEventCounterResponseBuilder(ModbusPDUBuilder): status: int - eventCount: int - - def __post_init__(self): - pass + event_count: int - def build(self,) -> ModbusPDUGetComEventCounterResponse: - modbus_pdu_get_com_event_counter_response: ModbusPDUGetComEventCounterResponse = ModbusPDUGetComEventCounterResponse(self.status, self.event_count ) + def build( + self, + ) -> ModbusPDUGetComEventCounterResponse: + modbus_pdu_get_com_event_counter_response: ModbusPDUGetComEventCounterResponse = ModbusPDUGetComEventCounterResponse( + self.status, self.event_count + ) return modbus_pdu_get_com_event_counter_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogRequest.py index 48f054e73c9..dd3ff4799c1 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogRequest.py @@ -19,42 +19,37 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUGetComEventLogRequest(PlcMessage,ModbusPDU): +class ModbusPDUGetComEventLogRequest(ModbusPDU): # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x0C response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUGetComEventLogRequest") write_buffer.pop_context("ModbusPDUGetComEventLogRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUGetComEventLogRequest = self return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUGetComEventLogRequest") @@ -63,7 +58,6 @@ def static_parse_builder(read_buffer: ReadBuffer, response: bool): # Create the instance return ModbusPDUGetComEventLogRequestBuilder() - def equals(self, o: object) -> bool: if self == o: return True @@ -78,24 +72,22 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUGetComEventLogRequestBuilder(ModbusPDUBuilder): - - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUGetComEventLogRequest: - modbus_pdu_get_com_event_log_request: ModbusPDUGetComEventLogRequest = ModbusPDUGetComEventLogRequest() + def build( + self, + ) -> ModbusPDUGetComEventLogRequest: + modbus_pdu_get_com_event_log_request: ModbusPDUGetComEventLogRequest = ( + ModbusPDUGetComEventLogRequest() + ) return modbus_pdu_get_com_event_log_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogResponse.py index 82487455f94..f7b6516c2d9 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUGetComEventLogResponse.py @@ -19,16 +19,20 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUGetComEventLogResponse(PlcMessage,ModbusPDU): +class ModbusPDUGetComEventLogResponse(ModbusPDU): status: int event_count: int message_count: int @@ -38,17 +42,11 @@ class ModbusPDUGetComEventLogResponse(PlcMessage,ModbusPDU): function_flag: int = 0x0C response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUGetComEventLogResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.events))+ int(6)) + byte_count: int = int(len(self.events)) + int(6) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Simple Field (status) @@ -58,19 +56,20 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.write_unsigned_short(self.event_count, logical_name="eventCount") # Simple Field (messageCount) - write_buffer.write_unsigned_short(self.message_count, logical_name="messageCount") + write_buffer.write_unsigned_short( + self.message_count, logical_name="messageCount" + ) # Array Field (events) write_buffer.write_byte_array(self.events, logical_name="events") write_buffer.pop_context("ModbusPDUGetComEventLogResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUGetComEventLogResponse = self # Implicit Field (byteCount) @@ -86,31 +85,43 @@ def get_length_in_bits(self) -> int: length_in_bits += 16 # Array field - if self.events != None: + if self.events is not None: length_in_bits += 8 * len(self.events) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUGetComEventLogResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - self.status= read_simple_field("status", read_unsigned_int) + status: int = read_buffer.read_unsigned_short( + logical_name="status", bit_length=16, response=response + ) - self.event_count= read_simple_field("eventCount", read_unsigned_int) + event_count: int = read_buffer.read_unsigned_short( + logical_name="eventCount", bit_length=16, response=response + ) - self.message_count= read_simple_field("messageCount", read_unsigned_int) + message_count: int = read_buffer.read_unsigned_short( + logical_name="messageCount", bit_length=16, response=response + ) - events: List[int] = read_buffer.read_byte_array("events", int(byte_count- int(6))) + events: List[Any] = read_buffer.read_array_field( + logical_name="events", + read_function=read_buffer.read_byte, + count=byte_count - int(6), + response=response, + ) read_buffer.pop_context("ModbusPDUGetComEventLogResponse") # Create the instance - return ModbusPDUGetComEventLogResponseBuilder(status, event_count, message_count, events ) - + return ModbusPDUGetComEventLogResponseBuilder( + status, event_count, message_count, events + ) def equals(self, o: object) -> bool: if self == o: @@ -120,34 +131,42 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUGetComEventLogResponse = ModbusPDUGetComEventLogResponse(o) - return (self.status == that.status) and (self.event_count == that.event_count) and (self.message_count == that.message_count) and (self.events == that.events) and super().equals(that) and True + return ( + (self.status == that.status) + and (self.event_count == that.event_count) + and (self.message_count == that.message_count) + and (self.events == that.events) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUGetComEventLogResponseBuilder(ModbusPDUBuilder): status: int - eventCount: int - messageCount: int + event_count: int + message_count: int events: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUGetComEventLogResponse: - modbus_pdu_get_com_event_log_response: ModbusPDUGetComEventLogResponse = ModbusPDUGetComEventLogResponse(self.status, self.event_count, self.message_count, self.events ) + def build( + self, + ) -> ModbusPDUGetComEventLogResponse: + modbus_pdu_get_com_event_log_response: ModbusPDUGetComEventLogResponse = ( + ModbusPDUGetComEventLogResponse( + self.status, self.event_count, self.message_count, self.events + ) + ) return modbus_pdu_get_com_event_log_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterRequest.py index 5c6b647be53..47f8810d843 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUMaskWriteHoldingRegisterRequest(PlcMessage,ModbusPDU): +class ModbusPDUMaskWriteHoldingRegisterRequest(ModbusPDU): reference_address: int and_mask: int or_mask: int @@ -36,17 +39,13 @@ class ModbusPDUMaskWriteHoldingRegisterRequest(PlcMessage,ModbusPDU): function_flag: int = 0x16 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUMaskWriteHoldingRegisterRequest") # Simple Field (referenceAddress) - write_buffer.write_unsigned_short(self.reference_address, logical_name="referenceAddress") + write_buffer.write_unsigned_short( + self.reference_address, logical_name="referenceAddress" + ) # Simple Field (andMask) write_buffer.write_unsigned_short(self.and_mask, logical_name="andMask") @@ -56,12 +55,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUMaskWriteHoldingRegisterRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUMaskWriteHoldingRegisterRequest = self # Simple field (referenceAddress) @@ -75,21 +73,27 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUMaskWriteHoldingRegisterRequest") - self.reference_address= read_simple_field("referenceAddress", read_unsigned_int) + reference_address: int = read_buffer.read_unsigned_short( + logical_name="referenceAddress", bit_length=16, response=response + ) - self.and_mask= read_simple_field("andMask", read_unsigned_int) + and_mask: int = read_buffer.read_unsigned_short( + logical_name="andMask", bit_length=16, response=response + ) - self.or_mask= read_simple_field("orMask", read_unsigned_int) + or_mask: int = read_buffer.read_unsigned_short( + logical_name="orMask", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUMaskWriteHoldingRegisterRequest") # Create the instance - return ModbusPDUMaskWriteHoldingRegisterRequestBuilder(reference_address, and_mask, or_mask ) - + return ModbusPDUMaskWriteHoldingRegisterRequestBuilder( + reference_address, and_mask, or_mask + ) def equals(self, o: object) -> bool: if self == o: @@ -98,34 +102,41 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUMaskWriteHoldingRegisterRequest): return False - that: ModbusPDUMaskWriteHoldingRegisterRequest = ModbusPDUMaskWriteHoldingRegisterRequest(o) - return (self.reference_address == that.reference_address) and (self.and_mask == that.and_mask) and (self.or_mask == that.or_mask) and super().equals(that) and True + that: ModbusPDUMaskWriteHoldingRegisterRequest = ( + ModbusPDUMaskWriteHoldingRegisterRequest(o) + ) + return ( + (self.reference_address == that.reference_address) + and (self.and_mask == that.and_mask) + and (self.or_mask == that.or_mask) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUMaskWriteHoldingRegisterRequestBuilder(ModbusPDUBuilder): - referenceAddress: int - andMask: int - orMask: int - - def __post_init__(self): - pass + reference_address: int + and_mask: int + or_mask: int - def build(self,) -> ModbusPDUMaskWriteHoldingRegisterRequest: - modbus_pdu_mask_write_holding_register_request: ModbusPDUMaskWriteHoldingRegisterRequest = ModbusPDUMaskWriteHoldingRegisterRequest(self.reference_address, self.and_mask, self.or_mask ) + def build( + self, + ) -> ModbusPDUMaskWriteHoldingRegisterRequest: + modbus_pdu_mask_write_holding_register_request: ModbusPDUMaskWriteHoldingRegisterRequest = ModbusPDUMaskWriteHoldingRegisterRequest( + self.reference_address, self.and_mask, self.or_mask + ) return modbus_pdu_mask_write_holding_register_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterResponse.py index bf63c1ae25a..ad6c1de2d9b 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUMaskWriteHoldingRegisterResponse.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUMaskWriteHoldingRegisterResponse(PlcMessage,ModbusPDU): +class ModbusPDUMaskWriteHoldingRegisterResponse(ModbusPDU): reference_address: int and_mask: int or_mask: int @@ -36,17 +39,13 @@ class ModbusPDUMaskWriteHoldingRegisterResponse(PlcMessage,ModbusPDU): function_flag: int = 0x16 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUMaskWriteHoldingRegisterResponse") # Simple Field (referenceAddress) - write_buffer.write_unsigned_short(self.reference_address, logical_name="referenceAddress") + write_buffer.write_unsigned_short( + self.reference_address, logical_name="referenceAddress" + ) # Simple Field (andMask) write_buffer.write_unsigned_short(self.and_mask, logical_name="andMask") @@ -56,12 +55,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUMaskWriteHoldingRegisterResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUMaskWriteHoldingRegisterResponse = self # Simple field (referenceAddress) @@ -75,21 +73,27 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUMaskWriteHoldingRegisterResponse") - self.reference_address= read_simple_field("referenceAddress", read_unsigned_int) + reference_address: int = read_buffer.read_unsigned_short( + logical_name="referenceAddress", bit_length=16, response=response + ) - self.and_mask= read_simple_field("andMask", read_unsigned_int) + and_mask: int = read_buffer.read_unsigned_short( + logical_name="andMask", bit_length=16, response=response + ) - self.or_mask= read_simple_field("orMask", read_unsigned_int) + or_mask: int = read_buffer.read_unsigned_short( + logical_name="orMask", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUMaskWriteHoldingRegisterResponse") # Create the instance - return ModbusPDUMaskWriteHoldingRegisterResponseBuilder(reference_address, and_mask, or_mask ) - + return ModbusPDUMaskWriteHoldingRegisterResponseBuilder( + reference_address, and_mask, or_mask + ) def equals(self, o: object) -> bool: if self == o: @@ -98,34 +102,41 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUMaskWriteHoldingRegisterResponse): return False - that: ModbusPDUMaskWriteHoldingRegisterResponse = ModbusPDUMaskWriteHoldingRegisterResponse(o) - return (self.reference_address == that.reference_address) and (self.and_mask == that.and_mask) and (self.or_mask == that.or_mask) and super().equals(that) and True + that: ModbusPDUMaskWriteHoldingRegisterResponse = ( + ModbusPDUMaskWriteHoldingRegisterResponse(o) + ) + return ( + (self.reference_address == that.reference_address) + and (self.and_mask == that.and_mask) + and (self.or_mask == that.or_mask) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUMaskWriteHoldingRegisterResponseBuilder(ModbusPDUBuilder): - referenceAddress: int - andMask: int - orMask: int - - def __post_init__(self): - pass + reference_address: int + and_mask: int + or_mask: int - def build(self,) -> ModbusPDUMaskWriteHoldingRegisterResponse: - modbus_pdu_mask_write_holding_register_response: ModbusPDUMaskWriteHoldingRegisterResponse = ModbusPDUMaskWriteHoldingRegisterResponse(self.reference_address, self.and_mask, self.or_mask ) + def build( + self, + ) -> ModbusPDUMaskWriteHoldingRegisterResponse: + modbus_pdu_mask_write_holding_register_response: ModbusPDUMaskWriteHoldingRegisterResponse = ModbusPDUMaskWriteHoldingRegisterResponse( + self.reference_address, self.and_mask, self.or_mask + ) return modbus_pdu_mask_write_holding_register_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsRequest.py index fe142c9ba12..83a90c7dc2a 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadCoilsRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadCoilsRequest(ModbusPDU): starting_address: int quantity: int # Accessors for discriminator values. @@ -35,29 +38,24 @@ class ModbusPDUReadCoilsRequest(PlcMessage,ModbusPDU): function_flag: int = 0x01 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadCoilsRequest") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") write_buffer.pop_context("ModbusPDUReadCoilsRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadCoilsRequest = self # Simple field (startingAddress) @@ -68,19 +66,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadCoilsRequest") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUReadCoilsRequest") # Create the instance - return ModbusPDUReadCoilsRequestBuilder(starting_address, quantity ) - + return ModbusPDUReadCoilsRequestBuilder(starting_address, quantity) def equals(self, o: object) -> bool: if self == o: @@ -90,32 +90,36 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUReadCoilsRequest = ModbusPDUReadCoilsRequest(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and super().equals(that) and True + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadCoilsRequestBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadCoilsRequest: - modbus_pdu_read_coils_request: ModbusPDUReadCoilsRequest = ModbusPDUReadCoilsRequest(self.starting_address, self.quantity ) + def build( + self, + ) -> ModbusPDUReadCoilsRequest: + modbus_pdu_read_coils_request: ModbusPDUReadCoilsRequest = ( + ModbusPDUReadCoilsRequest(self.starting_address, self.quantity) + ) return modbus_pdu_read_coils_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsResponse.py index ebc242fa050..4cf12012291 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadCoilsResponse.py @@ -19,33 +19,31 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadCoilsResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadCoilsResponse(ModbusPDU): value: List[int] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x01 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadCoilsResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -53,37 +51,40 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadCoilsResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadCoilsResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadCoilsResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadCoilsResponse") # Create the instance - return ModbusPDUReadCoilsResponseBuilder(value ) - + return ModbusPDUReadCoilsResponseBuilder(value) def equals(self, o: object) -> bool: if self == o: @@ -99,25 +100,24 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadCoilsResponseBuilder(ModbusPDUBuilder): value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadCoilsResponse: - modbus_pdu_read_coils_response: ModbusPDUReadCoilsResponse = ModbusPDUReadCoilsResponse(self.value ) + def build( + self, + ) -> ModbusPDUReadCoilsResponse: + modbus_pdu_read_coils_response: ModbusPDUReadCoilsResponse = ( + ModbusPDUReadCoilsResponse(self.value) + ) return modbus_pdu_read_coils_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationRequest.py index aafec0182d9..80410cc4674 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationRequest.py @@ -19,51 +19,48 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage -from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationLevel import ModbusDeviceInformationLevel +from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationLevel import ( + ModbusDeviceInformationLevel, +) from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadDeviceIdentificationRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadDeviceIdentificationRequest(ModbusPDU): level: ModbusDeviceInformationLevel object_id: int - MEITYPE: int = 0x0E + MEI_TYPE: int = 0x0E # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x2B response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadDeviceIdentificationRequest") # Const Field (meiType) - write_buffer.write_unsigned_byte(self.mei_type.value, logical_name="meiType") + write_buffer.write_unsigned_byte(self.MEI_TYPE, logical_name="meiType") # Simple Field (level) - write_buffer.DataWriterEnumDefault(ModbusDeviceInformationLevel.value, ModbusDeviceInformationLevel.name, write_unsigned_byte)(self.level, logical_name="level") - + write_buffer.write_unsigned_byte(self.level, logical_name="level") # Simple Field (objectId) write_buffer.write_unsigned_byte(self.object_id, logical_name="objectId") write_buffer.pop_context("ModbusPDUReadDeviceIdentificationRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadDeviceIdentificationRequest = self # Const Field (meiType) @@ -77,21 +74,28 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadDeviceIdentificationRequest") - self.mei_type: int = read_const_field("meiType", read_unsigned_short, ModbusPDUReadDeviceIdentificationRequest.MEITYPE) + MEI_TYPE: int = read_buffer.read_unsigned_byte( + logical_name="meiType", response=response + ) - self.level= read_enum_field("level", "ModbusDeviceInformationLevel", DataReaderEnumDefault(ModbusDeviceInformationLevel.enumForValue, read_unsigned_short)) + level: ModbusDeviceInformationLevel = read_buffer.read_enum( + read_function=ModbusDeviceInformationLevel, + bit_length=8, + logical_name="level", + response=response, + ) - self.object_id= read_simple_field("objectId", read_unsigned_short) + object_id: int = read_buffer.read_unsigned_byte( + logical_name="objectId", bit_length=8, response=response + ) read_buffer.pop_context("ModbusPDUReadDeviceIdentificationRequest") # Create the instance - return ModbusPDUReadDeviceIdentificationRequestBuilder(level, object_id ) - + return ModbusPDUReadDeviceIdentificationRequestBuilder(level, object_id) def equals(self, o: object) -> bool: if self == o: @@ -100,33 +104,39 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadDeviceIdentificationRequest): return False - that: ModbusPDUReadDeviceIdentificationRequest = ModbusPDUReadDeviceIdentificationRequest(o) - return (self.level == that.level) and (self.object_id == that.object_id) and super().equals(that) and True + that: ModbusPDUReadDeviceIdentificationRequest = ( + ModbusPDUReadDeviceIdentificationRequest(o) + ) + return ( + (self.level == that.level) + and (self.object_id == that.object_id) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadDeviceIdentificationRequestBuilder(ModbusPDUBuilder): level: ModbusDeviceInformationLevel - objectId: int - - def __post_init__(self): - pass + object_id: int - def build(self,) -> ModbusPDUReadDeviceIdentificationRequest: - modbus_pdu_read_device_identification_request: ModbusPDUReadDeviceIdentificationRequest = ModbusPDUReadDeviceIdentificationRequest(self.level, self.object_id ) + def build( + self, + ) -> ModbusPDUReadDeviceIdentificationRequest: + modbus_pdu_read_device_identification_request: ModbusPDUReadDeviceIdentificationRequest = ModbusPDUReadDeviceIdentificationRequest( + self.level, self.object_id + ) return modbus_pdu_read_device_identification_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationResponse.py index 3b95753ad03..042cb555fc9 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDeviceIdentificationResponse.py @@ -19,11 +19,21 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage -from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationConformityLevel import ModbusDeviceInformationConformityLevel -from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationLevel import ModbusDeviceInformationLevel -from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationMoreFollows import ModbusDeviceInformationMoreFollows -from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationObject import ModbusDeviceInformationObject +from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationConformityLevel import ( + ModbusDeviceInformationConformityLevel, +) +from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationLevel import ( + ModbusDeviceInformationLevel, +) +from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationMoreFollows import ( + ModbusDeviceInformationMoreFollows, +) +from plc4py.protocols.modbus.readwrite.ModbusDeviceInformationObject import ( + ModbusDeviceInformationObject, +) from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer @@ -31,66 +41,63 @@ from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadDeviceIdentificationResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadDeviceIdentificationResponse(ModbusPDU): level: ModbusDeviceInformationLevel individual_access: bool conformity_level: ModbusDeviceInformationConformityLevel more_follows: ModbusDeviceInformationMoreFollows next_object_id: int objects: List[ModbusDeviceInformationObject] - MEITYPE: int = 0x0E + MEI_TYPE: int = 0x0E # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x2B response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadDeviceIdentificationResponse") # Const Field (meiType) - write_buffer.write_unsigned_byte(self.mei_type.value, logical_name="meiType") + write_buffer.write_unsigned_byte(self.MEI_TYPE, logical_name="meiType") # Simple Field (level) - write_buffer.DataWriterEnumDefault(ModbusDeviceInformationLevel.value, ModbusDeviceInformationLevel.name, write_unsigned_byte)(self.level, logical_name="level") - + write_buffer.write_unsigned_byte(self.level, logical_name="level") # Simple Field (individualAccess) - write_buffer.write_boolean(self.individual_access, logical_name="individualAccess") + write_buffer.write_bit(self.individual_access, logical_name="individualAccess") # Simple Field (conformityLevel) - write_buffer.DataWriterEnumDefault(ModbusDeviceInformationConformityLevel.value, ModbusDeviceInformationConformityLevel.name, write_unsigned_byte)(self.conformity_level, logical_name="conformityLevel") - + write_buffer.write_unsigned_byte( + self.conformity_level, logical_name="conformityLevel" + ) # Simple Field (moreFollows) - write_buffer.DataWriterEnumDefault(ModbusDeviceInformationMoreFollows.value, ModbusDeviceInformationMoreFollows.name, write_unsigned_byte)(self.more_follows, logical_name="moreFollows") - + write_buffer.write_unsigned_byte(self.more_follows, logical_name="moreFollows") # Simple Field (nextObjectId) - write_buffer.write_unsigned_byte(self.next_object_id, logical_name="nextObjectId") + write_buffer.write_unsigned_byte( + self.next_object_id, logical_name="nextObjectId" + ) # Implicit Field (number_of_objects) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - number_of_objects: int = (int(len(self.objects))) - write_buffer.write_unsigned_byte(number_of_objects, logical_name="numberOfObjects") + number_of_objects: int = int(len(self.objects)) + write_buffer.write_unsigned_byte( + number_of_objects, logical_name="numberOfObjects" + ) # Array Field (objects) write_buffer.write_complex_array(self.objects, logical_name="objects") write_buffer.pop_context("ModbusPDUReadDeviceIdentificationResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadDeviceIdentificationResponse = self # Const Field (meiType) @@ -115,41 +122,72 @@ def get_length_in_bits(self) -> int: length_in_bits += 8 # Array field - if self.objects != None: - i: int = 0 + if self.objects is not None: for element in self.objects: - last: bool = ++i >= len(self.objects) - length_in_bits += element.get_length_in_bits() - - + length_in_bits += element.length_in_bits() return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadDeviceIdentificationResponse") - self.mei_type: int = read_const_field("meiType", read_unsigned_short, ModbusPDUReadDeviceIdentificationResponse.MEITYPE) - - self.level= read_enum_field("level", "ModbusDeviceInformationLevel", DataReaderEnumDefault(ModbusDeviceInformationLevel.enumForValue, read_unsigned_short)) - - self.individual_access= read_simple_field("individualAccess", read_bit) - - self.conformity_level= read_enum_field("conformityLevel", "ModbusDeviceInformationConformityLevel", DataReaderEnumDefault(ModbusDeviceInformationConformityLevel.enumForValue, read_unsigned_short)) - - self.more_follows= read_enum_field("moreFollows", "ModbusDeviceInformationMoreFollows", DataReaderEnumDefault(ModbusDeviceInformationMoreFollows.enumForValue, read_unsigned_short)) - - self.next_object_id= read_simple_field("nextObjectId", read_unsigned_short) - - number_of_objects: int = read_implicit_field("numberOfObjects", read_unsigned_short) - - objects: List[Any] = read_buffer.read_array_field("objects", read_buffer.DataReaderComplexDefault(ModbusDeviceInformationObject.static_parse(read_buffer), read_buffer), count=number_of_objects) + MEI_TYPE: int = read_buffer.read_unsigned_byte( + logical_name="meiType", response=response + ) + + level: ModbusDeviceInformationLevel = read_buffer.read_enum( + read_function=ModbusDeviceInformationLevel, + bit_length=8, + logical_name="level", + response=response, + ) + + individual_access: bool = read_buffer.read_bit( + logical_name="individualAccess", bit_length=1, response=response + ) + + conformity_level: ModbusDeviceInformationConformityLevel = ( + read_buffer.read_enum( + read_function=ModbusDeviceInformationConformityLevel, + bit_length=7, + logical_name="conformityLevel", + response=response, + ) + ) + + more_follows: ModbusDeviceInformationMoreFollows = read_buffer.read_enum( + read_function=ModbusDeviceInformationMoreFollows, + bit_length=8, + logical_name="moreFollows", + response=response, + ) + + next_object_id: int = read_buffer.read_unsigned_byte( + logical_name="nextObjectId", bit_length=8, response=response + ) + + number_of_objects: int = read_buffer.read_unsigned_byte( + logical_name="numberOfObjects", response=response + ) + + objects: List[Any] = read_buffer.read_array_field( + logical_name="objects", + read_function=ModbusDeviceInformationObject.static_parse, + count=number_of_objects, + response=response, + ) read_buffer.pop_context("ModbusPDUReadDeviceIdentificationResponse") # Create the instance - return ModbusPDUReadDeviceIdentificationResponseBuilder(level, individual_access, conformity_level, more_follows, next_object_id, objects ) - + return ModbusPDUReadDeviceIdentificationResponseBuilder( + level, + individual_access, + conformity_level, + more_follows, + next_object_id, + objects, + ) def equals(self, o: object) -> bool: if self == o: @@ -158,37 +196,52 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadDeviceIdentificationResponse): return False - that: ModbusPDUReadDeviceIdentificationResponse = ModbusPDUReadDeviceIdentificationResponse(o) - return (self.level == that.level) and (self.individual_access == that.individual_access) and (self.conformity_level == that.conformity_level) and (self.more_follows == that.more_follows) and (self.next_object_id == that.next_object_id) and (self.objects == that.objects) and super().equals(that) and True + that: ModbusPDUReadDeviceIdentificationResponse = ( + ModbusPDUReadDeviceIdentificationResponse(o) + ) + return ( + (self.level == that.level) + and (self.individual_access == that.individual_access) + and (self.conformity_level == that.conformity_level) + and (self.more_follows == that.more_follows) + and (self.next_object_id == that.next_object_id) + and (self.objects == that.objects) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadDeviceIdentificationResponseBuilder(ModbusPDUBuilder): level: ModbusDeviceInformationLevel - individualAccess: bool - conformityLevel: ModbusDeviceInformationConformityLevel - moreFollows: ModbusDeviceInformationMoreFollows - nextObjectId: int + individual_access: bool + conformity_level: ModbusDeviceInformationConformityLevel + more_follows: ModbusDeviceInformationMoreFollows + next_object_id: int objects: List[ModbusDeviceInformationObject] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadDeviceIdentificationResponse: - modbus_pdu_read_device_identification_response: ModbusPDUReadDeviceIdentificationResponse = ModbusPDUReadDeviceIdentificationResponse(self.level, self.individual_access, self.conformity_level, self.more_follows, self.next_object_id, self.objects ) + def build( + self, + ) -> ModbusPDUReadDeviceIdentificationResponse: + modbus_pdu_read_device_identification_response: ModbusPDUReadDeviceIdentificationResponse = ModbusPDUReadDeviceIdentificationResponse( + self.level, + self.individual_access, + self.conformity_level, + self.more_follows, + self.next_object_id, + self.objects, + ) return modbus_pdu_read_device_identification_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsRequest.py index af16e66183a..df5010d5b91 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadDiscreteInputsRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadDiscreteInputsRequest(ModbusPDU): starting_address: int quantity: int # Accessors for discriminator values. @@ -35,29 +38,24 @@ class ModbusPDUReadDiscreteInputsRequest(PlcMessage,ModbusPDU): function_flag: int = 0x02 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadDiscreteInputsRequest") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") write_buffer.pop_context("ModbusPDUReadDiscreteInputsRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadDiscreteInputsRequest = self # Simple field (startingAddress) @@ -68,19 +66,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadDiscreteInputsRequest") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUReadDiscreteInputsRequest") # Create the instance - return ModbusPDUReadDiscreteInputsRequestBuilder(starting_address, quantity ) - + return ModbusPDUReadDiscreteInputsRequestBuilder(starting_address, quantity) def equals(self, o: object) -> bool: if self == o: @@ -90,32 +90,36 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUReadDiscreteInputsRequest = ModbusPDUReadDiscreteInputsRequest(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and super().equals(that) and True + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadDiscreteInputsRequestBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadDiscreteInputsRequest: - modbus_pdu_read_discrete_inputs_request: ModbusPDUReadDiscreteInputsRequest = ModbusPDUReadDiscreteInputsRequest(self.starting_address, self.quantity ) + def build( + self, + ) -> ModbusPDUReadDiscreteInputsRequest: + modbus_pdu_read_discrete_inputs_request: ModbusPDUReadDiscreteInputsRequest = ( + ModbusPDUReadDiscreteInputsRequest(self.starting_address, self.quantity) + ) return modbus_pdu_read_discrete_inputs_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsResponse.py index cd4e14d8996..d88d4bf623e 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadDiscreteInputsResponse.py @@ -19,33 +19,31 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadDiscreteInputsResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadDiscreteInputsResponse(ModbusPDU): value: List[int] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x02 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadDiscreteInputsResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -53,37 +51,40 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadDiscreteInputsResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadDiscreteInputsResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadDiscreteInputsResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadDiscreteInputsResponse") # Create the instance - return ModbusPDUReadDiscreteInputsResponseBuilder(value ) - + return ModbusPDUReadDiscreteInputsResponseBuilder(value) def equals(self, o: object) -> bool: if self == o: @@ -92,32 +93,33 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadDiscreteInputsResponse): return False - that: ModbusPDUReadDiscreteInputsResponse = ModbusPDUReadDiscreteInputsResponse(o) + that: ModbusPDUReadDiscreteInputsResponse = ModbusPDUReadDiscreteInputsResponse( + o + ) return (self.value == that.value) and super().equals(that) and True def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadDiscreteInputsResponseBuilder(ModbusPDUBuilder): value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadDiscreteInputsResponse: - modbus_pdu_read_discrete_inputs_response: ModbusPDUReadDiscreteInputsResponse = ModbusPDUReadDiscreteInputsResponse(self.value ) + def build( + self, + ) -> ModbusPDUReadDiscreteInputsResponse: + modbus_pdu_read_discrete_inputs_response: ModbusPDUReadDiscreteInputsResponse = ModbusPDUReadDiscreteInputsResponse( + self.value + ) return modbus_pdu_read_discrete_inputs_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusRequest.py index c4cdd4917bf..50f61bda450 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusRequest.py @@ -19,42 +19,37 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadExceptionStatusRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadExceptionStatusRequest(ModbusPDU): # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x07 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadExceptionStatusRequest") write_buffer.pop_context("ModbusPDUReadExceptionStatusRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadExceptionStatusRequest = self return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadExceptionStatusRequest") @@ -63,7 +58,6 @@ def static_parse_builder(read_buffer: ReadBuffer, response: bool): # Create the instance return ModbusPDUReadExceptionStatusRequestBuilder() - def equals(self, o: object) -> bool: if self == o: return True @@ -71,31 +65,31 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadExceptionStatusRequest): return False - that: ModbusPDUReadExceptionStatusRequest = ModbusPDUReadExceptionStatusRequest(o) + that: ModbusPDUReadExceptionStatusRequest = ModbusPDUReadExceptionStatusRequest( + o + ) return super().equals(that) and True def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadExceptionStatusRequestBuilder(ModbusPDUBuilder): - - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadExceptionStatusRequest: - modbus_pdu_read_exception_status_request: ModbusPDUReadExceptionStatusRequest = ModbusPDUReadExceptionStatusRequest() + def build( + self, + ) -> ModbusPDUReadExceptionStatusRequest: + modbus_pdu_read_exception_status_request: ModbusPDUReadExceptionStatusRequest = ( + ModbusPDUReadExceptionStatusRequest() + ) return modbus_pdu_read_exception_status_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusResponse.py index cacad0d619f..a725aa15926 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadExceptionStatusResponse.py @@ -19,27 +19,24 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadExceptionStatusResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadExceptionStatusResponse(ModbusPDU): value: int # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x07 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadExceptionStatusResponse") @@ -48,12 +45,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadExceptionStatusResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadExceptionStatusResponse = self # Simple field (value) @@ -61,17 +57,17 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadExceptionStatusResponse") - self.value= read_simple_field("value", read_unsigned_short) + value: int = read_buffer.read_unsigned_byte( + logical_name="value", bit_length=8, response=response + ) read_buffer.pop_context("ModbusPDUReadExceptionStatusResponse") # Create the instance - return ModbusPDUReadExceptionStatusResponseBuilder(value ) - + return ModbusPDUReadExceptionStatusResponseBuilder(value) def equals(self, o: object) -> bool: if self == o: @@ -80,32 +76,33 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadExceptionStatusResponse): return False - that: ModbusPDUReadExceptionStatusResponse = ModbusPDUReadExceptionStatusResponse(o) + that: ModbusPDUReadExceptionStatusResponse = ( + ModbusPDUReadExceptionStatusResponse(o) + ) return (self.value == that.value) and super().equals(that) and True def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadExceptionStatusResponseBuilder(ModbusPDUBuilder): value: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadExceptionStatusResponse: - modbus_pdu_read_exception_status_response: ModbusPDUReadExceptionStatusResponse = ModbusPDUReadExceptionStatusResponse(self.value ) + def build( + self, + ) -> ModbusPDUReadExceptionStatusResponse: + modbus_pdu_read_exception_status_response: ModbusPDUReadExceptionStatusResponse = ModbusPDUReadExceptionStatusResponse( + self.value + ) return modbus_pdu_read_exception_status_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueRequest.py index e0de508408a..ad63375a7ba 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueRequest.py @@ -19,41 +19,39 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadFifoQueueRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadFifoQueueRequest(ModbusPDU): fifo_pointer_address: int # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x18 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadFifoQueueRequest") # Simple Field (fifoPointerAddress) - write_buffer.write_unsigned_short(self.fifo_pointer_address, logical_name="fifoPointerAddress") + write_buffer.write_unsigned_short( + self.fifo_pointer_address, logical_name="fifoPointerAddress" + ) write_buffer.pop_context("ModbusPDUReadFifoQueueRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadFifoQueueRequest = self # Simple field (fifoPointerAddress) @@ -61,17 +59,17 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadFifoQueueRequest") - self.fifo_pointer_address= read_simple_field("fifoPointerAddress", read_unsigned_int) + fifo_pointer_address: int = read_buffer.read_unsigned_short( + logical_name="fifoPointerAddress", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUReadFifoQueueRequest") # Create the instance - return ModbusPDUReadFifoQueueRequestBuilder(fifo_pointer_address ) - + return ModbusPDUReadFifoQueueRequestBuilder(fifo_pointer_address) def equals(self, o: object) -> bool: if self == o: @@ -81,31 +79,34 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUReadFifoQueueRequest = ModbusPDUReadFifoQueueRequest(o) - return (self.fifo_pointer_address == that.fifo_pointer_address) and super().equals(that) and True + return ( + (self.fifo_pointer_address == that.fifo_pointer_address) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadFifoQueueRequestBuilder(ModbusPDUBuilder): - fifoPointerAddress: int - - def __post_init__(self): - pass + fifo_pointer_address: int - def build(self,) -> ModbusPDUReadFifoQueueRequest: - modbus_pdu_read_fifo_queue_request: ModbusPDUReadFifoQueueRequest = ModbusPDUReadFifoQueueRequest(self.fifo_pointer_address ) + def build( + self, + ) -> ModbusPDUReadFifoQueueRequest: + modbus_pdu_read_fifo_queue_request: ModbusPDUReadFifoQueueRequest = ( + ModbusPDUReadFifoQueueRequest(self.fifo_pointer_address) + ) return modbus_pdu_read_fifo_queue_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueResponse.py index 98ff7a17fdd..2804e1abd18 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFifoQueueResponse.py @@ -19,6 +19,8 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder @@ -27,43 +29,39 @@ from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadFifoQueueResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadFifoQueueResponse(ModbusPDU): fifo_value: List[int] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x18 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadFifoQueueResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = ((int(len(self.fifo_value))* int(2))+ int(2)) + byte_count: int = (int(len(self.fifo_value)) * int(2)) + int(2) write_buffer.write_unsigned_short(byte_count, logical_name="byteCount") # Implicit Field (fifo_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - fifo_count: int = ((int(len(self.fifo_value))* int(2))/ int(2)) + fifo_count: int = (int(len(self.fifo_value)) * int(2)) / int(2) write_buffer.write_unsigned_short(fifo_count, logical_name="fifoCount") # Array Field (fifoValue) - write_buffer.write_simple_array(self.fifo_value, write_unsigned_short, logical_name="fifoValue") + write_buffer.write_simple_array( + self.fifo_value, write_unsigned_short, logical_name="fifoValue" + ) write_buffer.pop_context("ModbusPDUReadFifoQueueResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadFifoQueueResponse = self # Implicit Field (byteCount) @@ -73,27 +71,33 @@ def get_length_in_bits(self) -> int: length_in_bits += 16 # Array field - if self.fifo_value != None: + if self.fifo_value is not None: length_in_bits += 16 * len(self.fifo_value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadFifoQueueResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_int) + byte_count: int = read_buffer.read_unsigned_short( + logical_name="byteCount", response=response + ) - fifo_count: int = read_implicit_field("fifoCount", read_unsigned_int) + fifo_count: int = read_buffer.read_unsigned_short( + logical_name="fifoCount", response=response + ) - fifo_value: List[Any] = read_buffer.read_array_field("fifoValue", read_buffer.read_unsigned_int, count=fifo_count) + fifo_value: List[Any] = read_buffer.read_array_field( + logical_name="fifoValue", + read_function=read_buffer.read_unsigned_short, + count=fifo_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadFifoQueueResponse") # Create the instance - return ModbusPDUReadFifoQueueResponseBuilder(fifo_value ) - + return ModbusPDUReadFifoQueueResponseBuilder(fifo_value) def equals(self, o: object) -> bool: if self == o: @@ -109,25 +113,24 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadFifoQueueResponseBuilder(ModbusPDUBuilder): - fifoValue: List[int] - - def __post_init__(self): - pass + fifo_value: List[int] - def build(self,) -> ModbusPDUReadFifoQueueResponse: - modbus_pdu_read_fifo_queue_response: ModbusPDUReadFifoQueueResponse = ModbusPDUReadFifoQueueResponse(self.fifo_value ) + def build( + self, + ) -> ModbusPDUReadFifoQueueResponse: + modbus_pdu_read_fifo_queue_response: ModbusPDUReadFifoQueueResponse = ( + ModbusPDUReadFifoQueueResponse(self.fifo_value) + ) return modbus_pdu_read_fifo_queue_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequest.py index 3e0a55b8bc3..160ae5c19bd 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequest.py @@ -19,35 +19,35 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder -from plc4py.protocols.modbus.readwrite.ModbusPDUReadFileRecordRequestItem import ModbusPDUReadFileRecordRequestItem +from plc4py.protocols.modbus.readwrite.ModbusPDUReadFileRecordRequestItem import ( + ModbusPDUReadFileRecordRequestItem, +) from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer from sys import getsizeof +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadFileRecordRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadFileRecordRequest(ModbusPDU): items: List[ModbusPDUReadFileRecordRequestItem] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x14 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadFileRecordRequest") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(getsizeof(self.items))) + byte_count: int = int(getsizeof(self.items)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (items) @@ -55,39 +55,41 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadFileRecordRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadFileRecordRequest = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.items != None: + if self.items is not None: for element in self.items: - length_in_bits += element.get_length_in_bits() - - + length_in_bits += element.length_in_bits() return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadFileRecordRequest") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - items: List[Any] = read_buffer.read_array_field("items", read_buffer.DataReaderComplexDefault(ModbusPDUReadFileRecordRequestItem.static_parse(read_buffer), read_buffer), length=byte_count) + items: List[Any] = read_buffer.read_array_field( + logical_name="items", + read_function=ModbusPDUReadFileRecordRequestItem.static_parse, + length=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadFileRecordRequest") # Create the instance - return ModbusPDUReadFileRecordRequestBuilder(items ) - + return ModbusPDUReadFileRecordRequestBuilder(items) def equals(self, o: object) -> bool: if self == o: @@ -103,25 +105,24 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadFileRecordRequestBuilder(ModbusPDUBuilder): items: List[ModbusPDUReadFileRecordRequestItem] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadFileRecordRequest: - modbus_pdu_read_file_record_request: ModbusPDUReadFileRecordRequest = ModbusPDUReadFileRecordRequest(self.items ) + def build( + self, + ) -> ModbusPDUReadFileRecordRequest: + modbus_pdu_read_file_record_request: ModbusPDUReadFileRecordRequest = ( + ModbusPDUReadFileRecordRequest(self.items) + ) return modbus_pdu_read_file_record_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequestItem.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequestItem.py index 0997bb356aa..1705d912a38 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequestItem.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordRequestItem.py @@ -19,46 +19,48 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadFileRecordRequestItem(PlcMessage): +class ModbusPDUReadFileRecordRequestItem: reference_type: int file_number: int record_number: int record_length: int - - def __post_init__(self): - super().__init__( ) - - - def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadFileRecordRequestItem") # Simple Field (referenceType) - write_buffer.write_unsigned_byte(self.reference_type, logical_name="referenceType") + write_buffer.write_unsigned_byte( + self.reference_type, logical_name="referenceType" + ) # Simple Field (fileNumber) write_buffer.write_unsigned_short(self.file_number, logical_name="fileNumber") # Simple Field (recordNumber) - write_buffer.write_unsigned_short(self.record_number, logical_name="recordNumber") + write_buffer.write_unsigned_short( + self.record_number, logical_name="recordNumber" + ) # Simple Field (recordLength) - write_buffer.write_unsigned_short(self.record_length, logical_name="recordLength") + write_buffer.write_unsigned_short( + self.record_length, logical_name="recordLength" + ) write_buffer.pop_context("ModbusPDUReadFileRecordRequestItem") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusPDUReadFileRecordRequestItem = self @@ -76,29 +78,37 @@ def get_length_in_bits(self) -> int: return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - return self.static_parse_context(read_buffer) - + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + return ModbusPDUReadFileRecordRequestItem.static_parse_context(read_buffer) @staticmethod def static_parse_context(read_buffer: ReadBuffer): read_buffer.push_context("ModbusPDUReadFileRecordRequestItem") - self.reference_type= read_simple_field("referenceType", read_unsigned_short) + reference_type: int = read_buffer.read_unsigned_byte( + logical_name="referenceType", bit_length=8 + ) - self.file_number= read_simple_field("fileNumber", read_unsigned_int) + file_number: int = read_buffer.read_unsigned_short( + logical_name="fileNumber", bit_length=16 + ) - self.record_number= read_simple_field("recordNumber", read_unsigned_int) + record_number: int = read_buffer.read_unsigned_short( + logical_name="recordNumber", bit_length=16 + ) - self.record_length= read_simple_field("recordLength", read_unsigned_int) + record_length: int = read_buffer.read_unsigned_short( + logical_name="recordLength", bit_length=16 + ) read_buffer.pop_context("ModbusPDUReadFileRecordRequestItem") # Create the instance - _modbus_pdu_read_file_record_request_item: ModbusPDUReadFileRecordRequestItem = ModbusPDUReadFileRecordRequestItem(reference_type, file_number, record_number, record_length ) + _modbus_pdu_read_file_record_request_item: ModbusPDUReadFileRecordRequestItem = ModbusPDUReadFileRecordRequestItem( + reference_type, file_number, record_number, record_length + ) return _modbus_pdu_read_file_record_request_item - def equals(self, o: object) -> bool: if self == o: return True @@ -107,20 +117,23 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUReadFileRecordRequestItem = ModbusPDUReadFileRecordRequestItem(o) - return (self.reference_type == that.reference_type) and (self.file_number == that.file_number) and (self.record_number == that.record_number) and (self.record_length == that.record_length) and True + return ( + (self.reference_type == that.reference_type) + and (self.file_number == that.file_number) + and (self.record_number == that.record_number) + and (self.record_length == that.record_length) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - - - - + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponse.py index ce2ce730468..9d0ba52484b 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponse.py @@ -19,35 +19,35 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder -from plc4py.protocols.modbus.readwrite.ModbusPDUReadFileRecordResponseItem import ModbusPDUReadFileRecordResponseItem +from plc4py.protocols.modbus.readwrite.ModbusPDUReadFileRecordResponseItem import ( + ModbusPDUReadFileRecordResponseItem, +) from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer from sys import getsizeof +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadFileRecordResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadFileRecordResponse(ModbusPDU): items: List[ModbusPDUReadFileRecordResponseItem] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x14 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadFileRecordResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(getsizeof(self.items))) + byte_count: int = int(getsizeof(self.items)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (items) @@ -55,39 +55,41 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadFileRecordResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadFileRecordResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.items != None: + if self.items is not None: for element in self.items: - length_in_bits += element.get_length_in_bits() - - + length_in_bits += element.length_in_bits() return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadFileRecordResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - items: List[Any] = read_buffer.read_array_field("items", read_buffer.DataReaderComplexDefault(ModbusPDUReadFileRecordResponseItem.static_parse(read_buffer), read_buffer), length=byte_count) + items: List[Any] = read_buffer.read_array_field( + logical_name="items", + read_function=ModbusPDUReadFileRecordResponseItem.static_parse, + length=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadFileRecordResponse") # Create the instance - return ModbusPDUReadFileRecordResponseBuilder(items ) - + return ModbusPDUReadFileRecordResponseBuilder(items) def equals(self, o: object) -> bool: if self == o: @@ -103,25 +105,24 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadFileRecordResponseBuilder(ModbusPDUBuilder): items: List[ModbusPDUReadFileRecordResponseItem] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadFileRecordResponse: - modbus_pdu_read_file_record_response: ModbusPDUReadFileRecordResponse = ModbusPDUReadFileRecordResponse(self.items ) + def build( + self, + ) -> ModbusPDUReadFileRecordResponse: + modbus_pdu_read_file_record_response: ModbusPDUReadFileRecordResponse = ( + ModbusPDUReadFileRecordResponse(self.items) + ) return modbus_pdu_read_file_record_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponseItem.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponseItem.py index 9e2c5898732..c30705d95c5 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponseItem.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadFileRecordResponseItem.py @@ -19,43 +19,42 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadFileRecordResponseItem(PlcMessage): +class ModbusPDUReadFileRecordResponseItem: reference_type: int data: List[int] - - def __post_init__(self): - super().__init__( ) - - - def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadFileRecordResponseItem") # Implicit Field (data_length) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - data_length: int = (int(len(self.data))+ int(1)) + data_length: int = int(len(self.data)) + int(1) write_buffer.write_unsigned_byte(data_length, logical_name="dataLength") # Simple Field (referenceType) - write_buffer.write_unsigned_byte(self.reference_type, logical_name="referenceType") + write_buffer.write_unsigned_byte( + self.reference_type, logical_name="referenceType" + ) # Array Field (data) write_buffer.write_byte_array(self.data, logical_name="data") write_buffer.pop_context("ModbusPDUReadFileRecordResponseItem") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusPDUReadFileRecordResponseItem = self @@ -66,33 +65,38 @@ def get_length_in_bits(self) -> int: length_in_bits += 8 # Array field - if self.data != None: + if self.data is not None: length_in_bits += 8 * len(self.data) - return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - return self.static_parse_context(read_buffer) - + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + return ModbusPDUReadFileRecordResponseItem.static_parse_context(read_buffer) @staticmethod def static_parse_context(read_buffer: ReadBuffer): read_buffer.push_context("ModbusPDUReadFileRecordResponseItem") - data_length: int = read_implicit_field("dataLength", read_unsigned_short) + data_length: int = read_buffer.read_unsigned_byte(logical_name="dataLength") - self.reference_type= read_simple_field("referenceType", read_unsigned_short) + reference_type: int = read_buffer.read_unsigned_byte( + logical_name="referenceType", bit_length=8 + ) - data: List[int] = read_buffer.read_byte_array("data", int(data_length- int(1))) + data: List[Any] = read_buffer.read_array_field( + logical_name="data", + read_function=read_buffer.read_byte, + count=data_length - int(1), + ) read_buffer.pop_context("ModbusPDUReadFileRecordResponseItem") # Create the instance - _modbus_pdu_read_file_record_response_item: ModbusPDUReadFileRecordResponseItem = ModbusPDUReadFileRecordResponseItem(reference_type, data ) + _modbus_pdu_read_file_record_response_item: ModbusPDUReadFileRecordResponseItem = ModbusPDUReadFileRecordResponseItem( + reference_type, data + ) return _modbus_pdu_read_file_record_response_item - def equals(self, o: object) -> bool: if self == o: return True @@ -100,21 +104,24 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadFileRecordResponseItem): return False - that: ModbusPDUReadFileRecordResponseItem = ModbusPDUReadFileRecordResponseItem(o) - return (self.reference_type == that.reference_type) and (self.data == that.data) and True + that: ModbusPDUReadFileRecordResponseItem = ModbusPDUReadFileRecordResponseItem( + o + ) + return ( + (self.reference_type == that.reference_type) + and (self.data == that.data) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - - - - + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersRequest.py index 01b52c17fb0..0b43f55eb42 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadHoldingRegistersRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadHoldingRegistersRequest(ModbusPDU): starting_address: int quantity: int # Accessors for discriminator values. @@ -35,29 +38,24 @@ class ModbusPDUReadHoldingRegistersRequest(PlcMessage,ModbusPDU): function_flag: int = 0x03 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadHoldingRegistersRequest") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") write_buffer.pop_context("ModbusPDUReadHoldingRegistersRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadHoldingRegistersRequest = self # Simple field (startingAddress) @@ -68,19 +66,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadHoldingRegistersRequest") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUReadHoldingRegistersRequest") # Create the instance - return ModbusPDUReadHoldingRegistersRequestBuilder(starting_address, quantity ) - + return ModbusPDUReadHoldingRegistersRequestBuilder(starting_address, quantity) def equals(self, o: object) -> bool: if self == o: @@ -89,33 +89,39 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadHoldingRegistersRequest): return False - that: ModbusPDUReadHoldingRegistersRequest = ModbusPDUReadHoldingRegistersRequest(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and super().equals(that) and True + that: ModbusPDUReadHoldingRegistersRequest = ( + ModbusPDUReadHoldingRegistersRequest(o) + ) + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadHoldingRegistersRequestBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadHoldingRegistersRequest: - modbus_pdu_read_holding_registers_request: ModbusPDUReadHoldingRegistersRequest = ModbusPDUReadHoldingRegistersRequest(self.starting_address, self.quantity ) + def build( + self, + ) -> ModbusPDUReadHoldingRegistersRequest: + modbus_pdu_read_holding_registers_request: ModbusPDUReadHoldingRegistersRequest = ModbusPDUReadHoldingRegistersRequest( + self.starting_address, self.quantity + ) return modbus_pdu_read_holding_registers_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersResponse.py index dd2bf21ec66..d8d2c386157 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadHoldingRegistersResponse.py @@ -19,33 +19,31 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadHoldingRegistersResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadHoldingRegistersResponse(ModbusPDU): value: List[int] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x03 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadHoldingRegistersResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -53,37 +51,40 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadHoldingRegistersResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadHoldingRegistersResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadHoldingRegistersResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadHoldingRegistersResponse") # Create the instance - return ModbusPDUReadHoldingRegistersResponseBuilder(value ) - + return ModbusPDUReadHoldingRegistersResponseBuilder(value) def equals(self, o: object) -> bool: if self == o: @@ -92,32 +93,33 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadHoldingRegistersResponse): return False - that: ModbusPDUReadHoldingRegistersResponse = ModbusPDUReadHoldingRegistersResponse(o) + that: ModbusPDUReadHoldingRegistersResponse = ( + ModbusPDUReadHoldingRegistersResponse(o) + ) return (self.value == that.value) and super().equals(that) and True def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadHoldingRegistersResponseBuilder(ModbusPDUBuilder): value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadHoldingRegistersResponse: - modbus_pdu_read_holding_registers_response: ModbusPDUReadHoldingRegistersResponse = ModbusPDUReadHoldingRegistersResponse(self.value ) + def build( + self, + ) -> ModbusPDUReadHoldingRegistersResponse: + modbus_pdu_read_holding_registers_response: ModbusPDUReadHoldingRegistersResponse = ModbusPDUReadHoldingRegistersResponse( + self.value + ) return modbus_pdu_read_holding_registers_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersRequest.py index a8d0bc40d71..87beea34923 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReadInputRegistersRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadInputRegistersRequest(ModbusPDU): starting_address: int quantity: int # Accessors for discriminator values. @@ -35,29 +38,24 @@ class ModbusPDUReadInputRegistersRequest(PlcMessage,ModbusPDU): function_flag: int = 0x04 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadInputRegistersRequest") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") write_buffer.pop_context("ModbusPDUReadInputRegistersRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadInputRegistersRequest = self # Simple field (startingAddress) @@ -68,19 +66,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadInputRegistersRequest") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUReadInputRegistersRequest") # Create the instance - return ModbusPDUReadInputRegistersRequestBuilder(starting_address, quantity ) - + return ModbusPDUReadInputRegistersRequestBuilder(starting_address, quantity) def equals(self, o: object) -> bool: if self == o: @@ -90,32 +90,36 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUReadInputRegistersRequest = ModbusPDUReadInputRegistersRequest(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and super().equals(that) and True + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadInputRegistersRequestBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadInputRegistersRequest: - modbus_pdu_read_input_registers_request: ModbusPDUReadInputRegistersRequest = ModbusPDUReadInputRegistersRequest(self.starting_address, self.quantity ) + def build( + self, + ) -> ModbusPDUReadInputRegistersRequest: + modbus_pdu_read_input_registers_request: ModbusPDUReadInputRegistersRequest = ( + ModbusPDUReadInputRegistersRequest(self.starting_address, self.quantity) + ) return modbus_pdu_read_input_registers_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersResponse.py index 9fef623746d..5aa5e0cde61 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadInputRegistersResponse.py @@ -19,33 +19,31 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadInputRegistersResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadInputRegistersResponse(ModbusPDU): value: List[int] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x04 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadInputRegistersResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -53,37 +51,40 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadInputRegistersResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadInputRegistersResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadInputRegistersResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadInputRegistersResponse") # Create the instance - return ModbusPDUReadInputRegistersResponseBuilder(value ) - + return ModbusPDUReadInputRegistersResponseBuilder(value) def equals(self, o: object) -> bool: if self == o: @@ -92,32 +93,33 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadInputRegistersResponse): return False - that: ModbusPDUReadInputRegistersResponse = ModbusPDUReadInputRegistersResponse(o) + that: ModbusPDUReadInputRegistersResponse = ModbusPDUReadInputRegistersResponse( + o + ) return (self.value == that.value) and super().equals(that) and True def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadInputRegistersResponseBuilder(ModbusPDUBuilder): value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadInputRegistersResponse: - modbus_pdu_read_input_registers_response: ModbusPDUReadInputRegistersResponse = ModbusPDUReadInputRegistersResponse(self.value ) + def build( + self, + ) -> ModbusPDUReadInputRegistersResponse: + modbus_pdu_read_input_registers_response: ModbusPDUReadInputRegistersResponse = ModbusPDUReadInputRegistersResponse( + self.value + ) return modbus_pdu_read_input_registers_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersRequest.py index d0adbca2051..5a48ef69240 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersRequest.py @@ -19,16 +19,20 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadWriteMultipleHoldingRegistersRequest(PlcMessage,ModbusPDU): +class ModbusPDUReadWriteMultipleHoldingRegistersRequest(ModbusPDU): read_starting_address: int read_quantity: int write_starting_address: int @@ -39,29 +43,31 @@ class ModbusPDUReadWriteMultipleHoldingRegistersRequest(PlcMessage,ModbusPDU): function_flag: int = 0x17 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadWriteMultipleHoldingRegistersRequest") # Simple Field (readStartingAddress) - write_buffer.write_unsigned_short(self.read_starting_address, logical_name="readStartingAddress") + write_buffer.write_unsigned_short( + self.read_starting_address, logical_name="readStartingAddress" + ) # Simple Field (readQuantity) - write_buffer.write_unsigned_short(self.read_quantity, logical_name="readQuantity") + write_buffer.write_unsigned_short( + self.read_quantity, logical_name="readQuantity" + ) # Simple Field (writeStartingAddress) - write_buffer.write_unsigned_short(self.write_starting_address, logical_name="writeStartingAddress") + write_buffer.write_unsigned_short( + self.write_starting_address, logical_name="writeStartingAddress" + ) # Simple Field (writeQuantity) - write_buffer.write_unsigned_short(self.write_quantity, logical_name="writeQuantity") + write_buffer.write_unsigned_short( + self.write_quantity, logical_name="writeQuantity" + ) # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -69,12 +75,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadWriteMultipleHoldingRegistersRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadWriteMultipleHoldingRegistersRequest = self # Simple field (readStartingAddress) @@ -93,33 +98,51 @@ def get_length_in_bits(self) -> int: length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadWriteMultipleHoldingRegistersRequest") - self.read_starting_address= read_simple_field("readStartingAddress", read_unsigned_int) + read_starting_address: int = read_buffer.read_unsigned_short( + logical_name="readStartingAddress", bit_length=16, response=response + ) - self.read_quantity= read_simple_field("readQuantity", read_unsigned_int) + read_quantity: int = read_buffer.read_unsigned_short( + logical_name="readQuantity", bit_length=16, response=response + ) - self.write_starting_address= read_simple_field("writeStartingAddress", read_unsigned_int) + write_starting_address: int = read_buffer.read_unsigned_short( + logical_name="writeStartingAddress", bit_length=16, response=response + ) - self.write_quantity= read_simple_field("writeQuantity", read_unsigned_int) + write_quantity: int = read_buffer.read_unsigned_short( + logical_name="writeQuantity", bit_length=16, response=response + ) - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadWriteMultipleHoldingRegistersRequest") # Create the instance - return ModbusPDUReadWriteMultipleHoldingRegistersRequestBuilder(read_starting_address, read_quantity, write_starting_address, write_quantity, value ) - + return ModbusPDUReadWriteMultipleHoldingRegistersRequestBuilder( + read_starting_address, + read_quantity, + write_starting_address, + write_quantity, + value, + ) def equals(self, o: object) -> bool: if self == o: @@ -128,36 +151,49 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadWriteMultipleHoldingRegistersRequest): return False - that: ModbusPDUReadWriteMultipleHoldingRegistersRequest = ModbusPDUReadWriteMultipleHoldingRegistersRequest(o) - return (self.read_starting_address == that.read_starting_address) and (self.read_quantity == that.read_quantity) and (self.write_starting_address == that.write_starting_address) and (self.write_quantity == that.write_quantity) and (self.value == that.value) and super().equals(that) and True + that: ModbusPDUReadWriteMultipleHoldingRegistersRequest = ( + ModbusPDUReadWriteMultipleHoldingRegistersRequest(o) + ) + return ( + (self.read_starting_address == that.read_starting_address) + and (self.read_quantity == that.read_quantity) + and (self.write_starting_address == that.write_starting_address) + and (self.write_quantity == that.write_quantity) + and (self.value == that.value) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadWriteMultipleHoldingRegistersRequestBuilder(ModbusPDUBuilder): - readStartingAddress: int - readQuantity: int - writeStartingAddress: int - writeQuantity: int + read_starting_address: int + read_quantity: int + write_starting_address: int + write_quantity: int value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadWriteMultipleHoldingRegistersRequest: - modbus_pdu_read_write_multiple_holding_registers_request: ModbusPDUReadWriteMultipleHoldingRegistersRequest = ModbusPDUReadWriteMultipleHoldingRegistersRequest(self.read_starting_address, self.read_quantity, self.write_starting_address, self.write_quantity, self.value ) + def build( + self, + ) -> ModbusPDUReadWriteMultipleHoldingRegistersRequest: + modbus_pdu_read_write_multiple_holding_registers_request: ModbusPDUReadWriteMultipleHoldingRegistersRequest = ModbusPDUReadWriteMultipleHoldingRegistersRequest( + self.read_starting_address, + self.read_quantity, + self.write_starting_address, + self.write_quantity, + self.value, + ) return modbus_pdu_read_write_multiple_holding_registers_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersResponse.py index 22ed9dab1ba..8937dc1609a 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReadWriteMultipleHoldingRegistersResponse.py @@ -19,33 +19,31 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReadWriteMultipleHoldingRegistersResponse(PlcMessage,ModbusPDU): +class ModbusPDUReadWriteMultipleHoldingRegistersResponse(ModbusPDU): value: List[int] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x17 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReadWriteMultipleHoldingRegistersResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -53,37 +51,40 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReadWriteMultipleHoldingRegistersResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReadWriteMultipleHoldingRegistersResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReadWriteMultipleHoldingRegistersResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReadWriteMultipleHoldingRegistersResponse") # Create the instance - return ModbusPDUReadWriteMultipleHoldingRegistersResponseBuilder(value ) - + return ModbusPDUReadWriteMultipleHoldingRegistersResponseBuilder(value) def equals(self, o: object) -> bool: if self == o: @@ -92,32 +93,33 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUReadWriteMultipleHoldingRegistersResponse): return False - that: ModbusPDUReadWriteMultipleHoldingRegistersResponse = ModbusPDUReadWriteMultipleHoldingRegistersResponse(o) + that: ModbusPDUReadWriteMultipleHoldingRegistersResponse = ( + ModbusPDUReadWriteMultipleHoldingRegistersResponse(o) + ) return (self.value == that.value) and super().equals(that) and True def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReadWriteMultipleHoldingRegistersResponseBuilder(ModbusPDUBuilder): value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReadWriteMultipleHoldingRegistersResponse: - modbus_pdu_read_write_multiple_holding_registers_response: ModbusPDUReadWriteMultipleHoldingRegistersResponse = ModbusPDUReadWriteMultipleHoldingRegistersResponse(self.value ) + def build( + self, + ) -> ModbusPDUReadWriteMultipleHoldingRegistersResponse: + modbus_pdu_read_write_multiple_holding_registers_response: ModbusPDUReadWriteMultipleHoldingRegistersResponse = ModbusPDUReadWriteMultipleHoldingRegistersResponse( + self.value + ) return modbus_pdu_read_write_multiple_holding_registers_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdRequest.py index c9e346bacf9..14607d0227a 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdRequest.py @@ -19,42 +19,37 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUReportServerIdRequest(PlcMessage,ModbusPDU): +class ModbusPDUReportServerIdRequest(ModbusPDU): # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x11 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReportServerIdRequest") write_buffer.pop_context("ModbusPDUReportServerIdRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReportServerIdRequest = self return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReportServerIdRequest") @@ -63,7 +58,6 @@ def static_parse_builder(read_buffer: ReadBuffer, response: bool): # Create the instance return ModbusPDUReportServerIdRequestBuilder() - def equals(self, o: object) -> bool: if self == o: return True @@ -78,24 +72,22 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReportServerIdRequestBuilder(ModbusPDUBuilder): - - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReportServerIdRequest: - modbus_pdu_report_server_id_request: ModbusPDUReportServerIdRequest = ModbusPDUReportServerIdRequest() + def build( + self, + ) -> ModbusPDUReportServerIdRequest: + modbus_pdu_report_server_id_request: ModbusPDUReportServerIdRequest = ( + ModbusPDUReportServerIdRequest() + ) return modbus_pdu_report_server_id_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdResponse.py index 6f6659bbdca..7900a0efef5 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUReportServerIdResponse.py @@ -19,33 +19,31 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUReportServerIdResponse(PlcMessage,ModbusPDU): +class ModbusPDUReportServerIdResponse(ModbusPDU): value: List[int] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x11 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUReportServerIdResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -53,37 +51,40 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUReportServerIdResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUReportServerIdResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUReportServerIdResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUReportServerIdResponse") # Create the instance - return ModbusPDUReportServerIdResponseBuilder(value ) - + return ModbusPDUReportServerIdResponseBuilder(value) def equals(self, o: object) -> bool: if self == o: @@ -99,25 +100,24 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUReportServerIdResponseBuilder(ModbusPDUBuilder): value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUReportServerIdResponse: - modbus_pdu_report_server_id_response: ModbusPDUReportServerIdResponse = ModbusPDUReportServerIdResponse(self.value ) + def build( + self, + ) -> ModbusPDUReportServerIdResponse: + modbus_pdu_report_server_id_response: ModbusPDUReportServerIdResponse = ( + ModbusPDUReportServerIdResponse(self.value) + ) return modbus_pdu_report_server_id_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequest.py index 7506391cafc..64ae6562517 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequest.py @@ -19,35 +19,35 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder -from plc4py.protocols.modbus.readwrite.ModbusPDUWriteFileRecordRequestItem import ModbusPDUWriteFileRecordRequestItem +from plc4py.protocols.modbus.readwrite.ModbusPDUWriteFileRecordRequestItem import ( + ModbusPDUWriteFileRecordRequestItem, +) from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer from sys import getsizeof +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUWriteFileRecordRequest(PlcMessage,ModbusPDU): +class ModbusPDUWriteFileRecordRequest(ModbusPDU): items: List[ModbusPDUWriteFileRecordRequestItem] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x15 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteFileRecordRequest") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(getsizeof(self.items))) + byte_count: int = int(getsizeof(self.items)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (items) @@ -55,39 +55,41 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteFileRecordRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteFileRecordRequest = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.items != None: + if self.items is not None: for element in self.items: - length_in_bits += element.get_length_in_bits() - - + length_in_bits += element.length_in_bits() return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteFileRecordRequest") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - items: List[Any] = read_buffer.read_array_field("items", read_buffer.DataReaderComplexDefault(ModbusPDUWriteFileRecordRequestItem.static_parse(read_buffer), read_buffer), length=byte_count) + items: List[Any] = read_buffer.read_array_field( + logical_name="items", + read_function=ModbusPDUWriteFileRecordRequestItem.static_parse, + length=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUWriteFileRecordRequest") # Create the instance - return ModbusPDUWriteFileRecordRequestBuilder(items ) - + return ModbusPDUWriteFileRecordRequestBuilder(items) def equals(self, o: object) -> bool: if self == o: @@ -103,25 +105,24 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUWriteFileRecordRequestBuilder(ModbusPDUBuilder): items: List[ModbusPDUWriteFileRecordRequestItem] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteFileRecordRequest: - modbus_pdu_write_file_record_request: ModbusPDUWriteFileRecordRequest = ModbusPDUWriteFileRecordRequest(self.items ) + def build( + self, + ) -> ModbusPDUWriteFileRecordRequest: + modbus_pdu_write_file_record_request: ModbusPDUWriteFileRecordRequest = ( + ModbusPDUWriteFileRecordRequest(self.items) + ) return modbus_pdu_write_file_record_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequestItem.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequestItem.py index 905590c0a42..1d808a451a2 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequestItem.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordRequestItem.py @@ -19,39 +19,41 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUWriteFileRecordRequestItem(PlcMessage): +class ModbusPDUWriteFileRecordRequestItem: reference_type: int file_number: int record_number: int record_data: List[int] - - def __post_init__(self): - super().__init__( ) - - - def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteFileRecordRequestItem") # Simple Field (referenceType) - write_buffer.write_unsigned_byte(self.reference_type, logical_name="referenceType") + write_buffer.write_unsigned_byte( + self.reference_type, logical_name="referenceType" + ) # Simple Field (fileNumber) write_buffer.write_unsigned_short(self.file_number, logical_name="fileNumber") # Simple Field (recordNumber) - write_buffer.write_unsigned_short(self.record_number, logical_name="recordNumber") + write_buffer.write_unsigned_short( + self.record_number, logical_name="recordNumber" + ) # Implicit Field (record_length) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - record_length: int = (int(len(self.record_data))/ int(2)) + record_length: int = int(len(self.record_data)) / int(2) write_buffer.write_unsigned_short(record_length, logical_name="recordLength") # Array Field (recordData) @@ -59,11 +61,10 @@ def serialize(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteFileRecordRequestItem") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusPDUWriteFileRecordRequestItem = self @@ -80,37 +81,48 @@ def get_length_in_bits(self) -> int: length_in_bits += 16 # Array field - if self.record_data != None: + if self.record_data is not None: length_in_bits += 8 * len(self.record_data) - return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - return self.static_parse_context(read_buffer) - + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + return ModbusPDUWriteFileRecordRequestItem.static_parse_context(read_buffer) @staticmethod def static_parse_context(read_buffer: ReadBuffer): read_buffer.push_context("ModbusPDUWriteFileRecordRequestItem") - self.reference_type= read_simple_field("referenceType", read_unsigned_short) + reference_type: int = read_buffer.read_unsigned_byte( + logical_name="referenceType", bit_length=8 + ) - self.file_number= read_simple_field("fileNumber", read_unsigned_int) + file_number: int = read_buffer.read_unsigned_short( + logical_name="fileNumber", bit_length=16 + ) - self.record_number= read_simple_field("recordNumber", read_unsigned_int) + record_number: int = read_buffer.read_unsigned_short( + logical_name="recordNumber", bit_length=16 + ) - record_length: int = read_implicit_field("recordLength", read_unsigned_int) + record_length: int = read_buffer.read_unsigned_short( + logical_name="recordLength" + ) - record_data: List[int] = read_buffer.read_byte_array("recordData", int(record_length* int(2))) + record_data: List[Any] = read_buffer.read_array_field( + logical_name="recordData", + read_function=read_buffer.read_byte, + count=record_length * int(2), + ) read_buffer.pop_context("ModbusPDUWriteFileRecordRequestItem") # Create the instance - _modbus_pdu_write_file_record_request_item: ModbusPDUWriteFileRecordRequestItem = ModbusPDUWriteFileRecordRequestItem(reference_type, file_number, record_number, record_data ) + _modbus_pdu_write_file_record_request_item: ModbusPDUWriteFileRecordRequestItem = ModbusPDUWriteFileRecordRequestItem( + reference_type, file_number, record_number, record_data + ) return _modbus_pdu_write_file_record_request_item - def equals(self, o: object) -> bool: if self == o: return True @@ -118,21 +130,26 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUWriteFileRecordRequestItem): return False - that: ModbusPDUWriteFileRecordRequestItem = ModbusPDUWriteFileRecordRequestItem(o) - return (self.reference_type == that.reference_type) and (self.file_number == that.file_number) and (self.record_number == that.record_number) and (self.record_data == that.record_data) and True + that: ModbusPDUWriteFileRecordRequestItem = ModbusPDUWriteFileRecordRequestItem( + o + ) + return ( + (self.reference_type == that.reference_type) + and (self.file_number == that.file_number) + and (self.record_number == that.record_number) + and (self.record_data == that.record_data) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - - - - + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponse.py index 54cd49b92cc..0ca10c3b7eb 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponse.py @@ -19,35 +19,35 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder -from plc4py.protocols.modbus.readwrite.ModbusPDUWriteFileRecordResponseItem import ModbusPDUWriteFileRecordResponseItem +from plc4py.protocols.modbus.readwrite.ModbusPDUWriteFileRecordResponseItem import ( + ModbusPDUWriteFileRecordResponseItem, +) from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer from sys import getsizeof +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUWriteFileRecordResponse(PlcMessage,ModbusPDU): +class ModbusPDUWriteFileRecordResponse(ModbusPDU): items: List[ModbusPDUWriteFileRecordResponseItem] # Accessors for discriminator values. error_flag: bool = False function_flag: int = 0x15 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteFileRecordResponse") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(getsizeof(self.items))) + byte_count: int = int(getsizeof(self.items)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (items) @@ -55,39 +55,41 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteFileRecordResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteFileRecordResponse = self # Implicit Field (byteCount) length_in_bits += 8 # Array field - if self.items != None: + if self.items is not None: for element in self.items: - length_in_bits += element.get_length_in_bits() - - + length_in_bits += element.length_in_bits() return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteFileRecordResponse") - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - items: List[Any] = read_buffer.read_array_field("items", read_buffer.DataReaderComplexDefault(ModbusPDUWriteFileRecordResponseItem.static_parse(read_buffer), read_buffer), length=byte_count) + items: List[Any] = read_buffer.read_array_field( + logical_name="items", + read_function=ModbusPDUWriteFileRecordResponseItem.static_parse, + length=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUWriteFileRecordResponse") # Create the instance - return ModbusPDUWriteFileRecordResponseBuilder(items ) - + return ModbusPDUWriteFileRecordResponseBuilder(items) def equals(self, o: object) -> bool: if self == o: @@ -103,25 +105,24 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUWriteFileRecordResponseBuilder(ModbusPDUBuilder): items: List[ModbusPDUWriteFileRecordResponseItem] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteFileRecordResponse: - modbus_pdu_write_file_record_response: ModbusPDUWriteFileRecordResponse = ModbusPDUWriteFileRecordResponse(self.items ) + def build( + self, + ) -> ModbusPDUWriteFileRecordResponse: + modbus_pdu_write_file_record_response: ModbusPDUWriteFileRecordResponse = ( + ModbusPDUWriteFileRecordResponse(self.items) + ) return modbus_pdu_write_file_record_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponseItem.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponseItem.py index 00aca97b37e..023a53a2506 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponseItem.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteFileRecordResponseItem.py @@ -19,39 +19,41 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUWriteFileRecordResponseItem(PlcMessage): +class ModbusPDUWriteFileRecordResponseItem: reference_type: int file_number: int record_number: int record_data: List[int] - - def __post_init__(self): - super().__init__( ) - - - def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteFileRecordResponseItem") # Simple Field (referenceType) - write_buffer.write_unsigned_byte(self.reference_type, logical_name="referenceType") + write_buffer.write_unsigned_byte( + self.reference_type, logical_name="referenceType" + ) # Simple Field (fileNumber) write_buffer.write_unsigned_short(self.file_number, logical_name="fileNumber") # Simple Field (recordNumber) - write_buffer.write_unsigned_short(self.record_number, logical_name="recordNumber") + write_buffer.write_unsigned_short( + self.record_number, logical_name="recordNumber" + ) # Implicit Field (record_length) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - record_length: int = (int(len(self.record_data))/ int(2)) + record_length: int = int(len(self.record_data)) / int(2) write_buffer.write_unsigned_short(record_length, logical_name="recordLength") # Array Field (recordData) @@ -59,11 +61,10 @@ def serialize(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteFileRecordResponseItem") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: ModbusPDUWriteFileRecordResponseItem = self @@ -80,37 +81,48 @@ def get_length_in_bits(self) -> int: length_in_bits += 16 # Array field - if self.record_data != None: + if self.record_data is not None: length_in_bits += 8 * len(self.record_data) - return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - return self.static_parse_context(read_buffer) - + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + return ModbusPDUWriteFileRecordResponseItem.static_parse_context(read_buffer) @staticmethod def static_parse_context(read_buffer: ReadBuffer): read_buffer.push_context("ModbusPDUWriteFileRecordResponseItem") - self.reference_type= read_simple_field("referenceType", read_unsigned_short) + reference_type: int = read_buffer.read_unsigned_byte( + logical_name="referenceType", bit_length=8 + ) - self.file_number= read_simple_field("fileNumber", read_unsigned_int) + file_number: int = read_buffer.read_unsigned_short( + logical_name="fileNumber", bit_length=16 + ) - self.record_number= read_simple_field("recordNumber", read_unsigned_int) + record_number: int = read_buffer.read_unsigned_short( + logical_name="recordNumber", bit_length=16 + ) - record_length: int = read_implicit_field("recordLength", read_unsigned_int) + record_length: int = read_buffer.read_unsigned_short( + logical_name="recordLength" + ) - record_data: List[int] = read_buffer.read_byte_array("recordData", int(record_length)) + record_data: List[Any] = read_buffer.read_array_field( + logical_name="recordData", + read_function=read_buffer.read_byte, + count=record_length, + ) read_buffer.pop_context("ModbusPDUWriteFileRecordResponseItem") # Create the instance - _modbus_pdu_write_file_record_response_item: ModbusPDUWriteFileRecordResponseItem = ModbusPDUWriteFileRecordResponseItem(reference_type, file_number, record_number, record_data ) + _modbus_pdu_write_file_record_response_item: ModbusPDUWriteFileRecordResponseItem = ModbusPDUWriteFileRecordResponseItem( + reference_type, file_number, record_number, record_data + ) return _modbus_pdu_write_file_record_response_item - def equals(self, o: object) -> bool: if self == o: return True @@ -118,21 +130,26 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUWriteFileRecordResponseItem): return False - that: ModbusPDUWriteFileRecordResponseItem = ModbusPDUWriteFileRecordResponseItem(o) - return (self.reference_type == that.reference_type) and (self.file_number == that.file_number) and (self.record_number == that.record_number) and (self.record_data == that.record_data) and True + that: ModbusPDUWriteFileRecordResponseItem = ( + ModbusPDUWriteFileRecordResponseItem(o) + ) + return ( + (self.reference_type == that.reference_type) + and (self.file_number == that.file_number) + and (self.record_number == that.record_number) + and (self.record_data == that.record_data) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - - - - + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsRequest.py index e0e9a007296..c02aaac09ee 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsRequest.py @@ -19,16 +19,20 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUWriteMultipleCoilsRequest(PlcMessage,ModbusPDU): +class ModbusPDUWriteMultipleCoilsRequest(ModbusPDU): starting_address: int quantity: int value: List[int] @@ -37,23 +41,19 @@ class ModbusPDUWriteMultipleCoilsRequest(PlcMessage,ModbusPDU): function_flag: int = 0x0F response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteMultipleCoilsRequest") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -61,12 +61,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteMultipleCoilsRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteMultipleCoilsRequest = self # Simple field (startingAddress) @@ -79,29 +78,39 @@ def get_length_in_bits(self) -> int: length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteMultipleCoilsRequest") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUWriteMultipleCoilsRequest") # Create the instance - return ModbusPDUWriteMultipleCoilsRequestBuilder(starting_address, quantity, value ) - + return ModbusPDUWriteMultipleCoilsRequestBuilder( + starting_address, quantity, value + ) def equals(self, o: object) -> bool: if self == o: @@ -111,33 +120,40 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUWriteMultipleCoilsRequest = ModbusPDUWriteMultipleCoilsRequest(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and (self.value == that.value) and super().equals(that) and True + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and (self.value == that.value) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUWriteMultipleCoilsRequestBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteMultipleCoilsRequest: - modbus_pdu_write_multiple_coils_request: ModbusPDUWriteMultipleCoilsRequest = ModbusPDUWriteMultipleCoilsRequest(self.starting_address, self.quantity, self.value ) + def build( + self, + ) -> ModbusPDUWriteMultipleCoilsRequest: + modbus_pdu_write_multiple_coils_request: ModbusPDUWriteMultipleCoilsRequest = ( + ModbusPDUWriteMultipleCoilsRequest( + self.starting_address, self.quantity, self.value + ) + ) return modbus_pdu_write_multiple_coils_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsResponse.py index 0206cd8fe08..8dd285aeb85 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleCoilsResponse.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUWriteMultipleCoilsResponse(PlcMessage,ModbusPDU): +class ModbusPDUWriteMultipleCoilsResponse(ModbusPDU): starting_address: int quantity: int # Accessors for discriminator values. @@ -35,29 +38,24 @@ class ModbusPDUWriteMultipleCoilsResponse(PlcMessage,ModbusPDU): function_flag: int = 0x0F response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteMultipleCoilsResponse") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") write_buffer.pop_context("ModbusPDUWriteMultipleCoilsResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteMultipleCoilsResponse = self # Simple field (startingAddress) @@ -68,19 +66,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteMultipleCoilsResponse") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUWriteMultipleCoilsResponse") # Create the instance - return ModbusPDUWriteMultipleCoilsResponseBuilder(starting_address, quantity ) - + return ModbusPDUWriteMultipleCoilsResponseBuilder(starting_address, quantity) def equals(self, o: object) -> bool: if self == o: @@ -89,33 +89,39 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUWriteMultipleCoilsResponse): return False - that: ModbusPDUWriteMultipleCoilsResponse = ModbusPDUWriteMultipleCoilsResponse(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and super().equals(that) and True + that: ModbusPDUWriteMultipleCoilsResponse = ModbusPDUWriteMultipleCoilsResponse( + o + ) + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUWriteMultipleCoilsResponseBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteMultipleCoilsResponse: - modbus_pdu_write_multiple_coils_response: ModbusPDUWriteMultipleCoilsResponse = ModbusPDUWriteMultipleCoilsResponse(self.starting_address, self.quantity ) + def build( + self, + ) -> ModbusPDUWriteMultipleCoilsResponse: + modbus_pdu_write_multiple_coils_response: ModbusPDUWriteMultipleCoilsResponse = ModbusPDUWriteMultipleCoilsResponse( + self.starting_address, self.quantity + ) return modbus_pdu_write_multiple_coils_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersRequest.py index 3024d1761f7..a04a760c520 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersRequest.py @@ -19,16 +19,20 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from typing import Any from typing import List import math - + + @dataclass -class ModbusPDUWriteMultipleHoldingRegistersRequest(PlcMessage,ModbusPDU): +class ModbusPDUWriteMultipleHoldingRegistersRequest(ModbusPDU): starting_address: int quantity: int value: List[int] @@ -37,23 +41,19 @@ class ModbusPDUWriteMultipleHoldingRegistersRequest(PlcMessage,ModbusPDU): function_flag: int = 0x10 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteMultipleHoldingRegistersRequest") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") # Implicit Field (byte_count) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - byte_count: int = (int(len(self.value))) + byte_count: int = int(len(self.value)) write_buffer.write_unsigned_byte(byte_count, logical_name="byteCount") # Array Field (value) @@ -61,12 +61,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteMultipleHoldingRegistersRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteMultipleHoldingRegistersRequest = self # Simple field (startingAddress) @@ -79,29 +78,39 @@ def get_length_in_bits(self) -> int: length_in_bits += 8 # Array field - if self.value != None: + if self.value is not None: length_in_bits += 8 * len(self.value) - return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteMultipleHoldingRegistersRequest") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) - byte_count: int = read_implicit_field("byteCount", read_unsigned_short) + byte_count: int = read_buffer.read_unsigned_byte( + logical_name="byteCount", response=response + ) - value: List[int] = read_buffer.read_byte_array("value", int(byte_count)) + value: List[Any] = read_buffer.read_array_field( + logical_name="value", + read_function=read_buffer.read_byte, + count=byte_count, + response=response, + ) read_buffer.pop_context("ModbusPDUWriteMultipleHoldingRegistersRequest") # Create the instance - return ModbusPDUWriteMultipleHoldingRegistersRequestBuilder(starting_address, quantity, value ) - + return ModbusPDUWriteMultipleHoldingRegistersRequestBuilder( + starting_address, quantity, value + ) def equals(self, o: object) -> bool: if self == o: @@ -110,34 +119,41 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUWriteMultipleHoldingRegistersRequest): return False - that: ModbusPDUWriteMultipleHoldingRegistersRequest = ModbusPDUWriteMultipleHoldingRegistersRequest(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and (self.value == that.value) and super().equals(that) and True + that: ModbusPDUWriteMultipleHoldingRegistersRequest = ( + ModbusPDUWriteMultipleHoldingRegistersRequest(o) + ) + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and (self.value == that.value) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUWriteMultipleHoldingRegistersRequestBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int value: List[int] - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteMultipleHoldingRegistersRequest: - modbus_pdu_write_multiple_holding_registers_request: ModbusPDUWriteMultipleHoldingRegistersRequest = ModbusPDUWriteMultipleHoldingRegistersRequest(self.starting_address, self.quantity, self.value ) + def build( + self, + ) -> ModbusPDUWriteMultipleHoldingRegistersRequest: + modbus_pdu_write_multiple_holding_registers_request: ModbusPDUWriteMultipleHoldingRegistersRequest = ModbusPDUWriteMultipleHoldingRegistersRequest( + self.starting_address, self.quantity, self.value + ) return modbus_pdu_write_multiple_holding_registers_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersResponse.py index c877e114af2..6bd8f4072d3 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteMultipleHoldingRegistersResponse.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUWriteMultipleHoldingRegistersResponse(PlcMessage,ModbusPDU): +class ModbusPDUWriteMultipleHoldingRegistersResponse(ModbusPDU): starting_address: int quantity: int # Accessors for discriminator values. @@ -35,29 +38,24 @@ class ModbusPDUWriteMultipleHoldingRegistersResponse(PlcMessage,ModbusPDU): function_flag: int = 0x10 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteMultipleHoldingRegistersResponse") # Simple Field (startingAddress) - write_buffer.write_unsigned_short(self.starting_address, logical_name="startingAddress") + write_buffer.write_unsigned_short( + self.starting_address, logical_name="startingAddress" + ) # Simple Field (quantity) write_buffer.write_unsigned_short(self.quantity, logical_name="quantity") write_buffer.pop_context("ModbusPDUWriteMultipleHoldingRegistersResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteMultipleHoldingRegistersResponse = self # Simple field (startingAddress) @@ -68,19 +66,23 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteMultipleHoldingRegistersResponse") - self.starting_address= read_simple_field("startingAddress", read_unsigned_int) + starting_address: int = read_buffer.read_unsigned_short( + logical_name="startingAddress", bit_length=16, response=response + ) - self.quantity= read_simple_field("quantity", read_unsigned_int) + quantity: int = read_buffer.read_unsigned_short( + logical_name="quantity", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUWriteMultipleHoldingRegistersResponse") # Create the instance - return ModbusPDUWriteMultipleHoldingRegistersResponseBuilder(starting_address, quantity ) - + return ModbusPDUWriteMultipleHoldingRegistersResponseBuilder( + starting_address, quantity + ) def equals(self, o: object) -> bool: if self == o: @@ -89,33 +91,39 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUWriteMultipleHoldingRegistersResponse): return False - that: ModbusPDUWriteMultipleHoldingRegistersResponse = ModbusPDUWriteMultipleHoldingRegistersResponse(o) - return (self.starting_address == that.starting_address) and (self.quantity == that.quantity) and super().equals(that) and True + that: ModbusPDUWriteMultipleHoldingRegistersResponse = ( + ModbusPDUWriteMultipleHoldingRegistersResponse(o) + ) + return ( + (self.starting_address == that.starting_address) + and (self.quantity == that.quantity) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusPDUWriteMultipleHoldingRegistersResponseBuilder(ModbusPDUBuilder): - startingAddress: int + starting_address: int quantity: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteMultipleHoldingRegistersResponse: - modbus_pdu_write_multiple_holding_registers_response: ModbusPDUWriteMultipleHoldingRegistersResponse = ModbusPDUWriteMultipleHoldingRegistersResponse(self.starting_address, self.quantity ) + def build( + self, + ) -> ModbusPDUWriteMultipleHoldingRegistersResponse: + modbus_pdu_write_multiple_holding_registers_response: ModbusPDUWriteMultipleHoldingRegistersResponse = ModbusPDUWriteMultipleHoldingRegistersResponse( + self.starting_address, self.quantity + ) return modbus_pdu_write_multiple_holding_registers_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilRequest.py index d2b59516643..5921fa6b1d9 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUWriteSingleCoilRequest(PlcMessage,ModbusPDU): +class ModbusPDUWriteSingleCoilRequest(ModbusPDU): address: int value: int # Accessors for discriminator values. @@ -35,12 +38,6 @@ class ModbusPDUWriteSingleCoilRequest(PlcMessage,ModbusPDU): function_flag: int = 0x05 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteSingleCoilRequest") @@ -52,12 +49,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteSingleCoilRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteSingleCoilRequest = self # Simple field (address) @@ -68,19 +64,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteSingleCoilRequest") - self.address= read_simple_field("address", read_unsigned_int) + address: int = read_buffer.read_unsigned_short( + logical_name="address", bit_length=16, response=response + ) - self.value= read_simple_field("value", read_unsigned_int) + value: int = read_buffer.read_unsigned_short( + logical_name="value", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUWriteSingleCoilRequest") # Create the instance - return ModbusPDUWriteSingleCoilRequestBuilder(address, value ) - + return ModbusPDUWriteSingleCoilRequestBuilder(address, value) def equals(self, o: object) -> bool: if self == o: @@ -90,19 +88,25 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUWriteSingleCoilRequest = ModbusPDUWriteSingleCoilRequest(o) - return (self.address == that.address) and (self.value == that.value) and super().equals(that) and True + return ( + (self.address == that.address) + and (self.value == that.value) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass @@ -110,12 +114,10 @@ class ModbusPDUWriteSingleCoilRequestBuilder(ModbusPDUBuilder): address: int value: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteSingleCoilRequest: - modbus_pdu_write_single_coil_request: ModbusPDUWriteSingleCoilRequest = ModbusPDUWriteSingleCoilRequest(self.address, self.value ) + def build( + self, + ) -> ModbusPDUWriteSingleCoilRequest: + modbus_pdu_write_single_coil_request: ModbusPDUWriteSingleCoilRequest = ( + ModbusPDUWriteSingleCoilRequest(self.address, self.value) + ) return modbus_pdu_write_single_coil_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilResponse.py index f298f6e825d..6a1e2a8b7ae 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleCoilResponse.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUWriteSingleCoilResponse(PlcMessage,ModbusPDU): +class ModbusPDUWriteSingleCoilResponse(ModbusPDU): address: int value: int # Accessors for discriminator values. @@ -35,12 +38,6 @@ class ModbusPDUWriteSingleCoilResponse(PlcMessage,ModbusPDU): function_flag: int = 0x05 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteSingleCoilResponse") @@ -52,12 +49,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteSingleCoilResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteSingleCoilResponse = self # Simple field (address) @@ -68,19 +64,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteSingleCoilResponse") - self.address= read_simple_field("address", read_unsigned_int) + address: int = read_buffer.read_unsigned_short( + logical_name="address", bit_length=16, response=response + ) - self.value= read_simple_field("value", read_unsigned_int) + value: int = read_buffer.read_unsigned_short( + logical_name="value", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUWriteSingleCoilResponse") # Create the instance - return ModbusPDUWriteSingleCoilResponseBuilder(address, value ) - + return ModbusPDUWriteSingleCoilResponseBuilder(address, value) def equals(self, o: object) -> bool: if self == o: @@ -90,19 +88,25 @@ def equals(self, o: object) -> bool: return False that: ModbusPDUWriteSingleCoilResponse = ModbusPDUWriteSingleCoilResponse(o) - return (self.address == that.address) and (self.value == that.value) and super().equals(that) and True + return ( + (self.address == that.address) + and (self.value == that.value) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass @@ -110,12 +114,10 @@ class ModbusPDUWriteSingleCoilResponseBuilder(ModbusPDUBuilder): address: int value: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteSingleCoilResponse: - modbus_pdu_write_single_coil_response: ModbusPDUWriteSingleCoilResponse = ModbusPDUWriteSingleCoilResponse(self.address, self.value ) + def build( + self, + ) -> ModbusPDUWriteSingleCoilResponse: + modbus_pdu_write_single_coil_response: ModbusPDUWriteSingleCoilResponse = ( + ModbusPDUWriteSingleCoilResponse(self.address, self.value) + ) return modbus_pdu_write_single_coil_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterRequest.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterRequest.py index 39d93747d57..90c33d472ab 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterRequest.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterRequest.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUWriteSingleRegisterRequest(PlcMessage,ModbusPDU): +class ModbusPDUWriteSingleRegisterRequest(ModbusPDU): address: int value: int # Accessors for discriminator values. @@ -35,12 +38,6 @@ class ModbusPDUWriteSingleRegisterRequest(PlcMessage,ModbusPDU): function_flag: int = 0x06 response: bool = False - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteSingleRegisterRequest") @@ -52,12 +49,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteSingleRegisterRequest") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteSingleRegisterRequest = self # Simple field (address) @@ -68,19 +64,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteSingleRegisterRequest") - self.address= read_simple_field("address", read_unsigned_int) + address: int = read_buffer.read_unsigned_short( + logical_name="address", bit_length=16, response=response + ) - self.value= read_simple_field("value", read_unsigned_int) + value: int = read_buffer.read_unsigned_short( + logical_name="value", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUWriteSingleRegisterRequest") # Create the instance - return ModbusPDUWriteSingleRegisterRequestBuilder(address, value ) - + return ModbusPDUWriteSingleRegisterRequestBuilder(address, value) def equals(self, o: object) -> bool: if self == o: @@ -89,20 +87,28 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUWriteSingleRegisterRequest): return False - that: ModbusPDUWriteSingleRegisterRequest = ModbusPDUWriteSingleRegisterRequest(o) - return (self.address == that.address) and (self.value == that.value) and super().equals(that) and True + that: ModbusPDUWriteSingleRegisterRequest = ModbusPDUWriteSingleRegisterRequest( + o + ) + return ( + (self.address == that.address) + and (self.value == that.value) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass @@ -110,12 +116,10 @@ class ModbusPDUWriteSingleRegisterRequestBuilder(ModbusPDUBuilder): address: int value: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteSingleRegisterRequest: - modbus_pdu_write_single_register_request: ModbusPDUWriteSingleRegisterRequest = ModbusPDUWriteSingleRegisterRequest(self.address, self.value ) + def build( + self, + ) -> ModbusPDUWriteSingleRegisterRequest: + modbus_pdu_write_single_register_request: ModbusPDUWriteSingleRegisterRequest = ModbusPDUWriteSingleRegisterRequest( + self.address, self.value + ) return modbus_pdu_write_single_register_request - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterResponse.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterResponse.py index 971edcf6cc7..ef96ece2358 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterResponse.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusPDUWriteSingleRegisterResponse.py @@ -19,15 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDUBuilder from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer import math - + + @dataclass -class ModbusPDUWriteSingleRegisterResponse(PlcMessage,ModbusPDU): +class ModbusPDUWriteSingleRegisterResponse(ModbusPDU): address: int value: int # Accessors for discriminator values. @@ -35,12 +38,6 @@ class ModbusPDUWriteSingleRegisterResponse(PlcMessage,ModbusPDU): function_flag: int = 0x06 response: bool = True - - def __post_init__(self): - super().__init__( ) - - - def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusPDUWriteSingleRegisterResponse") @@ -52,12 +49,11 @@ def serialize_modbus_pdu_child(self, write_buffer: WriteBuffer): write_buffer.pop_context("ModbusPDUWriteSingleRegisterResponse") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusPDUWriteSingleRegisterResponse = self # Simple field (address) @@ -68,19 +64,21 @@ def get_length_in_bits(self) -> int: return length_in_bits - @staticmethod def static_parse_builder(read_buffer: ReadBuffer, response: bool): read_buffer.push_context("ModbusPDUWriteSingleRegisterResponse") - self.address= read_simple_field("address", read_unsigned_int) + address: int = read_buffer.read_unsigned_short( + logical_name="address", bit_length=16, response=response + ) - self.value= read_simple_field("value", read_unsigned_int) + value: int = read_buffer.read_unsigned_short( + logical_name="value", bit_length=16, response=response + ) read_buffer.pop_context("ModbusPDUWriteSingleRegisterResponse") # Create the instance - return ModbusPDUWriteSingleRegisterResponseBuilder(address, value ) - + return ModbusPDUWriteSingleRegisterResponseBuilder(address, value) def equals(self, o: object) -> bool: if self == o: @@ -89,20 +87,28 @@ def equals(self, o: object) -> bool: if not isinstance(o, ModbusPDUWriteSingleRegisterResponse): return False - that: ModbusPDUWriteSingleRegisterResponse = ModbusPDUWriteSingleRegisterResponse(o) - return (self.address == that.address) and (self.value == that.value) and super().equals(that) and True + that: ModbusPDUWriteSingleRegisterResponse = ( + ModbusPDUWriteSingleRegisterResponse(o) + ) + return ( + (self.address == that.address) + and (self.value == that.value) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass @@ -110,12 +116,10 @@ class ModbusPDUWriteSingleRegisterResponseBuilder(ModbusPDUBuilder): address: int value: int - def __post_init__(self): - pass - - def build(self,) -> ModbusPDUWriteSingleRegisterResponse: - modbus_pdu_write_single_register_response: ModbusPDUWriteSingleRegisterResponse = ModbusPDUWriteSingleRegisterResponse(self.address, self.value ) + def build( + self, + ) -> ModbusPDUWriteSingleRegisterResponse: + modbus_pdu_write_single_register_response: ModbusPDUWriteSingleRegisterResponse = ModbusPDUWriteSingleRegisterResponse( + self.address, self.value + ) return modbus_pdu_write_single_register_response - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusRtuADU.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusRtuADU.py index 9e3386ad2e5..fd533a66b46 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusRtuADU.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusRtuADU.py @@ -19,6 +19,8 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus import StaticHelper from plc4py.protocols.modbus.readwrite.DriverType import DriverType @@ -27,10 +29,12 @@ from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from plc4py.utils.GenericTypes import ByteOrder import math - + + @dataclass -class ModbusRtuADU(PlcMessage,ModbusADU): +class ModbusRtuADU(ModbusADU): address: int pdu: ModbusPDU # Arguments. @@ -38,12 +42,6 @@ class ModbusRtuADU(PlcMessage,ModbusADU): # Accessors for discriminator values. driver_type: DriverType = DriverType.MODBUS_RTU - - def __post_init__(self): - super().__init__( self.response ) - - - def serialize_modbus_adu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusRtuADU") @@ -54,44 +52,62 @@ def serialize_modbus_adu_child(self, write_buffer: WriteBuffer): write_buffer.write_serializable(self.pdu, logical_name="pdu") # Checksum Field (checksum) (Calculated) - write_buffer.write_unsigned_short(int(StaticHelper.rtu_crc_check(self.address, self.pdu)), logical_name="crc") + write_buffer.write_unsigned_short( + int(StaticHelper.rtu_crc_check(address, pdu)), logical_name="crc" + ) write_buffer.pop_context("ModbusRtuADU") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusRtuADU = self # Simple field (address) length_in_bits += 8 # Simple field (pdu) - length_in_bits += self.pdu.get_length_in_bits() + length_in_bits += self.pdu.length_in_bits() # Checksum Field (checksum) length_in_bits += 16 return length_in_bits - @staticmethod - def static_parse_builder(read_buffer: ReadBuffer, driver_type: DriverType, response: bool): + def static_parse_builder( + read_buffer: ReadBuffer, driver_type: DriverType, response: bool + ): read_buffer.push_context("ModbusRtuADU") - self.address= read_simple_field("address", read_unsigned_short, WithOption.WithByteOrder(get_bi_g__endian())) - - self.pdu= read_simple_field("pdu", DataReaderComplexDefault(ModbusPDU.static_parse(read_buffer, bool(response)), read_buffer), WithOption.WithByteOrder(get_bi_g__endian())) - - crc: int = read_checksum_field("crc", read_unsigned_int, (int) (rtu_crc_check(self.address, self.pdu)), WithOption.WithByteOrder(get_bi_g__endian())) + address: int = read_buffer.read_unsigned_byte( + logical_name="address", + bit_length=8, + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + pdu: ModbusPDU = read_buffer.read_complex( + read_function=ModbusPDU.static_parse, + logical_name="pdu", + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + crc: int = read_buffer.read_unsigned_short( + logical_name="crc", + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) read_buffer.pop_context("ModbusRtuADU") # Create the instance - return ModbusRtuADUBuilder(address, pdu , response ) - + return ModbusRtuADUBuilder(address, pdu) def equals(self, o: object) -> bool: if self == o: @@ -101,33 +117,35 @@ def equals(self, o: object) -> bool: return False that: ModbusRtuADU = ModbusRtuADU(o) - return (self.address == that.address) and (self.pdu == that.pdu) and super().equals(that) and True + return ( + (self.address == that.address) + and (self.pdu == that.pdu) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusRtuADUBuilder(ModbusADUBuilder): address: int pdu: ModbusPDU - response: bool - def __post_init__(self): - pass - - def build(self,response: bool ) -> ModbusRtuADU: - modbus_rtu_adu: ModbusRtuADU = ModbusRtuADU(self.address, self.pdu , response ) + def build( + self, + response: bool, + ) -> ModbusRtuADU: + modbus_rtu_adu: ModbusRtuADU = ModbusRtuADU(response, self.address, self.pdu) return modbus_rtu_adu - - - diff --git a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py index 4ba09ebfe12..67d369132ab 100644 --- a/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py +++ b/sandbox/plc4py/plc4py/protocols/modbus/readwrite/ModbusTcpADU.py @@ -19,6 +19,8 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.protocols.modbus.readwrite.DriverType import DriverType from plc4py.protocols.modbus.readwrite.ModbusADU import ModbusADU @@ -26,52 +28,53 @@ from plc4py.protocols.modbus.readwrite.ModbusPDU import ModbusPDU from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from plc4py.utils.GenericTypes import ByteOrder import math - + + @dataclass -class ModbusTcpADU(PlcMessage,ModbusADU): +class ModbusTcpADU(ModbusADU): transaction_identifier: int unit_identifier: int pdu: ModbusPDU # Arguments. response: bool - PROTOCOLIDENTIFIER: int = 0x0000 + PROTOCOL_IDENTIFIER: int = 0x0000 # Accessors for discriminator values. driver_type: DriverType = DriverType.MODBUS_TCP - - def __post_init__(self): - super().__init__( self.response ) - - - def serialize_modbus_adu_child(self, write_buffer: WriteBuffer): write_buffer.push_context("ModbusTcpADU") # Simple Field (transactionIdentifier) - write_buffer.write_unsigned_short(self.transaction_identifier, logical_name="transactionIdentifier") + write_buffer.write_unsigned_short( + self.transaction_identifier, logical_name="transactionIdentifier" + ) # Const Field (protocolIdentifier) - write_buffer.write_unsigned_short(self.protocol_identifier.value, logical_name="protocolIdentifier") + write_buffer.write_unsigned_short( + self.PROTOCOL_IDENTIFIER, logical_name="protocolIdentifier" + ) # Implicit Field (length) (Used for parsing, but its value is not stored as it's implicitly given by the objects content) - length: int = (self.pdu.getlength_in_bytes(ctx)+ int(1)) + length: int = self.pdu.length_in_bytes() + int(1) write_buffer.write_unsigned_short(length, logical_name="length") # Simple Field (unitIdentifier) - write_buffer.write_unsigned_byte(self.unit_identifier, logical_name="unitIdentifier") + write_buffer.write_unsigned_byte( + self.unit_identifier, logical_name="unitIdentifier" + ) # Simple Field (pdu) write_buffer.write_serializable(self.pdu, logical_name="pdu") write_buffer.pop_context("ModbusTcpADU") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: - length_in_bits: int = super().get_length_in_bits() + def length_in_bits(self) -> int: + length_in_bits: int = super().length_in_bits() _value: ModbusTcpADU = self # Simple field (transactionIdentifier) @@ -87,29 +90,57 @@ def get_length_in_bits(self) -> int: length_in_bits += 8 # Simple field (pdu) - length_in_bits += self.pdu.get_length_in_bits() + length_in_bits += self.pdu.length_in_bits() return length_in_bits - @staticmethod - def static_parse_builder(read_buffer: ReadBuffer, driver_type: DriverType, response: bool): + def static_parse_builder( + read_buffer: ReadBuffer, driver_type: DriverType, response: bool + ): read_buffer.push_context("ModbusTcpADU") - self.transaction_identifier= read_simple_field("transactionIdentifier", read_unsigned_int, WithOption.WithByteOrder(get_bi_g__endian())) - - self.protocol_identifier: int = read_const_field("protocolIdentifier", read_unsigned_int, ModbusTcpADU.PROTOCOLIDENTIFIER, WithOption.WithByteOrder(get_bi_g__endian())) - - length: int = read_implicit_field("length", read_unsigned_int, WithOption.WithByteOrder(get_bi_g__endian())) - - self.unit_identifier= read_simple_field("unitIdentifier", read_unsigned_short, WithOption.WithByteOrder(get_bi_g__endian())) - - self.pdu= read_simple_field("pdu", DataReaderComplexDefault(ModbusPDU.static_parse(read_buffer, bool(response)), read_buffer), WithOption.WithByteOrder(get_bi_g__endian())) + transaction_identifier: int = read_buffer.read_unsigned_short( + logical_name="transactionIdentifier", + bit_length=16, + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + PROTOCOL_IDENTIFIER: int = read_buffer.read_unsigned_short( + logical_name="protocolIdentifier", + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + length: int = read_buffer.read_unsigned_short( + logical_name="length", + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + unit_identifier: int = read_buffer.read_unsigned_byte( + logical_name="unitIdentifier", + bit_length=8, + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) + + pdu: ModbusPDU = read_buffer.read_complex( + read_function=ModbusPDU.static_parse, + logical_name="pdu", + byte_order=ByteOrder.BIG_ENDIAN, + driver_type=driver_type, + response=response, + ) read_buffer.pop_context("ModbusTcpADU") # Create the instance - return ModbusTcpADUBuilder(transaction_identifier, unit_identifier, pdu , response ) - + return ModbusTcpADUBuilder(transaction_identifier, unit_identifier, pdu) def equals(self, o: object) -> bool: if self == o: @@ -119,34 +150,39 @@ def equals(self, o: object) -> bool: return False that: ModbusTcpADU = ModbusTcpADU(o) - return (self.transaction_identifier == that.transaction_identifier) and (self.unit_identifier == that.unit_identifier) and (self.pdu == that.pdu) and super().equals(that) and True + return ( + (self.transaction_identifier == that.transaction_identifier) + and (self.unit_identifier == that.unit_identifier) + and (self.pdu == that.pdu) + and super().equals(that) + and True + ) def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) - return "\n" + str(write_buffer_box_based.get_box()) + "\n" + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" @dataclass class ModbusTcpADUBuilder(ModbusADUBuilder): - transactionIdentifier: int - unitIdentifier: int + transaction_identifier: int + unit_identifier: int pdu: ModbusPDU - response: bool - def __post_init__(self): - pass - - def build(self,response: bool ) -> ModbusTcpADU: - modbus_tcp_adu: ModbusTcpADU = ModbusTcpADU(self.transaction_identifier, self.unit_identifier, self.pdu , response ) + def build( + self, + response: bool, + ) -> ModbusTcpADU: + modbus_tcp_adu: ModbusTcpADU = ModbusTcpADU( + response, self.transaction_identifier, self.unit_identifier, self.pdu + ) return modbus_tcp_adu - - - diff --git a/sandbox/plc4py/plc4py/protocols/simulated/readwrite/DataItem.py b/sandbox/plc4py/plc4py/protocols/simulated/readwrite/DataItem.py index 1bb91cef3d0..55989bbfa01 100644 --- a/sandbox/plc4py/plc4py/protocols/simulated/readwrite/DataItem.py +++ b/sandbox/plc4py/plc4py/protocols/simulated/readwrite/DataItem.py @@ -17,708 +17,642 @@ # under the License. # -from abc import staticmethod -from loguru import logging as log +from plc4py.api.value.PlcValue import PlcValue +from plc4py.spi.generation.ReadBuffer import ReadBuffer +from plc4py.spi.generation.WriteBuffer import WriteBuffer +from plc4py.spi.values.PlcValues import PlcBOOL +from plc4py.spi.values.PlcValues import PlcBYTE +from plc4py.spi.values.PlcValues import PlcCHAR +from plc4py.spi.values.PlcValues import PlcDINT +from plc4py.spi.values.PlcValues import PlcDWORD +from plc4py.spi.values.PlcValues import PlcINT +from plc4py.spi.values.PlcValues import PlcLINT +from plc4py.spi.values.PlcValues import PlcLREAL +from plc4py.spi.values.PlcValues import PlcLWORD +from plc4py.spi.values.PlcValues import PlcList +from plc4py.spi.values.PlcValues import PlcREAL +from plc4py.spi.values.PlcValues import PlcSINT +from plc4py.spi.values.PlcValues import PlcSTRING +from plc4py.spi.values.PlcValues import PlcUDINT +from plc4py.spi.values.PlcValues import PlcUINT +from plc4py.spi.values.PlcValues import PlcULINT +from plc4py.spi.values.PlcValues import PlcUSINT +from plc4py.spi.values.PlcValues import PlcWCHAR +from plc4py.spi.values.PlcValues import PlcWORD +from plc4py.utils.GenericTypes import ByteOrder +from typing import List import math - -class DataItem: +class DataItem: @staticmethod def static_parse(read_buffer: ReadBuffer, data_type: str, number_of_values: int): - if EvaluationHelper.equals( data_type, "_bool" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # BOOL - + if data_type == "_bool" and number_of_values == int(1): # BOOL # Simple Field (value) value: bool = read_buffer.read_bit("") return PlcBOOL(value) - if EvaluationHelper.equals( data_type, "_bool" ) : # List + if data_type == "_bool": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcBOOL(bool(read_buffer.read_bit("")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, "_byte" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # BYTE - + if data_type == "_byte" and number_of_values == int(1): # BYTE # Simple Field (value) value: int = read_buffer.read_unsigned_short(8, logical_name="") return PlcBYTE(value) - if EvaluationHelper.equals( data_type, "_byte" ) : # List + if data_type == "_byte": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcUINT(int(read_buffer.read_unsigned_short(8, logical_name="")))) - + value.append( + PlcUINT(int(read_buffer.read_unsigned_short(8, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_word" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # WORD - + if data_type == "_word" and number_of_values == int(1): # WORD # Simple Field (value) value: int = read_buffer.read_unsigned_int(16, logical_name="") return PlcWORD(value) - if EvaluationHelper.equals( data_type, "_word" ) : # List + if data_type == "_word": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcUDINT(int(read_buffer.read_unsigned_int(16, logical_name="")))) - + value.append( + PlcUDINT(int(read_buffer.read_unsigned_int(16, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_dword" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # DWORD - + if data_type == "_dword" and number_of_values == int(1): # DWORD # Simple Field (value) value: int = read_buffer.read_unsigned_long(32, logical_name="") return PlcDWORD(value) - if EvaluationHelper.equals( data_type, "_dword" ) : # List + if data_type == "_dword": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcULINT(int(read_buffer.read_unsigned_long(32, logical_name="")))) - + value.append( + PlcULINT(int(read_buffer.read_unsigned_long(32, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_lword" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # LWORD - + if data_type == "_lword" and number_of_values == int(1): # LWORD # Simple Field (value) - value: int = read_buffer.read_unsigned_big_integer(64, logical_name="") + value: int = read_buffer.read_unsigned_long(64, logical_name="") return PlcLWORD(value) - if EvaluationHelper.equals( data_type, "_lword" ) : # List + if data_type == "_lword": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcLINT(int(read_buffer.read_unsigned_big_integer(64, logical_name="")))) - + value.append( + PlcLINT(int(read_buffer.read_unsigned_long(64, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_sint" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # SINT - + if data_type == "_sint" and number_of_values == int(1): # SINT # Simple Field (value) value: int = read_buffer.read_signed_byte(8, logical_name="") return PlcSINT(value) - if EvaluationHelper.equals( data_type, "_sint" ) : # List + if data_type == "_sint": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcSINT(int(read_buffer.read_signed_byte(8, logical_name="")))) - + value.append( + PlcSINT(int(read_buffer.read_signed_byte(8, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_int" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # INT - + if data_type == "_int" and number_of_values == int(1): # INT # Simple Field (value) value: int = read_buffer.read_short(16, logical_name="") return PlcINT(value) - if EvaluationHelper.equals( data_type, "_int" ) : # List + if data_type == "_int": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcINT(int(read_buffer.read_short(16, logical_name="")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, "_dint" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # DINT - + if data_type == "_dint" and number_of_values == int(1): # DINT # Simple Field (value) value: int = read_buffer.read_int(32, logical_name="") return PlcDINT(value) - if EvaluationHelper.equals( data_type, "_dint" ) : # List + if data_type == "_dint": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcDINT(int(read_buffer.read_int(32, logical_name="")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, "_lint" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # LINT - + if data_type == "_lint" and number_of_values == int(1): # LINT # Simple Field (value) value: int = read_buffer.read_long(64, logical_name="") return PlcLINT(value) - if EvaluationHelper.equals( data_type, "_lint" ) : # List + if data_type == "_lint": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): value.append(PlcLINT(int(read_buffer.read_long(64, logical_name="")))) - return PlcList(value) - if EvaluationHelper.equals( data_type, "_usint" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # USINT - + if data_type == "_usint" and number_of_values == int(1): # USINT # Simple Field (value) value: int = read_buffer.read_unsigned_short(8, logical_name="") return PlcUSINT(value) - if EvaluationHelper.equals( data_type, "_usint" ) : # List + if data_type == "_usint": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcUINT(int(read_buffer.read_unsigned_short(8, logical_name="")))) - + value.append( + PlcUINT(int(read_buffer.read_unsigned_short(8, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_uint" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # UINT - + if data_type == "_uint" and number_of_values == int(1): # UINT # Simple Field (value) value: int = read_buffer.read_unsigned_int(16, logical_name="") return PlcUINT(value) - if EvaluationHelper.equals( data_type, "_uint" ) : # List + if data_type == "_uint": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcUDINT(int(read_buffer.read_unsigned_int(16, logical_name="")))) - + value.append( + PlcUDINT(int(read_buffer.read_unsigned_int(16, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_udint" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # UDINT - + if data_type == "_udint" and number_of_values == int(1): # UDINT # Simple Field (value) value: int = read_buffer.read_unsigned_long(32, logical_name="") return PlcUDINT(value) - if EvaluationHelper.equals( data_type, "_udint" ) : # List + if data_type == "_udint": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcULINT(int(read_buffer.read_unsigned_long(32, logical_name="")))) - + value.append( + PlcULINT(int(read_buffer.read_unsigned_long(32, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_ulint" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # ULINT - + if data_type == "_ulint" and number_of_values == int(1): # ULINT # Simple Field (value) - value: int = read_buffer.read_unsigned_big_integer(64, logical_name="") + value: int = read_buffer.read_unsigned_long(64, logical_name="") return PlcULINT(value) - if EvaluationHelper.equals( data_type, "_ulint" ) : # List + if data_type == "_ulint": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcLINT(int(read_buffer.read_unsigned_big_integer(64, logical_name="")))) - + value.append( + PlcLINT(int(read_buffer.read_unsigned_long(64, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_real" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # REAL - + if data_type == "_real" and number_of_values == int(1): # REAL # Simple Field (value) value: float = read_buffer.read_float(32, logical_name="") return PlcREAL(value) - if EvaluationHelper.equals( data_type, "_real" ) : # List + if data_type == "_real": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcREAL(float(read_buffer.read_float(32, logical_name="")))) - + value.append( + PlcREAL(float(read_buffer.read_float(32, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_lreal" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # LREAL - + if data_type == "_lreal" and number_of_values == int(1): # LREAL # Simple Field (value) value: float = read_buffer.read_double(64, logical_name="") return PlcLREAL(value) - if EvaluationHelper.equals( data_type, "_lreal" ) : # List + if data_type == "_lreal": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcLREAL(float(read_buffer.read_double(64, logical_name="")))) - + value.append( + PlcLREAL(float(read_buffer.read_double(64, logical_name=""))) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_char" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # CHAR - + if data_type == "_char" and number_of_values == int(1): # CHAR # Simple Field (value) - value: str = read_buffer.read_string(8, logical_name="", encoding="") + value: str = read_buffer.read_str(8, logical_name="", encoding="") return PlcCHAR(value) - if EvaluationHelper.equals( data_type, "_char" ) : # List + if data_type == "_char": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcSTRING(str(read_buffer.read_string(8, logical_name="", encoding="")))) - + value.append( + PlcSTRING( + str(read_buffer.read_str(8, logical_name="", encoding="")) + ) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_wchar" ) and EvaluationHelper.equals( number_of_values, int(1) ) : # WCHAR - + if data_type == "_wchar" and number_of_values == int(1): # WCHAR # Simple Field (value) - value: str = read_buffer.read_string(16, logical_name="", encoding="") + value: str = read_buffer.read_str(16, logical_name="", encoding="") return PlcWCHAR(value) - if EvaluationHelper.equals( data_type, "_wchar" ) : # List + if data_type == "_wchar": # List # Array field (value) # Count array - if numberOfValues > Integer.MAX_VALUE: - raise ParseException("Array count of " + (numberOfValues) + " exceeds the maximum allowed count of " + Integer.MAX_VALUE) - - item_count: int = int(numberOfValues) + item_count: int = int(number_of_values) value: List[PlcValue] = [] for cur_item in range(item_count): - value.append(PlcSTRING(str(read_buffer.read_string(16, logical_name="", encoding="")))) - + value.append( + PlcSTRING( + str(read_buffer.read_str(16, logical_name="", encoding="")) + ) + ) return PlcList(value) - if EvaluationHelper.equals( data_type, "_string" ) : # STRING - + if data_type == "_string": # STRING # Simple Field (value) - value: str = read_buffer.read_string(255, logical_name="", encoding="") + value: str = read_buffer.read_str(255, logical_name="", encoding="") return PlcSTRING(value) - if EvaluationHelper.equals( data_type, "_wstring" ) : # STRING - + if data_type == "_wstring": # STRING # Simple Field (value) - value: str = read_buffer.read_string(255, logical_name="", encoding="") + value: str = read_buffer.read_str(255, logical_name="", encoding="") return PlcSTRING(value) return None @staticmethod - def static_serialize(writeBuffer: WriteBuffer, _value: PlcValue, dataType: str, numberOfValues: int) -> None: - static_serialize(writeBuffer, _value, dataType, numberOfValues, ByteOrder.BIG_ENDIAN) - - @staticmethod - def static_serialize(writeBuffer: WriteBuffer, _value: PlcValue, dataType: str, numberOfValues: int, byteOrder: ByteOrder) -> None: - if EvaluationHelper.equals( dataType, "BOOL" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # BOOL - - # Simple Field (value) - value: bool = _value.getBool() - writeBuffer.WriteBit("value", (value)) - if EvaluationHelper.equals( dataType, "BOOL" ) : # List - + def static_serialize( + write_buffer: WriteBuffer, + _value: PlcValue, + data_type: str, + number_of_values: int, + byte_order: ByteOrder, + ) -> None: + if data_type == "BOOL" and number_of_values == int(1): # BOOL + # Simple Field (value) + value: bool = _value.get_bool() + write_buffer.write_bit((value), "value") + if data_type == "BOOL": # List values: PlcList = _value - for val in values.getList(): - value: bool = val.getBool() - writeBuffer.WriteBit("value", (value)) - - if EvaluationHelper.equals( dataType, "BYTE" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # BYTE + for val in values.get_list(): + value: bool = val.get_bool() + write_buffer.write_bit((value), "value") + if data_type == "BYTE" and number_of_values == int(1): # BYTE # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint8("value", 8, (value)) - if EvaluationHelper.equals( dataType, "BYTE" ) : # List - + value: int = _value.get_int() + write_buffer.write_byte((value), 8, "value") + if data_type == "BYTE": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint8("value", 8, (value)) - - if EvaluationHelper.equals( dataType, "WORD" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # WORD + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_byte((value), 8, "value") + if data_type == "WORD" and number_of_values == int(1): # WORD # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint16("value", 16, (value)) - if EvaluationHelper.equals( dataType, "WORD" ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_short((value), 16, "value") + if data_type == "WORD": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint16("value", 16, (value)) - - if EvaluationHelper.equals( dataType, "DWORD" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # DWORD + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_short((value), 16, "value") + if data_type == "DWORD" and number_of_values == int(1): # DWORD # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint32("value", 32, (value)) - if EvaluationHelper.equals( dataType, "DWORD" ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_int((value), 32, "value") + if data_type == "DWORD": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint32("value", 32, (value)) - - if EvaluationHelper.equals( dataType, "LWORD" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # LWORD + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_int((value), 32, "value") + if data_type == "LWORD" and number_of_values == int(1): # LWORD # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint64("value", 64, (value)) - if EvaluationHelper.equals( dataType, "LWORD" ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_long((value), 64, "value") + if data_type == "LWORD": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint64("value", 64, (value)) - - if EvaluationHelper.equals( dataType, "SINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # SINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_long((value), 64, "value") + if data_type == "SINT" and number_of_values == int(1): # SINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt8("value", 8, (value)) - if EvaluationHelper.equals( dataType, "SINT" ) : # List - + value: int = _value.get_int() + write_buffer.write_signed_byte((value), 8, "value") + if data_type == "SINT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt8("value", 8, (value)) - - if EvaluationHelper.equals( dataType, "INT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # INT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_signed_byte((value), 8, "value") + if data_type == "INT" and number_of_values == int(1): # INT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt16("value", 16, (value)) - if EvaluationHelper.equals( dataType, "INT" ) : # List - + value: int = _value.get_int() + write_buffer.write_short((value), 16, "value") + if data_type == "INT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt16("value", 16, (value)) - - if EvaluationHelper.equals( dataType, "DINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # DINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_short((value), 16, "value") + if data_type == "DINT" and number_of_values == int(1): # DINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt32("value", 32, (value)) - if EvaluationHelper.equals( dataType, "DINT" ) : # List - + value: int = _value.get_int() + write_buffer.write_int((value), 32, "value") + if data_type == "DINT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt32("value", 32, (value)) - - if EvaluationHelper.equals( dataType, "LINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # LINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_int((value), 32, "value") + if data_type == "LINT" and number_of_values == int(1): # LINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteInt64("value", 64, (value)) - if EvaluationHelper.equals( dataType, "LINT" ) : # List - + value: int = _value.get_int() + write_buffer.write_long((value), 64, "value") + if data_type == "LINT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteInt64("value", 64, (value)) - - if EvaluationHelper.equals( dataType, "USINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # USINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_long((value), 64, "value") + if data_type == "USINT" and number_of_values == int(1): # USINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint8("value", 8, (value)) - if EvaluationHelper.equals( dataType, "USINT" ) : # List - + value: int = _value.get_int() + write_buffer.write_byte((value), 8, "value") + if data_type == "USINT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint8("value", 8, (value)) - - if EvaluationHelper.equals( dataType, "UINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # UINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_byte((value), 8, "value") + if data_type == "UINT" and number_of_values == int(1): # UINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint16("value", 16, (value)) - if EvaluationHelper.equals( dataType, "UINT" ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_short((value), 16, "value") + if data_type == "UINT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint16("value", 16, (value)) - - if EvaluationHelper.equals( dataType, "UDINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # UDINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_short((value), 16, "value") + if data_type == "UDINT" and number_of_values == int(1): # UDINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint32("value", 32, (value)) - if EvaluationHelper.equals( dataType, "UDINT" ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_int((value), 32, "value") + if data_type == "UDINT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint32("value", 32, (value)) - - if EvaluationHelper.equals( dataType, "ULINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # ULINT + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_int((value), 32, "value") + if data_type == "ULINT" and number_of_values == int(1): # ULINT # Simple Field (value) - value: int = _value.getInt() - writeBuffer.WriteUint64("value", 64, (value)) - if EvaluationHelper.equals( dataType, "ULINT" ) : # List - + value: int = _value.get_int() + write_buffer.write_unsigned_long((value), 64, "value") + if data_type == "ULINT": # List values: PlcList = _value - for val in values.getList(): - value: int = val.getInt() - writeBuffer.WriteUint64("value", 64, (value)) - - if EvaluationHelper.equals( dataType, "REAL" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # REAL + for val in values.get_list(): + value: int = val.get_int() + write_buffer.write_unsigned_long((value), 64, "value") + if data_type == "REAL" and number_of_values == int(1): # REAL # Simple Field (value) - value: float = _value.getFloat() - writeBuffer.WriteFloat32("value", 32, (value)) - if EvaluationHelper.equals( dataType, "REAL" ) : # List - + value: float = _value.get_float() + write_buffer.write_float((value), 32, "value") + if data_type == "REAL": # List values: PlcList = _value - for val in values.getList(): - value: float = val.getFloat() - writeBuffer.WriteFloat32("value", 32, (value)) - - if EvaluationHelper.equals( dataType, "LREAL" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # LREAL + for val in values.get_list(): + value: float = val.get_float() + write_buffer.write_float((value), 32, "value") + if data_type == "LREAL" and number_of_values == int(1): # LREAL # Simple Field (value) - value: float = _value.getFloat() - writeBuffer.WriteFloat64("value", 64, (value)) - if EvaluationHelper.equals( dataType, "LREAL" ) : # List - + value: float = _value.get_float() + write_buffer.write_double((value), 64, "value") + if data_type == "LREAL": # List values: PlcList = _value - for val in values.getList(): - value: float = val.getFloat() - writeBuffer.WriteFloat64("value", 64, (value)) - - if EvaluationHelper.equals( dataType, "CHAR" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # CHAR + for val in values.get_list(): + value: float = val.get_float() + write_buffer.write_double((value), 64, "value") + if data_type == "CHAR" and number_of_values == int(1): # CHAR # Simple Field (value) - value: str = _value.getStr() - writeBuffer.WriteString("value", uint32(8), "UTF-8", (value)) - if EvaluationHelper.equals( dataType, "CHAR" ) : # List - + value: str = _value.get_str() + write_buffer.write_str((value), 8, "UTF-8", "value") + if data_type == "CHAR": # List values: PlcList = _value - for val in values.getList(): - value: str = val.getStr() - writeBuffer.WriteString("value", uint32(8), "UTF-8", (value)) - - if EvaluationHelper.equals( dataType, "WCHAR" ) and EvaluationHelper.equals( numberOfValues, int(1) ) : # WCHAR + for val in values.get_list(): + value: str = val.get_str() + write_buffer.write_str((value), 8, "UTF-8", "value") + if data_type == "WCHAR" and number_of_values == int(1): # WCHAR # Simple Field (value) - value: str = _value.getStr() - writeBuffer.WriteString("value", uint32(16), "UTF-16", (value)) - if EvaluationHelper.equals( dataType, "WCHAR" ) : # List - + value: str = _value.get_str() + write_buffer.write_str((value), 16, "UTF-16", "value") + if data_type == "WCHAR": # List values: PlcList = _value - for val in values.getList(): - value: str = val.getStr() - writeBuffer.WriteString("value", uint32(16), "UTF-16", (value)) - - if EvaluationHelper.equals( dataType, "STRING" ) : # STRING + for val in values.get_list(): + value: str = val.get_str() + write_buffer.write_str((value), 16, "UTF-16", "value") + if data_type == "STRING": # STRING # Simple Field (value) - value: str = _value.getStr() - writeBuffer.WriteString("value", uint32(255), "UTF-8", (value)) - if EvaluationHelper.equals( dataType, "WSTRING" ) : # STRING - + value: str = _value.get_str() + write_buffer.write_str((value), 255, "UTF-8", "value") + if data_type == "WSTRING": # STRING # Simple Field (value) - value: str = _value.getStr() - writeBuffer.WriteString("value", uint32(255), "UTF-16", (value)) + value: str = _value.get_str() + write_buffer.write_str((value), 255, "UTF-16", "value") @staticmethod - def get_length_in_bytes(_value: PlcValue, dataType: str, numberOfValues: int) -> int: - return int(math.ceil(float(getLengthInBits(_value, dataType, numberOfValues)) / 8.0)) - + def get_length_in_bytes( + _value: PlcValue, data_type: str, number_of_values: int + ) -> int: + return int( + math.ceil( + float(DataItem.get_length_in_bits(_value, data_type, number_of_values)) + / 8.0 + ) + ) @staticmethod - def get_length_in_bits(_value: PlcValue, dataType: str, numberOfValues: int) -> int: - sizeInBits: int = 0 - if EvaluationHelper.equals( dataType, "BOOL" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # BOOL - # Simple Field (value) - sizeInBits += 1 - if EvaluationHelper.equals( dataType, "BOOL" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 1 - if EvaluationHelper.equals( dataType, "BYTE" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # BYTE - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, "BYTE" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 8 - if EvaluationHelper.equals( dataType, "WORD" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # WORD - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, "WORD" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 16 - if EvaluationHelper.equals( dataType, "DWORD" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # DWORD - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, "DWORD" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 32 - if EvaluationHelper.equals( dataType, "LWORD" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # LWORD - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, "LWORD" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 64 - if EvaluationHelper.equals( dataType, "SINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # SINT - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, "SINT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 8 - if EvaluationHelper.equals( dataType, "INT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # INT - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, "INT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 16 - if EvaluationHelper.equals( dataType, "DINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # DINT - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, "DINT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 32 - if EvaluationHelper.equals( dataType, "LINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # LINT - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, "LINT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 64 - if EvaluationHelper.equals( dataType, "USINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # USINT - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, "USINT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 8 - if EvaluationHelper.equals( dataType, "UINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # UINT - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, "UINT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 16 - if EvaluationHelper.equals( dataType, "UDINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # UDINT - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, "UDINT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 32 - if EvaluationHelper.equals( dataType, "ULINT" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # ULINT - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, "ULINT" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 64 - if EvaluationHelper.equals( dataType, "REAL" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # REAL - # Simple Field (value) - sizeInBits += 32 - if EvaluationHelper.equals( dataType, "REAL" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 32 - if EvaluationHelper.equals( dataType, "LREAL" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # LREAL - # Simple Field (value) - sizeInBits += 64 - if EvaluationHelper.equals( dataType, "LREAL" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 64 - if EvaluationHelper.equals( dataType, "CHAR" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # CHAR - # Simple Field (value) - sizeInBits += 8 - if EvaluationHelper.equals( dataType, "CHAR" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 8 - if EvaluationHelper.equals( dataType, "WCHAR" ) and EvaluationHelper.equals( numberOfValues, int(1) ): # WCHAR - # Simple Field (value) - sizeInBits += 16 - if EvaluationHelper.equals( dataType, "WCHAR" ): # List - values: PlcList = _value - sizeInBits += values.getList().size() * 16 - if EvaluationHelper.equals( dataType, "STRING" ): # STRING - # Simple Field (value) - sizeInBits += 255 - if EvaluationHelper.equals( dataType, "WSTRING" ): # STRING - # Simple Field (value) - sizeInBits += 255 - return sizeInBits - - - - + def get_length_in_bits( + _value: PlcValue, data_type: str, number_of_values: int + ) -> int: + size_in_bits: int = 0 + if data_type == "BOOL" and number_of_values == int(1): # BOOL + # Simple Field (value) + size_in_bits += 1 + if data_type == "BOOL": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 1 + if data_type == "BYTE" and number_of_values == int(1): # BYTE + # Simple Field (value) + size_in_bits += 8 + if data_type == "BYTE": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 8 + if data_type == "WORD" and number_of_values == int(1): # WORD + # Simple Field (value) + size_in_bits += 16 + if data_type == "WORD": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 16 + if data_type == "DWORD" and number_of_values == int(1): # DWORD + # Simple Field (value) + size_in_bits += 32 + if data_type == "DWORD": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 32 + if data_type == "LWORD" and number_of_values == int(1): # LWORD + # Simple Field (value) + size_in_bits += 64 + if data_type == "LWORD": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 64 + if data_type == "SINT" and number_of_values == int(1): # SINT + # Simple Field (value) + size_in_bits += 8 + if data_type == "SINT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 8 + if data_type == "INT" and number_of_values == int(1): # INT + # Simple Field (value) + size_in_bits += 16 + if data_type == "INT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 16 + if data_type == "DINT" and number_of_values == int(1): # DINT + # Simple Field (value) + size_in_bits += 32 + if data_type == "DINT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 32 + if data_type == "LINT" and number_of_values == int(1): # LINT + # Simple Field (value) + size_in_bits += 64 + if data_type == "LINT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 64 + if data_type == "USINT" and number_of_values == int(1): # USINT + # Simple Field (value) + size_in_bits += 8 + if data_type == "USINT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 8 + if data_type == "UINT" and number_of_values == int(1): # UINT + # Simple Field (value) + size_in_bits += 16 + if data_type == "UINT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 16 + if data_type == "UDINT" and number_of_values == int(1): # UDINT + # Simple Field (value) + size_in_bits += 32 + if data_type == "UDINT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 32 + if data_type == "ULINT" and number_of_values == int(1): # ULINT + # Simple Field (value) + size_in_bits += 64 + if data_type == "ULINT": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 64 + if data_type == "REAL" and number_of_values == int(1): # REAL + # Simple Field (value) + size_in_bits += 32 + if data_type == "REAL": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 32 + if data_type == "LREAL" and number_of_values == int(1): # LREAL + # Simple Field (value) + size_in_bits += 64 + if data_type == "LREAL": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 64 + if data_type == "CHAR" and number_of_values == int(1): # CHAR + # Simple Field (value) + size_in_bits += 8 + if data_type == "CHAR": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 8 + if data_type == "WCHAR" and number_of_values == int(1): # WCHAR + # Simple Field (value) + size_in_bits += 16 + if data_type == "WCHAR": # List + values: PlcList = _value + size_in_bits += len(values.get_list()) * 16 + if data_type == "STRING": # STRING + # Simple Field (value) + size_in_bits += 255 + if data_type == "WSTRING": # STRING + # Simple Field (value) + size_in_bits += 255 + return size_in_bits diff --git a/sandbox/plc4py/plc4py/protocols/simulated/readwrite/Dummy.py b/sandbox/plc4py/plc4py/protocols/simulated/readwrite/Dummy.py index 3d67068ed3d..4b6d9d371f8 100644 --- a/sandbox/plc4py/plc4py/protocols/simulated/readwrite/Dummy.py +++ b/sandbox/plc4py/plc4py/protocols/simulated/readwrite/Dummy.py @@ -19,20 +19,18 @@ from dataclasses import dataclass +from plc4py.api.exceptions.exceptions import PlcRuntimeException +from plc4py.api.exceptions.exceptions import SerializationException from plc4py.api.messages.PlcMessage import PlcMessage from plc4py.spi.generation.ReadBuffer import ReadBuffer from plc4py.spi.generation.WriteBuffer import WriteBuffer +from plc4py.utils.GenericTypes import ByteOrder import math - -@dataclass -class Dummy(PlcMessage): - dummy: int - - - def __post_init__(self): - super().__init__( ) +@dataclass +class Dummy: + dummy: int def serialize(self, write_buffer: WriteBuffer): write_buffer.push_context("Dummy") @@ -42,11 +40,10 @@ def serialize(self, write_buffer: WriteBuffer): write_buffer.pop_context("Dummy") - def length_in_bytes(self) -> int: - return int(math.ceil(float(self.get_length_in_bits() / 8.0))) + return int(math.ceil(float(self.length_in_bits() / 8.0))) - def get_length_in_bits(self) -> int: + def length_in_bits(self) -> int: length_in_bits: int = 0 _value: Dummy = self @@ -55,23 +52,23 @@ def get_length_in_bits(self) -> int: return length_in_bits - - def static_parse(self, read_buffer: ReadBuffer , args): - return self.static_parse_context(read_buffer) - + @staticmethod + def static_parse(read_buffer: ReadBuffer, **kwargs): + return Dummy.static_parse_context(read_buffer) @staticmethod def static_parse_context(read_buffer: ReadBuffer): read_buffer.push_context("Dummy") - self.dummy= read_simple_field("dummy", read_unsigned_int, WithOption.WithByteOrder(get_bi_g__endian())) + dummy: int = read_buffer.read_unsigned_short( + logical_name="dummy", bit_length=16, byte_order=ByteOrder.BIG_ENDIAN + ) read_buffer.pop_context("Dummy") # Create the instance - _dummy: Dummy = Dummy(dummy ) + _dummy: Dummy = Dummy(dummy) return _dummy - def equals(self, o: object) -> bool: if self == o: return True @@ -86,14 +83,11 @@ def hash_code(self) -> int: return hash(self) def __str__(self) -> str: - write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) - try: - write_buffer_box_based.writeSerializable(self) - except SerializationException as e: - raise RuntimeException(e) - - return "\n" + str(write_buffer_box_based.get_box()) + "\n" - - - - + pass + # write_buffer_box_based: WriteBufferBoxBased = WriteBufferBoxBased(True, True) + # try: + # write_buffer_box_based.writeSerializable(self) + # except SerializationException as e: + # raise PlcRuntimeException(e) + + # return "\n" + str(write_buffer_box_based.get_box()) + "\n" diff --git a/sandbox/plc4py/plc4py/protocols/simulated/readwrite/SimulatedDataTypeSizes.py b/sandbox/plc4py/plc4py/protocols/simulated/readwrite/SimulatedDataTypeSizes.py index ffc38bb79cb..9c391b4351e 100644 --- a/sandbox/plc4py/plc4py/protocols/simulated/readwrite/SimulatedDataTypeSizes.py +++ b/sandbox/plc4py/plc4py/protocols/simulated/readwrite/SimulatedDataTypeSizes.py @@ -18,42 +18,35 @@ # # Code generated by code-generation. DO NOT EDIT. -from enum import IntEnum - -class SimulatedDataTypeSizes(IntEnum): - BOOL: int = (1 , int(1) ) - BYTE: int = (2 , int(1) ) - WORD: int = (3 , int(2) ) - DWORD: int = (4 , int(4) ) - LWORD: int = (5 , int(8) ) - SINT: int = (6 , int(1) ) - INT: int = (7 , int(2) ) - DINT: int = (8 , int(4) ) - LINT: int = (9 , int(8) ) - USINT: int = (10 , int(1) ) - UINT: int = (11 , int(2) ) - UDINT: int = (12 , int(4) ) - ULINT: int = (13 , int(8) ) - REAL: int = (14 , int(4) ) - LREAL: int = (15 , int(8) ) - TIME: int = (16 , int(8) ) - LTIME: int = (17 , int(8) ) - DATE: int = (18 , int(8) ) - LDATE: int = (19 , int(8) ) - TIME_OF_DAY: int = (20 , int(8) ) - LTIME_OF_DAY: int = (21 , int(8) ) - DATE_AND_TIME: int = (22 , int(8) ) - LDATE_AND_TIME: int = (23 , int(8) ) - CHAR: int = (24 , int(1) ) - WCHAR: int = (25 , int(2) ) - STRING: int = (26 , int(255) ) - WSTRING: int = (27 , int(127) ) - - def __new__(cls, value, data_type_size ): - obj = object.__new__(cls) - obj._value_ = value - obj.dataTypeSize = dataTypeSize - return obj - +from aenum import AutoNumberEnum +class SimulatedDataTypeSizes(AutoNumberEnum): + _init_ = "value, data_type_size" + BOOL = (1, int(1)) + BYTE = (2, int(1)) + WORD = (3, int(2)) + DWORD = (4, int(4)) + LWORD = (5, int(8)) + SINT = (6, int(1)) + INT = (7, int(2)) + DINT = (8, int(4)) + LINT = (9, int(8)) + USINT = (10, int(1)) + UINT = (11, int(2)) + UDINT = (12, int(4)) + ULINT = (13, int(8)) + REAL = (14, int(4)) + LREAL = (15, int(8)) + TIME = (16, int(8)) + LTIME = (17, int(8)) + DATE = (18, int(8)) + LDATE = (19, int(8)) + TIME_OF_DAY = (20, int(8)) + LTIME_OF_DAY = (21, int(8)) + DATE_AND_TIME = (22, int(8)) + LDATE_AND_TIME = (23, int(8)) + CHAR = (24, int(1)) + WCHAR = (25, int(2)) + STRING = (26, int(255)) + WSTRING = (27, int(127)) diff --git a/sandbox/plc4py/plc4py/spi/generation/ReadBuffer.py b/sandbox/plc4py/plc4py/spi/generation/ReadBuffer.py index aaec45dfd64..c781d755ca8 100644 --- a/sandbox/plc4py/plc4py/spi/generation/ReadBuffer.py +++ b/sandbox/plc4py/plc4py/spi/generation/ReadBuffer.py @@ -15,6 +15,7 @@ # specific language governing permissions and limitations # under the License. import struct +import types from ctypes import ( c_byte, c_ubyte, @@ -30,8 +31,9 @@ c_uint8, ) from dataclasses import dataclass -from typing import List, Union +from typing import List, Union, Any +import aenum from bitarray import bitarray from bitarray.util import zeros, ba2int, ba2base @@ -119,7 +121,15 @@ def read_str(self, bit_length: int = -1, logical_name: str = "", **kwargs) -> st def read_virtual(self, logical_name: str = "", **kwargs) -> str: raise NotImplementedError - def read_complex_array(self, logical_name: str = "", **kwargs) -> List[PlcMessage]: + def read_complex_array(self, logical_name: str = "", **kwargs) -> List[Any]: + raise NotImplementedError + + def read_complex(self, logical_name: str = "", read_function=None, **kwargs) -> Any: + raise NotImplementedError + + def read_enum( + self, bit_length: int = -1, logical_name: str = "", read_function=None, **kwargs + ) -> Any: raise NotImplementedError def read_array_field( @@ -130,15 +140,11 @@ def read_array_field( length: int = None, terminated=None, **kwargs - ) -> List[PlcMessage]: + ) -> List[Any]: raise NotImplementedError class ReadBufferByteBased(ReadBuffer): - byte_order: ByteOrder - position: int = 0 - bb: bitarray - NUMERIC_UNION = Union[ c_ubyte, c_byte, @@ -162,6 +168,7 @@ def __init__(self, bb: bytearray, byte_order: ByteOrder): buffer=memoryview(bb), endian=ByteOrder.get_short_name(byte_order) ) self.byte_order = byte_order + self.position = 0 def get_bytes(self) -> memoryview: return memoryview(self.bb) @@ -173,6 +180,9 @@ def push_context(self, logical_name: str, **kwargs) -> None: # byte buffer need no context handling pass + def pop_context(self, logical_name: str, **kwargs) -> None: + pass + def read_bit(self, logical_name: str = "", **kwargs) -> bool: result: bool = bool(self.bb[self.position]) self.position += 1 @@ -199,7 +209,9 @@ def read_unsigned_byte( elif bit_length > 8: raise SerializationException("unsigned byte can only contain max 8 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -212,7 +224,9 @@ def read_unsigned_short( elif bit_length > 16: raise SerializationException("unsigned short can only contain max 16 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -225,7 +239,10 @@ def read_unsigned_int( elif bit_length > 32: raise SerializationException("unsigned int can only contain max 32 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + ss = self.bb[self.position : bit_length] + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -238,7 +255,9 @@ def read_unsigned_long( elif bit_length > 64: raise SerializationException("unsigned long can only contain max 64 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -251,7 +270,9 @@ def read_signed_byte( elif bit_length > 8: raise SerializationException("signed byte can only contain max 8 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -262,7 +283,9 @@ def read_short(self, bit_length: int = 16, logical_name: str = "", **kwargs) -> elif bit_length > 16: raise SerializationException("signed short can only contain max 16 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -273,7 +296,9 @@ def read_int(self, bit_length: int = 32, logical_name: str = "", **kwargs) -> in elif bit_length > 32: raise SerializationException("signed int can only contain max 32 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -284,7 +309,9 @@ def read_long(self, bit_length: int = 64, logical_name: str = "", **kwargs) -> i elif bit_length > 64: raise SerializationException("signed long can only contain max 64 bits") else: - result: int = ba2int(self.bb[self.position : bit_length], signed=False) + result: int = ba2int( + self.bb[self.position : self.position + bit_length], signed=False + ) self.position += bit_length return result @@ -299,7 +326,7 @@ def read_float( if byte_order == ByteOrder.LITTLE_ENDIAN: endianness = "<" result: float = struct.unpack( - endianness + "f", self.bb[self.position : bit_length] + endianness + "f", self.bb[self.position : self.position + bit_length] )[0] self.position += bit_length return result @@ -315,7 +342,38 @@ def read_double( if byte_order == ByteOrder.LITTLE_ENDIAN: endianness = "<" result: float = struct.unpack( - endianness + "d", self.bb[self.position : bit_length] + endianness + "d", self.bb[self.position : self.position + bit_length] )[0] self.position += bit_length return result + + def read_complex(self, logical_name: str = "", read_function=None, **kwargs) -> Any: + if isinstance(read_function, types.FunctionType): + return read_function(self, **kwargs) + pass + + def read_enum( + self, bit_length: int = -1, logical_name: str = "", read_function=None, **kwargs + ) -> Any: + if isinstance(read_function, aenum._enum.EnumType): + enum_return_value = read_function(ba2int(self.bb[self.position : self.position + bit_length], signed=False)) + return enum_return_value + else: + raise RuntimeError("read_enum called but read_function wasn't an enum") + + def read_array_field( + self, + logical_name: str = "", + read_function=None, + count: int = None, + length: int = None, + terminated=None, + **kwargs + ) -> List[Any]: + if count is not None: + parsed_array = [] + for i in range(count): + parsed_array.append(read_function(self, **kwargs)) + return parsed_array + else: + raise NotImplementedError diff --git a/sandbox/plc4py/plc4py/spi/generation/WriteBuffer.py b/sandbox/plc4py/plc4py/spi/generation/WriteBuffer.py index f6b7cc92c66..0222fd9cda0 100644 --- a/sandbox/plc4py/plc4py/spi/generation/WriteBuffer.py +++ b/sandbox/plc4py/plc4py/spi/generation/WriteBuffer.py @@ -14,6 +14,8 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +import struct +from abc import ABCMeta from ctypes import ( c_byte, c_ubyte, @@ -119,7 +121,12 @@ def write_double( raise NotImplementedError def write_str( - self, value: str, bit_length: int = -1, logical_name: str = "", **kwargs + self, + value: str, + bit_length: int = -1, + logical_name: str = "", + encoding: str = "UTF-8", + **kwargs ) -> None: raise NotImplementedError @@ -141,11 +148,7 @@ def write_serializable(self, value, logical_name="") -> None: value.serialize(self) -class WriteBufferByteBased(WriteBuffer): - byte_order: ByteOrder - position: int = 0 - bb: bitarray - +class WriteBufferByteBased(WriteBuffer, metaclass=ABCMeta): NUMERIC_UNION = Union[ c_ubyte, c_byte, @@ -162,8 +165,10 @@ class WriteBufferByteBased(WriteBuffer): ] def __init__(self, size: int, byte_order: ByteOrder): - self.bb = zeros(size * 8, endian=ByteOrder.get_short_name(byte_order)) + # This refers to the bit alignment, which we always use big bit endianess + self.bb = zeros(size * 8, endian=ByteOrder.get_short_name(ByteOrder.BIG_ENDIAN)) self.byte_order = byte_order + self.position: int = 0 def get_bytes(self) -> memoryview: return memoryview(self.bb) @@ -175,6 +180,9 @@ def push_context(self, logical_name: str, **kwargs) -> None: # byte buffer need no context handling pass + def pop_context(self, logical_name: str, **kwargs) -> None: + pass + def write_bit(self, value: bool, logical_name: str = "", **kwargs) -> None: self.bb[self.position] = value self.position += 1 @@ -206,6 +214,10 @@ def write_unsigned_short( elif bit_length > 16: raise SerializationException("unsigned short can only contain max 16 bits") else: + if self.byte_order == ByteOrder.LITTLE_ENDIAN: + value = struct.unpack("H", struct.pack("H", value))[0] self._handle_numeric_encoding(c_uint16(value), bit_length, **kwargs) def write_unsigned_int( @@ -291,29 +303,20 @@ def write_complex_array( self.pop_context(logical_name, **kwargs) def _handle_numeric_encoding(self, value: NUMERIC_UNION, bit_length: int, **kwargs): - byte_order = kwargs.get("byte_order", self.byte_order) + bit_order = kwargs.get("bit_order", ByteOrder.BIG_ENDIAN) value_encoding: str = kwargs.get("encoding", "default") if value_encoding == "ASCII": if bit_length % 8 != 0: raise SerializationException( "'ASCII' encoded fields must have a length that is a multiple of 8 bits long" ) - char_len: int = int(bit_length / 8) - max_value: int = int(10**char_len - 1) - if value.value > max_value: - raise SerializationException( - "Provided value of " - + str(value) - + " exceeds the max value of " - + str(max_value) - ) string_value: str = "{}".format(value.value) - src = bitarray(endian=ByteOrder.get_short_name(byte_order)) + src = bitarray(endian=ByteOrder.get_short_name(bit_order)) src.frombytes(bytearray(string_value, value_encoding)) - self.bb[self.position : bit_length] = src[:bit_length] + self.bb[self.position : self.position + bit_length] = src[:bit_length] self.position += bit_length elif value_encoding == "default": - src = bitarray(endian=ByteOrder.get_short_name(byte_order)) + src = bitarray(endian=ByteOrder.get_short_name(bit_order)) src.frombytes(value) - self.bb[self.position : bit_length] = src[:bit_length] + self.bb[self.position : self.position + bit_length] = src[-bit_length:] self.position += bit_length diff --git a/sandbox/plc4py/plc4py/spi/values/PlcINT.py b/sandbox/plc4py/plc4py/spi/messages/PlcRequest.py similarity index 54% rename from sandbox/plc4py/plc4py/spi/values/PlcINT.py rename to sandbox/plc4py/plc4py/spi/messages/PlcRequest.py index 38f628414ad..c02f9dd6aed 100644 --- a/sandbox/plc4py/plc4py/spi/values/PlcINT.py +++ b/sandbox/plc4py/plc4py/spi/messages/PlcRequest.py @@ -16,12 +16,28 @@ # specific language governing permissions and limitations # under the License. # -from dataclasses import dataclass -from plc4py.api.value.PlcValue import PlcValue +from plc4py.api.messages.PlcRequest import ( + PlcReadRequest, + ReadRequestBuilder, +) -@dataclass -class PlcINT(PlcValue[int]): - def get_int(self): - return self.value +class TagBuilder: + @staticmethod + def create(address_string: str): + raise NotImplementedError + + +class DefaultReadRequestBuilder(ReadRequestBuilder): + def __init__(self, tag_builder: TagBuilder): + super().__init__() + self.read_request = PlcReadRequest() + self.tag_builder = tag_builder + + def build(self) -> PlcReadRequest: + return self.read_request + + def add_item(self, tag_name: str, address_string: str) -> None: + tag = self.tag_builder.create(address_string) + self.read_request.tags[tag_name] = tag diff --git a/sandbox/plc4py/plc4py/spi/values/PlcValues.py b/sandbox/plc4py/plc4py/spi/values/PlcValues.py new file mode 100644 index 00000000000..3744b805a60 --- /dev/null +++ b/sandbox/plc4py/plc4py/spi/values/PlcValues.py @@ -0,0 +1,182 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +from dataclasses import dataclass +from typing import List, Any, Dict + +from plc4py.api.value.PlcValue import PlcValue + + +@dataclass +class PlcINT(PlcValue[int]): + pass + + +@dataclass +class PlcBYTE(PlcValue[int]): + pass + + +@dataclass +class PlcCHAR(PlcValue[str]): + pass + + +@dataclass +class PlcDATE(PlcValue[int]): + pass + + +@dataclass +class PlcDATE_AND_TIME(PlcValue[int]): + pass + + +@dataclass +class PlcDINT(PlcValue[int]): + pass + + +@dataclass +class PlcDWORD(PlcValue[int]): + pass + + +@dataclass +class PlcLDATE(PlcValue[int]): + pass + + +@dataclass +class PlcLDATE_AND_TIME(PlcValue[int]): + pass + + +@dataclass +class PlcLINT(PlcValue[int]): + pass + + +@dataclass +class PlcList(PlcValue[List[Any]]): + pass + + +@dataclass +class PlcLREAL(PlcValue[float]): + pass + + +@dataclass +class PlcLTIME(PlcValue[int]): + pass + + +@dataclass +class PlcLTIME_OF_DAY(PlcValue[int]): + pass + + +@dataclass +class PlcLWORD(PlcValue[int]): + pass + + +@dataclass +class PlcNull(PlcValue[None]): + pass + + +@dataclass +class PlcRawByteArray(List[PlcValue[Any]]): + pass + + +@dataclass +class PlcREAL(PlcValue[float]): + pass + + +@dataclass +class PlcSINT(PlcValue[int]): + pass + + +@dataclass +class PlcSTRING(PlcValue[str]): + pass + + +@dataclass +class PlcStruct(PlcValue[Dict[str, PlcValue[str]]]): + pass + + +@dataclass +class PlcTIME(PlcValue[int]): + pass + + +@dataclass +class PlcTIME_OF_DAY(PlcValue[int]): + pass + + +@dataclass +class PlcUBINT(PlcValue[int]): + pass + + +@dataclass +class PlcUDINT(PlcValue[int]): + pass + + +@dataclass +class PlcUINT(PlcValue[int]): + pass + + +@dataclass +class PlcULINT(PlcValue[int]): + pass + + +@dataclass +class PlcUSINT(PlcValue[int]): + pass + + +@dataclass +class PlcWCHAR(PlcValue[str]): + pass + + +@dataclass +class PlcWORD(PlcValue[int]): + pass + + +@dataclass +class PlcWSTRING(PlcValue[str]): + pass + + +@dataclass +class PlcBOOL(PlcValue[bool]): + pass diff --git a/sandbox/plc4py/plc4py/utils/GenericTypes.py b/sandbox/plc4py/plc4py/utils/GenericTypes.py index c1fb8ed5e12..e4f1aa19c20 100644 --- a/sandbox/plc4py/plc4py/utils/GenericTypes.py +++ b/sandbox/plc4py/plc4py/utils/GenericTypes.py @@ -16,6 +16,7 @@ # specific language governing permissions and limitations # under the License. # +import threading from dataclasses import dataclass from enum import Enum, auto from typing import Generator @@ -60,3 +61,23 @@ def get_short_name(order): @dataclass class ByteOrderAware: byte_order: ByteOrder + + +class AtomicInteger: + def __init__(self, seed=0): + self._value = seed + self._lock = threading.Lock() + + def increment(self, num=1): + with self._lock: + self._value += num + return self._value + + def decrement(self, num=1): + with self._lock: + self._value -= num + return self._value + + @property + def value(self): + return self._value diff --git a/sandbox/plc4py/pom.xml b/sandbox/plc4py/pom.xml index 8459d6b3c30..c42bf77715f 100644 --- a/sandbox/plc4py/pom.xml +++ b/sandbox/plc4py/pom.xml @@ -40,6 +40,74 @@ OFF + + + update-generated-code + + + + org.apache.plc4x.plugins + plc4x-maven-plugin + + + generate-modbus-driver + generate-sources + + generate-driver + + + modbus + python + read-write + ${project.basedir}/plc4py/protocols + + + + generate-simulated-driver + generate-sources + + generate-driver + + + simulated + python + read-write + ${project.basedir}/plc4py/protocols + + + + + + + + + + org.apache.plc4x + plc4x-code-generation-language-python + 0.12.0-SNAPSHOT + + provided + + + + org.apache.plc4x + plc4x-protocols-modbus + 0.12.0-SNAPSHOT + + provided + + + + org.apache.plc4x + plc4x-protocols-simulated + 0.12.0-SNAPSHOT + + provided + + + + + src/main/python src/test/python @@ -79,7 +147,7 @@ python-venv - generate-sources + initialize exec @@ -95,7 +163,7 @@ python-upgrade-pip - generate-sources + initialize exec @@ -113,7 +181,7 @@ python-install - generate-sources + initialize exec @@ -128,7 +196,7 @@ python-black - generate-sources + process-sources exec @@ -224,72 +292,6 @@ - - - update-generated-code - - - - org.apache.plc4x.plugins - plc4x-maven-plugin - - - generate-modbus-driver - generate-sources - - generate-driver - - - modbus - python - read-write - ${project.basedir}/plc4py/protocols - - - - generate-simulated-driver - generate-sources - - generate-driver - - - simulated - python - read-write - ${project.basedir}/plc4py/protocols - - - - - - - - - org.apache.plc4x - plc4x-code-generation-language-python - 0.12.0-SNAPSHOT - - provided - - - - org.apache.plc4x - plc4x-protocols-modbus - 0.12.0-SNAPSHOT - - provided - - - - org.apache.plc4x - plc4x-protocols-simulated - 0.12.0-SNAPSHOT - - provided - - - - diff --git a/sandbox/plc4py/setup.py b/sandbox/plc4py/setup.py index 8a7416a31e9..d4853fbcf0c 100644 --- a/sandbox/plc4py/setup.py +++ b/sandbox/plc4py/setup.py @@ -25,7 +25,7 @@ description="Plc4py The Python Industrial IOT Adapter", classifiers=[ "Development Status :: 3 - Alpha", - "License :: OSI Approved :: Apache 2.0 License", + "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator", ], diff --git a/sandbox/plc4py/tests/test_plc4py.py b/sandbox/plc4py/tests/test_plc4py.py index a8ef3cb8b28..f53bf155038 100644 --- a/sandbox/plc4py/tests/test_plc4py.py +++ b/sandbox/plc4py/tests/test_plc4py.py @@ -21,7 +21,7 @@ from plc4py import __version__ from plc4py.PlcDriverManager import PlcDriverManager from plc4py.api.PlcConnection import PlcConnection -from plc4py.api.messages.PlcRequest import PlcFieldRequest +from plc4py.api.messages.PlcRequest import PlcTagRequest from plc4py.api.messages.PlcResponse import PlcReadResponse from plc4py.api.value.PlcValue import PlcResponseCode from plc4py.drivers.mock.MockConnection import MockConnection @@ -52,12 +52,12 @@ async def test_plc_driver_manager_init_mock(): async def test_plc_driver_manager_init_mock_read_request(): driver_manager = PlcDriverManager() - field = "1:BOOL" + tag = "1:BOOL" async with driver_manager.connection("mock:tcp://127.0.0.1:502") as connection: with connection.read_request_builder() as builder: - builder.add_item(field) - request: PlcFieldRequest = builder.build() + builder.add_item("Random Tag", tag) + request: PlcTagRequest = builder.build() response: PlcReadResponse = cast( PlcReadResponse, await connection.execute(request) ) diff --git a/sandbox/plc4py/tests/unit/plc4py/api/test_PlcRequest.py b/sandbox/plc4py/tests/unit/plc4py/api/test_PlcRequest.py index 2ae1caa80e5..8a64dcf507e 100644 --- a/sandbox/plc4py/tests/unit/plc4py/api/test_PlcRequest.py +++ b/sandbox/plc4py/tests/unit/plc4py/api/test_PlcRequest.py @@ -21,15 +21,15 @@ import pytest from plc4py.api.PlcConnection import PlcConnection -from plc4py.api.messages.PlcField import PlcField +from plc4py.api.messages.PlcField import PlcTag from plc4py.api.messages.PlcRequest import ( - PlcFieldRequest, + PlcTagRequest, ) from plc4py.api.messages.PlcResponse import PlcReadResponse from plc4py.api.value.PlcValue import PlcResponseCode from plc4py.spi.messages.utils.ResponseItem import ResponseItem -from plc4py.spi.values.PlcBOOL import PlcBOOL -from plc4py.spi.values.PlcINT import PlcINT +from plc4py.spi.values.PlcValues import PlcBOOL +from plc4py.spi.values.PlcValues import PlcINT from plc4py.drivers.mock.MockConnection import MockConnection @@ -44,8 +44,8 @@ def test_read_request_builder_empty_request(mocker) -> None: # the connection function is supposed to support context manager # so using it in a with statement should result in close being called on the connection with connection.read_request_builder() as builder: - request: PlcFieldRequest = builder.build() - assert len(request.field_names) == 0 + request: PlcTagRequest = builder.build() + assert len(request.tag_names) == 0 def test_read_request_builder_non_empty_request(mocker) -> None: @@ -59,12 +59,12 @@ def test_read_request_builder_non_empty_request(mocker) -> None: # the connection function is supposed to support context manager # so using it in a with statement should result in close being called on the connection with connection.read_request_builder() as builder: - builder.add_item("1:BOOL") - request: PlcFieldRequest = builder.build() + builder.add_item("Random Tag", "1:BOOL") + request: PlcTagRequest = builder.build() # verify that request has one field - assert request.field_names == ["1:BOOL"] - assert len(request.field_names) == 1 + assert request.tag_names == ["Random Tag"] + assert len(request.tag_names) == 1 @pytest.mark.asyncio @@ -79,8 +79,8 @@ async def test_read_request_builder_non_empty_request_not_connected(mocker) -> N # the connection function is supposed to support context manager # so using it in a with statement should result in close being called on the connection with connection.read_request_builder() as builder: - builder.add_item("1:BOOL") - request: PlcFieldRequest = builder.build() + builder.add_item("Random Tag", "1:BOOL") + request: PlcTagRequest = builder.build() response = await connection.execute(request) # verify that request has one field @@ -95,13 +95,13 @@ async def test_read_request_builder_non_empty_request_connected_bool(mocker) -> :return: """ connection: PlcConnection = await MockConnection.create("mock://localhost") - field = "1:BOOL" + tag = "1:BOOL" # the connection function is supposed to support context manager # so using it in a with statement should result in close being called on the connection with connection.read_request_builder() as builder: - builder.add_item(field) - request: PlcFieldRequest = builder.build() + builder.add_item("Random Tag", tag) + request: PlcTagRequest = builder.build() response: PlcReadResponse = cast( PlcReadResponse, await connection.execute(request) ) @@ -109,7 +109,7 @@ async def test_read_request_builder_non_empty_request_connected_bool(mocker) -> # verify that request has one field assert response.code == PlcResponseCode.OK - value = response.values[field][0].value + value = response.values["Random Tag"][0].value assert not value.get_bool() @@ -121,13 +121,13 @@ async def test_read_request_builder_non_empty_request_connected_int(mocker) -> N :return: """ connection: PlcConnection = await MockConnection.create("mock://localhost") - field = "1:INT" + tag = "1:INT" # the connection function is supposed to support context manager # so using it in a with statement should result in close being called on the connection with connection.read_request_builder() as builder: - builder.add_item(field) - request: PlcFieldRequest = builder.build() + builder.add_item("Random Tag", tag) + request: PlcTagRequest = builder.build() response: PlcReadResponse = cast( PlcReadResponse, await connection.execute(request) ) @@ -135,7 +135,7 @@ async def test_read_request_builder_non_empty_request_connected_int(mocker) -> N # verify that request has one field assert response.code == PlcResponseCode.OK - value = response.values[field][0].value + value = response.values["Random Tag"][0].value assert value.get_int() == 0 @@ -147,7 +147,6 @@ def test_read_response_boolean_response(mocker) -> None: """ response = PlcReadResponse( PlcResponseCode.OK, - [PlcField("1:BOOL")], {"1:BOOL": [ResponseItem(PlcResponseCode.OK, PlcBOOL(True))]}, ) assert response.get_boolean("1:BOOL") @@ -162,7 +161,6 @@ def test_read_response_int_response(mocker) -> None: """ response = PlcReadResponse( PlcResponseCode.OK, - [PlcField("1:INT")], {"1:INT": [ResponseItem(PlcResponseCode.OK, PlcINT(10))]}, ) assert response.get_int("1:INT") == 10 diff --git a/sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_codegen.py b/sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_codegen.py new file mode 100644 index 00000000000..70d9040e9e9 --- /dev/null +++ b/sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_codegen.py @@ -0,0 +1,55 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +from plc4py.protocols.modbus.readwrite.ModbusTcpADU import ModbusTcpADUBuilder +from plc4py.spi.generation.WriteBuffer import WriteBufferByteBased + +from plc4py.protocols.modbus.readwrite.ModbusPDUReadDiscreteInputsRequest import ( + ModbusPDUReadDiscreteInputsRequestBuilder, +) +from plc4py.utils.GenericTypes import ByteOrder + + +async def test_modbus_discrete_inputs_request(): + request = ModbusPDUReadDiscreteInputsRequestBuilder(0, 10).build() + assert request is not None + + +async def test_modbus_discrete_inputs_request_serialize(): + request = ModbusPDUReadDiscreteInputsRequestBuilder(5, 2).build() + size = request.length_in_bytes() + write_buffer = WriteBufferByteBased(size, ByteOrder.BIG_ENDIAN) + serialize = request.serialize(write_buffer) + bytes_array = write_buffer.get_bytes().tobytes() + + assert request is not None + assert len(write_buffer.get_bytes()) * 8 == 40 + assert write_buffer.get_pos() == 40 + assert write_buffer.get_bytes().tobytes() == b"\x02\x00\x05\x00\x02" + + +async def test_modbus_ModbusTcpADUBuilder_serialize(): + pdu = ModbusPDUReadDiscreteInputsRequestBuilder(5, 2).build() + request = ModbusTcpADUBuilder(10, 5, pdu).build(False) + size = request.length_in_bytes() + write_buffer = WriteBufferByteBased(size, ByteOrder.BIG_ENDIAN) + serialize = request.serialize(write_buffer) + bytes_array = write_buffer.get_bytes().tobytes() + + assert request is not None diff --git a/sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py b/sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py index 295b9ee539d..6fb88312b71 100644 --- a/sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py +++ b/sandbox/plc4py/tests/unit/plc4py/drivers/modbus/test_modbus_connection.py @@ -16,14 +16,26 @@ # specific language governing permissions and limitations # under the License. # - +import time from plc4py.PlcDriverManager import PlcDriverManager async def manual_test_plc_driver_modbus_connect(): driver_manager = PlcDriverManager() - async with driver_manager.connection("modbus://127.0.0.1:502") as connection: + async with driver_manager.connection("modbus://127.0.0.1:5555") as connection: assert connection.is_connected() - assert not connection.is_connected() + + +async def manual_test_plc_driver_modbus_read(): + driver_manager = PlcDriverManager() + async with driver_manager.connection("modbus://127.0.0.1:5555") as connection: + with connection.read_request_builder() as builder: + builder.add_item("Random Tag", "4x00001[10]") + request = builder.build() + + future = connection.execute(request) + await future + response = future.result() + pass diff --git a/sandbox/plc4py/tests/unit/plc4py/spi/test_write_buffer.py b/sandbox/plc4py/tests/unit/plc4py/spi/test_write_buffer.py index 3ece65a7ecb..b8bcbf47797 100644 --- a/sandbox/plc4py/tests/unit/plc4py/spi/test_write_buffer.py +++ b/sandbox/plc4py/tests/unit/plc4py/spi/test_write_buffer.py @@ -41,7 +41,7 @@ def test_write_buffer_set_bit_little_endian(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN) wb.write_bit(True) ba: memoryview = wb.get_bytes() - assert b"\x01" == ba.tobytes() + assert b"\x80" == ba.tobytes() def test_write_buffer_set_bit_big_endian(mocker) -> None: @@ -63,7 +63,7 @@ def test_write_buffer_set_bit_x2_little_endian(mocker) -> None: wb.write_bit(True) wb.write_bit(True) ba: memoryview = wb.get_bytes() - assert b"\x03" == ba.tobytes() + assert b"\xc0" == ba.tobytes() def test_write_buffer_set_bit_x2_big_endian(mocker) -> None: @@ -93,7 +93,7 @@ def test_write_buffer_set_unsigned_byte_little_endian(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN) wb.write_unsigned_byte(0x12, 8) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("01001000") + assert ba.obj == bitarray("00010010") def test_write_buffer_set_unsigned_byte_big_endian(mocker) -> None: @@ -107,28 +107,42 @@ def test_write_buffer_set_unsigned_byte_little_endian_niblet(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN) wb.write_unsigned_byte(0x12, 4) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("01000000") + assert ba.obj == bitarray("00100000") def test_write_buffer_set_unsigned_byte_big_endian_niblet(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.BIG_ENDIAN) wb.write_unsigned_byte(0x12, 4) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("00010000") + assert ba.obj == bitarray("00100000") def test_write_buffer_write_unsigned_short_little_endian(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.LITTLE_ENDIAN) wb.write_unsigned_short(0x12, 16) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("01001000 00000000", endian="little") + assert ba.obj == bitarray("00010010 00000000", endian="big") def test_write_buffer_write_unsigned_short_big_endian(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN) wb.write_unsigned_short(0x12, 16) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("00010010 00000000", endian="big") + assert ba.obj == bitarray("00000000 00010010", endian="big") + + +def test_write_buffer_write_unsigned_short_large_number_big_endian(mocker) -> None: + wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN) + wb.write_unsigned_short(0x1213, 16) + ba: memoryview = wb.get_bytes() + assert ba.obj == bitarray("00010010 00010011 ", endian="big") + + +def test_write_buffer_write_unsigned_short_large_number_little_endian(mocker) -> None: + wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.LITTLE_ENDIAN) + wb.write_unsigned_short(0x1213, 16) + ba: memoryview = wb.get_bytes() + assert ba.obj == bitarray("00010011 00010010", endian="big") def test_write_buffer_write_unsigned_short_little_endian_dual(mocker) -> None: @@ -136,7 +150,7 @@ def test_write_buffer_write_unsigned_short_little_endian_dual(mocker) -> None: wb.write_unsigned_short(0x12, 16) wb.write_unsigned_short(0x34, 16) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("01001000 00000000 00101100 00000000", endian="little") + assert ba.obj == bitarray("00010010 00000000 00110100 00000000", endian="big") def test_write_buffer_write_unsigned_short_big_endian_dual(mocker) -> None: @@ -144,12 +158,12 @@ def test_write_buffer_write_unsigned_short_big_endian_dual(mocker) -> None: wb.write_unsigned_short(0x12, 16) wb.write_unsigned_short(0x34, 16) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("00010010 00000000 00110100 00000000", endian="big") + assert ba.obj == bitarray("00000000 00010010 00000000 00110100", endian="big") def test_write_buffer_write_unsigned_short_big_endian_full(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN) - wb.write_unsigned_short(-1, 16) + wb.write_unsigned_short(0xFFFF, 16) ba: memoryview = wb.get_bytes() assert ba.obj == bitarray("11111111 11111111", endian="big") @@ -158,23 +172,23 @@ def test_write_buffer_write_unsigned_short_bit_big_endian_full(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN) wb.write_bit(True) wb.write_bit(False) - wb.write_unsigned_short(-1, 16) - ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("10 11111111 11111111", endian="big") - - -def test_write_buffer_write_unsigned_short_ascii_encoding_little_endian(mocker) -> None: - wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.LITTLE_ENDIAN) - wb.write_unsigned_short(1, 16, "ASCII Value of 1 - 0x31", encoding="ASCII") + wb.write_unsigned_short(0xFFFF, 14) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("10001100", endian="little") + assert ba.obj == bitarray("10111111 11111111", endian="big") -def test_write_buffer_write_unsigned_short_ascii_encoding_big_endian(mocker) -> None: - wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN) - wb.write_unsigned_short(1, 16, "ASCII Value of 1 - 0x31", encoding="ASCII") - ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("00110001", endian="big") +# def test_write_buffer_write_unsigned_short_ascii_encoding_little_endian(mocker) -> None: +# wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.LITTLE_ENDIAN) +# wb.write_unsigned_short(1, 16, "ASCII Value of 1 - 0x31", encoding="ASCII") +# ba: memoryview = wb.get_bytes() +# assert ba.obj == bitarray("00110001", endian="big") +# +# +# def test_write_buffer_write_unsigned_short_ascii_encoding_big_endian(mocker) -> None: +# wb: WriteBufferByteBased = WriteBufferByteBased(2, ByteOrder.BIG_ENDIAN) +# wb.write_unsigned_short(1, 16, "ASCII Value of 1 - 0x31", encoding="ASCII") +# ba: memoryview = wb.get_bytes() +# assert ba.obj == bitarray("00110001", endian="big") def test_write_buffer_write_unsigned_int_little_endian(mocker) -> None: @@ -182,7 +196,7 @@ def test_write_buffer_write_unsigned_int_little_endian(mocker) -> None: # Testing incompatible format being sent to it. wb.write_unsigned_int(0x12, 32) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("01001000 00000000 00000000 00000000", endian="little") + assert ba.obj == bitarray("00010010 00000000 00000000 00000000", endian="big") def test_write_buffer_write_unsigned_int_big_endian(mocker) -> None: @@ -198,8 +212,8 @@ def test_write_buffer_write_unsigned_long_little_endian(mocker) -> None: wb.write_unsigned_long(0x12, 64) ba: memoryview = wb.get_bytes() assert ba.obj == bitarray( - "01001000 00000000 00000000 00000000 00000000 00000000 00000000 00000000", - endian="little", + "00010010 00000000 00000000 00000000 00000000 00000000 00000000 00000000", + endian="big", ) @@ -213,55 +227,55 @@ def test_write_buffer_write_unsigned_long_big_endian(mocker) -> None: ) -def test_write_buffer_write_unsigned_long_ascii_encoding_little_endian(mocker) -> None: - wb: WriteBufferByteBased = WriteBufferByteBased(8, ByteOrder.LITTLE_ENDIAN) - wb.write_unsigned_long( - 11111111, - 64, - "ASCII Value of 1111 1111 - 0x3131313131313131", - encoding="ASCII", - ) - ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray( - "10001100 10001100 10001100 10001100 10001100 10001100 10001100 10001100", - endian="little", - ) - - -def test_write_buffer_write_unsigned_long_ascii_encoding_big_endian(mocker) -> None: - wb: WriteBufferByteBased = WriteBufferByteBased(8, ByteOrder.BIG_ENDIAN) - wb.write_unsigned_long( - 11111111, - 64, - "ASCII Value of 1111 1111 - 0x3131313131313131", - encoding="ASCII", - ) - ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray( - "00110001 00110001 00110001 00110001 00110001 00110001 00110001 00110001", - endian="big", - ) +# def test_write_buffer_write_unsigned_long_ascii_encoding_little_endian(mocker) -> None: +# wb: WriteBufferByteBased = WriteBufferByteBased(8, ByteOrder.LITTLE_ENDIAN) +# wb.write_unsigned_long( +# 11111111, +# 64, +# "ASCII Value of 1111 1111 - 0x3131313131313131", +# encoding="ASCII", +# ) +# ba: memoryview = wb.get_bytes() +# assert ba.obj == bitarray( +# "10001100 10001100 10001100 10001100 10001100 10001100 10001100 10001100", +# endian="little", +# ) + + +# def test_write_buffer_write_unsigned_long_ascii_encoding_big_endian(mocker) -> None: +# wb: WriteBufferByteBased = WriteBufferByteBased(8, ByteOrder.BIG_ENDIAN) +# wb.write_unsigned_long( +# 11111111, +# 64, +# "ASCII Value of 1111 1111 - 0x3131313131313131", +# encoding="ASCII", +# ) +# ba: memoryview = wb.get_bytes() +# assert ba.obj == bitarray( +# "00110001 00110001 00110001 00110001 00110001 00110001 00110001 00110001", +# endian="big", +# ) def test_write_buffer_set_signed_byte(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN) wb.write_signed_byte(-1, 8) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("11111111", endian="little") + assert ba.obj == bitarray("11111111", endian="big") def test_write_buffer_set_signed_byte_three(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN) wb.write_signed_byte(3, 8) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("11000000", endian="little") + assert ba.obj == bitarray("00000011", endian="big") def test_write_buffer_set_float_little_endian(mocker) -> None: wb: WriteBufferByteBased = WriteBufferByteBased(1, ByteOrder.LITTLE_ENDIAN) wb.write_float(-1, 32) ba: memoryview = wb.get_bytes() - assert ba.obj == bitarray("00000000000000000000000111111101", endian="little") + assert ba.obj == bitarray("00000000000000001000000010111111", endian="big") def test_write_buffer_set_float_big_endian(mocker) -> None: