Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote a console C# program that sets parameters(I gave parameters from project->debug option) I am trying to get data from ethernet and serial port.

I set args parameters successfully but program gets timeout error at string filename = args[4]; (I put breakpoints and traced stack move.) Console opens suddenly and act as if it is in infinite loop bu there is no loop.(error occurs before reading while) I don't even call any methods at the time when I get this error, it doesn't make sense.

For those who want to read what are those parameters; 1 = IP, [2] = port number, [3] = port name(COM3), [4] = filename.

Timeouts are to prevent data loss considering I might be getting data from both connections at the same time from ethernet and serial port.

Also I want to say adding
DataReceived += new SerialDataReceivedEventHandler(ProcessReceivedData);
istead of while has no benefit since again it happens before the while loop.


Does anyone have any idea?

What I have tried:

C#
public class SPWrapper
    {
        private System.IO.Ports.SerialPort CmdSerialPort;

        public DateTime lastComm = DateTime.MinValue;
        public UdpClient udpClient_Cmd;
        public volatile bool _enabled_Cmd;
        public static int Ethernet_Packet_Header_Length = 14;
        private IPAddress IP { get; set; }
        private int Cmd_Port { get; set; }
        private string SerialPortName;
        private StreamWriter swLog;
        private bool _closing = false;
        private IPEndPoint IPE_Cmd;
        

        private void CloseEthernet()
        {
            udpClient_Cmd?.Close();
        }

        private void CloseSerialPort()
        {
            if (CmdSerialPort.IsOpen)
            {
                CmdSerialPort.Close();
            }
        }

        public void Close()
        {
            _closing = true;
            CloseEthernet();
            CloseSerialPort();
            swLog = null;
        }

        private bool InitilizeSerialPort(string portName)
        {
            try
            {
                CmdSerialPort.PortName = portName;
                CmdSerialPort.BaudRate = 115200;
                CmdSerialPort.ReadTimeout = 10; // 10milisecond read timeout
               
                CmdSerialPort.Open();
                if (CmdSerialPort.IsOpen)
                {
                    return true;
                }
                return false;
            }
            catch (UnauthorizedAccessException e)
            {
                Debug.WriteLine(e.ToString());
                Debug.WriteLine(e.Message);
                return false;
            }
            catch (ArgumentOutOfRangeException e)
            {
                Debug.WriteLine(e.ToString());
                Debug.WriteLine(e.Message);
                return false;
            }
            catch (ArgumentException e)
            {
                Debug.WriteLine(e.ToString());
                Debug.WriteLine(e.Message);
                return false;
            }
        }

        private bool InitializeEthernet()
        {
            bool retVal = true;
            IPE_Cmd = new IPEndPoint(IP, Cmd_Port);
            try
            {
                udpClient_Cmd = new UdpClient();
                udpClient_Cmd.Client.Bind(IPE_Cmd);
                udpClient_Cmd.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10);
            }
            catch (Exception ex)
            {
                retVal = false;
                udpClient_Cmd?.Close();
                udpClient_Cmd = null;
                Debug.WriteLine(ex.ToString());
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.InnerException?.ToString());
            }
            return retVal;
        }

        public SPWrapper(IPAddress ip, int cmdPort, string comPort, StreamWriter sw)
        {
            IP = ip;
            Cmd_Port = cmdPort;
            SerialPortName = comPort;
            swLog = sw;
            CmdSerialPort = new SerialPort();
        }

        public bool Init()
        {
            return (InitializeEthernet() && InitilizeSerialPort(SerialPortName));
        }

        internal void GetMessage()
        {
            lastComm = DateTime.Now;
            string SerialMessage = "";
            try
            {
                SerialMessage = CmdSerialPort.ReadLine();
            }
            catch (TimeoutException)
            {
            }
            if (SerialMessage.Length >0)
            {
                SerialMessage = SerialMessage.Trim(' ').Trim('\n').Trim('\r');
                swLog.WriteLine($"{CmdSerialPort.PortName}\t{lastComm}\t{SerialMessage}");
            }
            IPEndPoint e = new IPEndPoint(IPAddress.Any, 0);
            byte[] receiveBytes = null;
            try
            {
                receiveBytes = udpClient_Cmd?.Receive(ref e);
            }
            catch (ObjectDisposedException)
            {
                udpClient_Cmd?.Close();
                udpClient_Cmd = null;
            }
            catch(SocketException)
            {
            }
            if (receiveBytes != null)
            {
                string UDP_Read_Message = System.Text.Encoding.UTF8.GetString(receiveBytes.Skip(Ethernet_Packet_Header_Length).ToArray());
                swLog.WriteLine($"{e}\t{lastComm}\t{UDP_Read_Message}");
            }
        }
    }


This is my main

C#
class Program
    {
        public static SPWrapper p;
        static int Main(string[] args)
        {

            int err = 0;

            if (args.Length == 5)
            {
                IPAddress IP = IPAddress.Parse(args[1]);
                int CmdPort;
                if (int.TryParse(args[2],out CmdPort))
                {
                    string filename = args[4];//takes filename 
                   
                    String root = @".\\"; //DEFAULT EXE PATH ROOT
                    string path_combined;
                    path_combined = Path.Combine(root, filename);
                    StreamWriter sw;
                    try
                    {
                        sw = File.AppendText(path_combined);
                        p = new SPWrapper(IP, CmdPort, args[3], sw);
                        if (p.Init())
                        {
                            while (!Console.KeyAvailable)
                            {
                                p.GetMessage();
                                Thread.Sleep(100);
                            }
                            p.Close();
                        }
                        sw.Flush();
                        sw.Close();
                    }
                    catch (System.IndexOutOfRangeException ex)
                    {
                        System.ArgumentException argEx = new System.ArgumentException("File creation failed!", ex);
                        err = -2;
                        throw argEx;
                    }
                }
                else
                {
                    err = -1;
                }
            }
            if (err!=0)
            {
                Console.WriteLine("Not Enough Arguments");
                Console.WriteLine("Logger IP Port ComPort FileName");
            }
            return err;
        }//end of main
    }
Posted
Updated 27-Aug-19 22:11pm
v5

1 solution

Arrays are zero-based in C#; this means that your actual args array is more like
[0] = IP,
[1] = port number,
[2] = port name(COM3),
[3] = filename

Try to modify the line to:
C#
string filename = args[3];
and see where it leads you to.
 
Share this answer
 
Comments
Danny96 28-Aug-19 5:02am    
I changed it, both from code and argument side(project->debug->application arguments), I put spaces between them while giving arguments. I checked if args.Length == 4 now, it still performs the same behaviour
Danny96 28-Aug-19 5:06am    
when I put breakpoints args have the correct value but local variables that supposed to take those values from args are null, string filename is null for example.
phil.o 28-Aug-19 5:52am    
Double-check your indices. Since you put a breakpoint, press F11 to execute line-by-line and find why you get those results. I cannot do that for you.
Danny96 28-Aug-19 7:33am    
I traced and realized it caught up it "UnauthorizedAccessException" error
Danny96 28-Aug-19 7:36am    
I'll try to find the exception error I believe it is related to serial port opening and closing

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900