fbarresi / Sharp7

Nuget package for Sharp7
MIT License
207 stars 73 forks source link

ArgumentOutOfRangeException when executing the method DBWrite #38

Open PozitronikAkr opened 1 year ago

PozitronikAkr commented 1 year ago

Hi !

There is no physical connection.

The DBRead method predictably returns error number 9. CLI : Client not connected. The DB Write method returns an exception System.ArgumentOutOfRangeException. And it should, as it seemed to me, also return error number 9. Why is this not the case?

namespace TestSharp7ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            int result;
            byte[] db = new byte[20];
            S7Client client = new S7Client();
            client.ConnectTo("192.168.0.2", 0, 1);
            try
            {                
                result = client.DBRead(10, 0, db.Length, db);
                Console.WriteLine($"{result} : {client.ErrorText(result)}");
                result = client.DBWrite(10, 0, db.Length, db);
                Console.WriteLine($"{result} : {client.ErrorText(result)}");
            }
            catch (System.ArgumentOutOfRangeException e)
            {
                result = -1;
                Console.WriteLine($"{result} : {e.Message}");
            }
            Console.WriteLine();
            Console.WriteLine("Press <Enter> for exit");
            Console.ReadLine();        
        }
    }
}
fbarresi commented 1 year ago

Hi!

Please apologize my delayed answer.

Thank you for pointing out this behavior. I understand the problem. Actually the write function will prepare the data telegram regardless of the connection state. This is causing the different exception.

I will debug it and release a new version after the testing phase.

Apart this: is always a good practice to wait for connection established before start to read or write stuff.

If you need such a function that waits for the connection state you might give a try to Sharp7Rx a superimposition of Sharp7.

In this way you can dynamically wait for the connection state and you have some other comfortably function such an internal scheduler for thread safe operations.

await plc.ConnectionState
             .FirstAsync(c => c == Sharp7.Rx.Enums.ConnectionState.Connected)
             .ToTask();

Best regards, FB