public void WriteExample() { Console.WriteLine("FYI: WriteExample"); // Create the connection IPAddress iPAddress = new IPAddress(SETTING_MODBUS_SERVER_TCP_IP); this.tcpClient = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Attempt to connect to the Modbus slave. this.tcpClient.Connect(new IPEndPoint(iPAddress, SETTING_MODBUS_SERVER_TCP_PORT)); // We are connected. Console.WriteLine("FYI: Connected to IP address=[{0}]", this.tcpClient.RemoteEndPoint.ToString()); System.UInt16[] data = new System.UInt16[SETTING_MODBUS_CLIENT_LENGTH]; data[0] = 99; data[1] = 150; data[2] = 306; System.Byte exceptionCode; unsafe { // Set some unmanaged memory up. IntPtr unmanagedPointer = Marshal.AllocHGlobal(SETTING_MODBUS_CLIENT_LENGTH); CopyBytesIntoPointer(data, unmanagedPointer); // Send the message Console.WriteLine("FYI: Sending WriteRegisters message"); uint resultWriteRegisters = CASModbusAdapter.WriteRegisters(1, SETTING_MODBUS_CLIENT_DEVICE_ID, CASModbusAdapter.FUNCTION_10_FORCE_MULTIPLE_REGISTERS, SETTING_MODBUS_CLIENT_ADDRESS, unmanagedPointer, (ushort)(data.Length * sizeof(System.UInt16)), &exceptionCode); Marshal.FreeHGlobal(unmanagedPointer); this.tcpClient.Close(); // Print the results. if (resultWriteRegisters == CASModbusAdapter.STATUS_SUCCESS) { Console.WriteLine("Write was successful."); } else if (resultWriteRegisters == CASModbusAdapter.STATUS_ERROR_MODBUS_EXCEPTION) { Console.WriteLine("Modbus.Exception={0}", exceptionCode); } else { Console.WriteLine("ModbusStack.Error={0}", resultWriteRegisters); } } }
public void WriteExample() { Console.WriteLine("FYI: WriteExample"); System.UInt16[] data = new System.UInt16[SETTING_MODBUS_CLIENT_LENGTH]; data[0] = 99; data[1] = 150; data[2] = 306; System.Byte exceptionCode; unsafe { // Set some unmanaged memory up. IntPtr unmanagedPointer = Marshal.AllocHGlobal(SETTING_MODBUS_CLIENT_LENGTH); CopyBytesIntoPointer(data, unmanagedPointer); // Send the message Console.WriteLine("FYI: Sending WriteRegisters message"); uint resultWriteRegisters = CASModbusAdapter.WriteRegisters(1, SETTING_MODBUS_CLIENT_DEVICE_ID, CASModbusAdapter.FUNCTION_10_FORCE_MULTIPLE_REGISTERS, SETTING_MODBUS_CLIENT_ADDRESS, unmanagedPointer, (ushort)(data.Length * sizeof(System.UInt16)), &exceptionCode); Marshal.FreeHGlobal(unmanagedPointer); // Print the results. if (resultWriteRegisters == CASModbusAdapter.STATUS_SUCCESS) { Console.WriteLine("Write was successful."); } else if (resultWriteRegisters == CASModbusAdapter.STATUS_ERROR_MODBUS_EXCEPTION) { Console.WriteLine("Modbus.Exception={0}", exceptionCode); } else { Console.WriteLine("ModbusStack.Error={0}", resultWriteRegisters); } } }