Serial Port Server

Hello,

As my first netfm project I decided to write a Serial Port Server (which is something I could really use on UART level)…

Update: I was looking through the USB examples and have noticed that there are built in Events like device connected and device disconnected. Do they also exist for the network classes?
I started a new blog about my ChipWorkX experience at http://www.chipworkx.com (hope GHI won’t mind me using that domain name) I’ll update it as often as possible…

So my first part is implementing the telnetd (a TCP Server listing on Port 2001 for incoming connections). I noticed however that once I close the telnet session the while (true) function is “collecting” data as crazy… though I don’t know where they come from.

 
                  while (true)
                    {
                        mySocket.Receive(received_data);
                        DataReceivedEvent(received_data);
                    }

I would actually need something like while (telnet client connected) because else once I disconnect I cannot connect again without resetting the device.

Below is my entire code so far…I know it’s not pretty but that will come once the functionality is done… It’s a private project so the code is public domain, feel free to copy it if you like it.

Thanks in advance for any help!


using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.Hardware;

namespace SerialPortServer
{
    public class NetListener
    {
        private Socket listenSocket;
        private Thread NetReader;
        public delegate void EventHandler(byte[] data);
        public virtual event EventHandler DataReceivedEvent;
        private Socket mySocket;
        bool data_sent = false;
        OutputPort LED1 = new OutputPort(ChipworkX.Pin.PC5, false);

        public void run()
        {
            IPAddress hostIP = Network.systemIP;
            listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(hostIP, 2001);
            try
            {
                listenSocket.Bind(ep);
                listenSocket.Listen(1);
                Debug.Print("listening...");
                NetReader = new Thread(read_data);
                NetReader.Start();
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
            }
        }

        public void read_data()
        {
            while (true)
            {
                if (listenSocket.Poll(100, SelectMode.SelectRead))
                {
                    mySocket = listenSocket.Accept();
                    Debug.Print("Triggered a SelectRead " + mySocket.RemoteEndPoint.ToString());
                    byte[] received_data = new byte[1];
                    DataReceivedEvent += new EventHandler(DataReceived);
                    while (true)
                    {
                        mySocket.Receive(received_data);
                        DataReceivedEvent(received_data);
                    }
                }
            }
        }
        public void DataReceived(byte[] data)
        {
            try
            {
                LED1.Write(true);
                Thread.Sleep(10);
                if (!data_sent)
                    mySocket.Send(data, SocketFlags.None);
                data_sent = true;
                Debug.Print(Encoding.UTF8.GetChars(data)[0].ToString());
                LED1.Write(false);
            }
            catch (Exception ex)
            {
                Debug.Print("Exception in DataReceived: " + ex.ToString());
            }
            finally
            {
                LED1.Write(false);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Network.init();
            NetListener myListener = new NetListener();
            myListener.run();
            Debug.Print("I got to the end of main!");
            Thread.Sleep(Timeout.Infinite);
        }
    }
}

This is the Network init code… it seems to do what it needs to do… I put it extra so to not make the first post too long.


using System.Threading;
using System.Net;

using Microsoft.SPOT;

namespace SerialPortServer
{
    class Network
    {
        public static IPAddress systemIP;

        public static void init()
        {
            init(false);
        }
        
        public static void init(bool use_dhcp)
        {
            // First, make sure we actually have a network interface to work with!
            if (Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().Length < 1)
            {
                Debug.Print("No Active network interfaces. Bombing out.");
                Thread.CurrentThread.Abort();
            }

            // OK, retrieve the network interface
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface NI = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0];

            if (use_dhcp)
            {
                if (NI.IsDhcpEnabled == false)
                {
                    Debug.Print("Enabling DHCP.");
                    NI.EnableDhcp();
                    Debug.Print("DCHP - IP Address = " + NI.IPAddress + " ... Net Mask = " + NI.SubnetMask + " ... Gateway = " + NI.GatewayAddress);
                }
                else
                {
                    Debug.Print("Renewing DHCP lease.");
                    NI.RenewDhcpLease();
                    Debug.Print("DCHP - IP Address = " + NI.IPAddress + " ... Net Mask = " + NI.SubnetMask + " ... Gateway = " + NI.GatewayAddress);
                }
            }
            else
            {
                NI.EnableStaticIP("192.169.1.20", "255.255.255.0", "192.169.1.254");
            }
            systemIP=IPAddress.Parse(NI.IPAddress);
        }
    }
}

For telnet code look here: http://code.tinyclr.com/project/191/telnet-type-class-for-netmf/

Thanks for the link but the part I need is missing…