public static async Task <WriteSingleRegisterHandler> CreateAsync(IMessageBufferReader reader, CancellationToken cancellationToken) { var handler = new WriteSingleRegisterHandler(); await handler.InitializeAsync(reader, cancellationToken); return(handler); }
public static WriteSingleRegisterHandler Create(IMessageBufferReader reader) { var handler = new WriteSingleRegisterHandler(); handler.Initialize(reader); return(handler); }
public void HandleRequest(params ModbusDevice[] devices) { if (devices is null) { throw new ArgumentNullException(nameof(devices)); } if (devices.Length == 0) { throw new ArgumentException(); } MessageHandler?messageHandler = null; ModbusDevice? device = null; var requestContext = ModbusTransport.ReceiveMessage(reader => { var deviceAddress = reader.PushByteFromStream(); device = devices.FirstOrDefault(_ => _.Address == deviceAddress); if (device == null) { throw new InvalidOperationException($"Received request for device with unknown address {deviceAddress}"); } var functionCode = (ModbusFunctionCode)reader.PushByteFromStream(); messageHandler = functionCode switch { ModbusFunctionCode.ReadDiscreteInputs => ReadDiscreteInputsHandler.Create(reader), ModbusFunctionCode.ReadCoils => ReadCoilsHandler.Create(reader), ModbusFunctionCode.ReadInputRegisters => ReadInputRegistersHandler.Create(reader), ModbusFunctionCode.ReadHoldingRegisters => ReadHoldingRegistersHandler.Create(reader), ModbusFunctionCode.WriteSingleCoil => WriteSingleCoilHandler.Create(reader), ModbusFunctionCode.WriteSingleRegister => WriteSingleRegisterHandler.Create(reader), ModbusFunctionCode.WriteMultipleCoils => WriteMultipleCoilsHandler.Create(reader), ModbusFunctionCode.WriteMultipleRegisters => WriteMultipleRegistersHandler.Create(reader), ModbusFunctionCode.ReadWriteMultipleRegisters => ReadWriteMultipleRegistersHandler.Create(reader), _ => throw new NotSupportedException($"Function {functionCode} not supported"), }; }); if (messageHandler is WriteHandler writeHandler) { writeHandler.UpdateMemory(device !); } ModbusTransport.SendMessage(requestContext, writer => { messageHandler !.WriteResponse(device !, writer); });