internal static void Validate(WriteHoldingRegistersRequest request, RTUResponse response) { if (response.Data.Length < 4) { throw new RTUException("The Response Data Length of '" + response.Data.Length.ToString() + "' was too short - Expecting a Length of '4'"); } Memory <byte> bytes = response.Data.AsMemory(); Span <byte> addressBytes = bytes.Slice(0, 2).Span; addressBytes.Reverse(); ushort address = BitConverter.ToUInt16(addressBytes); if (address != request.Address) { throw new RTUException("The Response Address of '" + address.ToString() + "' did not match the Expected Address '" + request.Address.ToString() + "'"); } Span <byte> lengthBytes = bytes.Slice(2, 2).Span; lengthBytes.Reverse(); ushort length = BitConverter.ToUInt16(lengthBytes); if (length != request.Values.Length) { throw new RTUException("The Response Values Length of '" + length.ToString() + "' did not match the Expected Values Length '" + request.Values.Length.ToString() + "'"); } }
public async Task <WriteRegistersResult> WriteHoldingRegistersAsync(short[] values, ushort startAddress, CancellationToken cancellationToken) { lock (_isInitializedLock) { if (_isInitialized == false) { throw new ModbusException("This Modbus RTU Device must be Initialized first before any Requests can be Processed"); } } if (startAddress > MaximumAddress) { throw new ArgumentOutOfRangeException(nameof(startAddress), "The Start Address is greater than the Maximum Allowed Value of '" + MaximumAddress + "'"); } if (values.Length == 0) { throw new ArgumentOutOfRangeException(nameof(values), "The Values Array cannot be Empty"); } if (values.Length > MaximumRegistersWriteLength) { throw new ArgumentOutOfRangeException(nameof(values), "The Values Array Length was greater than the Maximum Allowed of '" + MaximumRegistersWriteLength + "'"); } WriteHoldingRegistersRequest request = WriteHoldingRegistersRequest.CreateNew(this, startAddress, values); ProcessRequestResult requestResult = await _channel.ProcessRequestAsync(request, _timeout, _retries, _delayBetweenMessages, cancellationToken); WriteHoldingRegistersResponse.Validate(request, requestResult.Response); return(new WriteRegistersResult { BytesSent = requestResult.BytesSent, PacketsSent = requestResult.PacketsSent, BytesReceived = requestResult.BytesReceived, PacketsReceived = requestResult.PacketsReceived, Duration = requestResult.Duration, }); }