Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to receive and write data into a txt file, I checked this post and added eventHandler properly. The sequence of opening etc. are the same. However I can not receive data, even when I try to print inside
SerialPort_DataReceived
it does not nothing. I can not receive data.

p.CmdSerialPort.DataReceived
is always null whatever I change.

Can someone please help?

using System;
using System.Linq;
using System.IO;
using System.IO.Ports;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;


namespace Logger
{
    public class SPWrapper
    {
        

        public System.IO.Ports.SerialPort CmdSerialPort;
        public StreamWriter swLog;
        public DateTime lastComm = DateTime.MinValue;
        public UdpClient udpClient_Cmd;
        public volatile bool _enabled_Cmd;
        public static int Ethernet_Packet_Header_Length = 14;
        public IPAddress IP { get;  set; }
        public int Cmd_Port { get;  set; }
        ////////////////////////////////////////////////////////////
        // SERIAL PORT 
        ////////////////////////////////////////////////////////////

        public bool TryConnect(string portName)
        {

            try
            {

                CmdSerialPort.PortName = portName;
                CmdSerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
                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;

            }

        }

        internal void Close2()
        {
            if (CmdSerialPort.IsOpen)
            {

                CmdSerialPort.Close();

            }

            swLog.Close();

            swLog = null;

        }



        public void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

            lastComm = DateTime.Now;

            if (sender is SerialPort sp)
            {

                string indata = sp.ReadExisting();

                indata = indata.Trim(' ').Trim('\n').Trim('\r');

                WriteToFile($"{CmdSerialPort.PortName}\t{lastComm}\t{indata}");

            }

        }

        public void WriteToFile(string v)
        {

            swLog.WriteLine(v);

        }


        ////////////////////////////////////////////////////////////
        // ETHERNET 
        ////////////////////////////////////////////////////////////
        public IPEndPoint IPE_Cmd;



        internal void Close()
        {

            udpClient_Cmd?.Close();

        }



        public bool Initialize()
        {

            bool retVal = true;

            IPE_Cmd = new IPEndPoint(IP, Cmd_Port);

            try
            {

                udpClient_Cmd = new UdpClient();

                udpClient_Cmd.Client.Bind(IPE_Cmd);

                _enabled_Cmd = true;

                udpClient_Cmd.BeginReceive(new AsyncCallback(ReceiveCallbackCmd), null);

            }
            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 void ReceiveCallbackCmd(IAsyncResult ar)
        {

            DateTime now = DateTime.Now;

            IPEndPoint e = new IPEndPoint(IPAddress.Any, 0);

            byte[] receiveBytes = null;

            try

            {

                receiveBytes = udpClient_Cmd?.EndReceive(ar, ref e);
                Console.WriteLine(receiveBytes);

            }

            catch (ObjectDisposedException)

            {

                _enabled_Cmd = false;

                udpClient_Cmd?.Close();

                udpClient_Cmd = null;

            }

            if (receiveBytes != null)

            {

                string UDP_Read_Message = System.Text.Encoding.UTF8.GetString(receiveBytes.Skip(Ethernet_Packet_Header_Length).ToArray());

                WriteToFile($"{e}\t{now}\t{UDP_Read_Message}");

            }

            if (_enabled_Cmd)

            {

                udpClient_Cmd?.BeginReceive(new AsyncCallback(ReceiveCallbackCmd), null);

            }

        }
    }

    class Program
    {
        public static SPWrapper p;
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter Parameters: ");
            p = new SPWrapper();
            p.IP = IPAddress.Parse("....");//IP

            //serial port configurations
            p.CmdSerialPort = new SerialPort();
            p.CmdSerialPort.Handshake = Handshake.None;
            p.CmdSerialPort.BaudRate = 115200;
            p.CmdSerialPort.Parity = Parity.None;
            p.CmdSerialPort.StopBits = StopBits.One;
            p.CmdSerialPort.DataBits = 8;

            //takes port, ethernet and filename inputs
            string s = Console.ReadLine();
            string[] input = s.Split(' ').ToArray();

            if (input.Length > 3)
                Console.WriteLine("Wrong input size!");

            string filename = input[2];//takes filename 
            //DEFAULT PATH ROOT
            String root = @".\\";
            string path_combined;

            filename += ".txt";
            path_combined = Path.Combine(root, filename);

            try
            {

                if (p.TryConnect(input[0]))//takes port name  eg.COM9
                    p.swLog = File.CreateText(path_combined);

            }
            catch (System.IndexOutOfRangeException ex)
            {
                System.ArgumentException argEx = new System.ArgumentException("File creation failed!", ex);
                throw argEx;
            }



            p.Cmd_Port = Int32.Parse(input[1]);//takes port number  eg.4667

            p.Initialize();

            Console.ReadKey();

            p.Close2();

            p.Close();


        }//end of main


    }
    
}


What I have tried:

I put breakpoints near all open() and close(), it seems they work fine, but I believe the problem might stem from
CmdSerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);

In official link of microsoft, this line is put before open(). Still I get an empty txt file, it can not write.
Posted
Updated 26-Aug-19 3:37am
v3

Start by using something you know works: Hyperterminal or similar. Set that up according to the book, and prove that you can establish communications directly with the other device. If you can't you need to find out why, and it's going to be wrong port; or wrong speed, BPC, Parity; wrong wring; wrong device; hardware failure; or you don't understand how to talk to that device (it may need a specific sequence sent to it in order to do anything).

When that works, you know you have the right stuff, so you can start with coding.
But until then, you can have no idea what is going on!
 
Share this answer
 
Comments
Danny96 26-Aug-19 8:39am    
I set the speed and parity correct, I used different cables, my computer sees COM3 successfully, I think it is software related. And I just learned serial port/IP/ethernet notions along with basic network knowledge 2-3 days ago. I am struggling that is why I seek help, I lost. I put breakpoints they all seem working, serial port opens but there is no data receive. I have been learning all the network stuff for 2-3 days, I am new and I have very limited time. I communicate with device well, there is no problem with that.
That is because p variable is created, and thus is only accessible, in Main method. In clear: the Program instance p in your Main method is not the same Program instance as your program actually runs in.
You could put all but the Main method in its own class, an instance of which you would then instantiate inside the Main method.
Schematically:
C#
public class SPWrapper
{
   public IPAddress IP { get; protected set; }
   public int Cmd_Port { get; protected set; }
   // ...
}

class Program
{
   private static SPWrapper p;

   static void Main(string[] args)
   {
      p = new SPWrapper();
      // ...
   }
}

p would then be accessible from everywhere inside the Program class.
 
Share this answer
 
Comments
Danny96 26-Aug-19 9:04am    
I changed the structure but it says;
"'SPWrapper.CmdSerialPort' is inaccessible due to its protection level" and "The property or indexer 'SPWrapper.IP' cannot be used in this context because the set accessor is inaccessible "
phil.o 26-Aug-19 9:18am    
You have to either change the protection level for said properties/methods in the new class, or create a constructor accepting arguments used to configure inner state.
For example, either declare
public IPAddress IP { get; set; }
or add a constructor allowing to set this value:
public SPWrapper(IPAddress address){   IPAddress = address; }

Please use the green Improve question widget and provide the new code.
Danny96 26-Aug-19 9:26am    
I corrected private problem, it just gives warning saying "CmdSerialPort will always be null"
phil.o 26-Aug-19 9:33am    
Not seeing your actual code, I'm just left to have to guess, and I hate guess-work when it comes to development :)
Please refer to the last phrase of my previous comment.
Danny96 26-Aug-19 9:38am    
I updated my code according to your structure, can you please help me

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