Spider built-in ethernet

I have this simple program:


    public partial class Program
    {
        private static EthernetBuiltIn ethernet = new EthernetBuiltIn();

        void ProgramStarted()
        {
            if( !ethernet.IsOpen)
                ethernet.Open();

            if (ethernet.NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
            {
                NetworkInterfaceExtension.AssignNetworkingStackTo(ethernet);
            }

            ethernet.NetworkInterface.EnableStaticIP("192.168.1.234","255.255.255.0","192.168.1.1");
            ethernet.NetworkInterface.EnableStaticDns(new[]{"212.24.128.8","212.24.132.132"});
            ethernet.NetworkInterface.PhysicalAddress = NTP.MACAddressToBytes("4C-0B-6D-22-54-5B");

            Ping("192.168.1.11");

            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");
        }

        private static byte lastSequenceNr = 0;
        private static byte[] pingCommand;

        public static bool Ping(string address)
        {
            bool result = false;
            byte[] receiveBuffer = new byte[540];
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0);
            IPEndPoint responseEndPoint = new IPEndPoint(IPAddress.Any, 0);
            EndPoint castResponseEndPoint = (EndPoint)responseEndPoint;
            pingCommand = new byte[8];
            pingCommand[0] = 8; // Type
            pingCommand[1] = 0; // Subtype
            pingCommand[2] = 0; // Checksum
            pingCommand[3] = 0;
            pingCommand[4] = 1; // Identifier
            pingCommand[5] = 0;
            pingCommand[6] = 0; // Sequence number
            pingCommand[7] = 0;
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
            socket.Bind(localEndPoint);
            socket.SetSocketOption(
                SocketOptionLevel.IP,
                SocketOptionName.IpTimeToLive,
                128
                );
            socket.ReceiveTimeout = 10;
            DateTime timeSend = DateTime.Now;
            Debug.Print(timeSend.ToString());
            pingCommand[6] = lastSequenceNr++;
            SetChecksum(pingCommand);
            socket.SendTo(pingCommand, pingCommand.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(address), 0));
            Debug.Print("sended");
            try
            {
                int Brecieved = socket.ReceiveFrom(
                    receiveBuffer,
                    0,
                    receiveBuffer.Length,
                    SocketFlags.None,
                    ref castResponseEndPoint
                    );
                if ((receiveBuffer[20] == 0) && (pingCommand[4] == receiveBuffer[24]) && (pingCommand[5] == receiveBuffer[25]) &&
                        (pingCommand[6] == receiveBuffer[26]) && (pingCommand[7] == receiveBuffer[27]))
                {
                    Debug.Print("response received");
                    Debug.Print(DateTime.Now.Subtract(timeSend).ToString());
                    result = true;
                }
            }
            catch (SocketException e)
            {
                if (e.ErrorCode != (int)SocketError.TimedOut)
                {
                    Debug.Print("unexpected error: " + e.ErrorCode);
                }
            }
            socket.Close();
            return result;
        }

        private static void SetChecksum(byte[] tel)
        {
            tel[2] = 0;
            tel[3] = 0;
            uint cs = 0;

            for (int i = 0; i < pingCommand.Length; i = i + 2)
                cs += (UInt16)(pingCommand[0 + i] << 0 | pingCommand[1 + i] << 8);

            cs = ~((cs & 0xffffu) + (cs >> 16));
            tel[2] = (byte)cs;
            tel[3] = (byte)(cs >> 8);
        }

        public static UInt16 ToUInt16(byte[] value, int index = 0) { return (UInt16)(value[0 + index] << 0 | value[1 + index] << 8); }
    }

Ping method is from codeshare.

It gives this output:

sended
response received
00:00:00.0338452
Program Started

Now, if I change the private ip address in Ping method to some public, say 85.13.110.1, I get this:

sended
#### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (1) ####
#### Message:
#### Microsoft.SPOT.Net.SocketNative::recvfrom [IP: 0000] ####
#### System.Net.Sockets.Socket::ReceiveFrom [IP: 0026] ####
#### SpiderNet.Program::Ping [IP: 00ce] ####
#### SpiderNet.Program::ProgramStarted [IP: 0070] ####
#### SpiderNet.Program::Main [IP: 0015] ####
#### SocketException ErrorCode = 10060
#### SocketException ErrorCode = 10060
A first chance exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = 10060
#### SocketException ErrorCode = 10060
Program Started

I have tried also NTP client from codeshare, which works for me on Hydra with ENC28, it ends with timeout waiting for response from ntp server.

What can be wrong?

What can be wrong? Maybe your default gateway is wrong.

Brett, thanks for reply, but the gateway is correct. It works for panda 2, hydra with enc28 and 4 PCs.

I did notice that yellow led on JD11 is always on - no flashing just still on even without network cable.
Another strange thing is that resolving dns names works, which I think would not be possible with wrong gateway.

Of course DNS resolution is possible without an operating default gateway, if your DNS server (or redirector) is on the same subnet - in your case however that’s not the case.

So lets just clarify, you’re able to use the exact same code on Hydra and Panda 2 and it gets the response?

Next step of course is to tell us where the exception is thrown. Perhaps step in to the code and see what values you have immediately before that.

Not saying there’s not something wrong at a firmware perspective, just that it’d help if we can drill into this and see more detail about where it is.

Yes, I should have mention that I don’t have private DNS server, of course.
Nevermind, I tried to sync time over net with this:

Common code:


        public static bool NTPTime(string TimeServer, int GmtOffset = 0)
        {
            Socket s = null;
            try
            {
                EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                var ntpData = new byte[48];
                Array.Clear(ntpData, 0, 48);
                ntpData[0] = 0x1B; // Set protocol version
                s.SendTo(ntpData, rep); // Send Request   
                if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
                {
                    s.ReceiveFrom(ntpData, ref rep); // Receive Time
                    const byte offsetTransmitTime = 40;
                    ulong intpart = 0;
                    ulong fractpart = 0;
                    for (var i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
                    for (var i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
                    var milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
                    var dateTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    Utility.SetLocalTime(dateTime.AddMinutes(GmtOffset));
                   return true;
                }
            }
            finally
            {
                if (s != null) 
                    s.Close();
            }

            return false;
        }

On Hydra I run this code:


            var nics = NetworkInterface.GetAllNetworkInterfaces();

            if (nics.Length > 0)
            {
                var nic = nics[0];

                nic.PhysicalAddress = MACAddressToBytes("AC-C3-04-1D-0E-1E");
                nic.EnableStaticIP("192.168.1.234", "255.255.255.0", "192.168.1.1");
                nic.EnableStaticDns(new[] {"212.24.128.8", "212.24.132.132"});

                Debug.Print(nic.IPAddress.ToString());
                Debug.Print(nic.GatewayAddress.ToString());
                Debug.Print(nic.DnsAddresses[0]);
                Debug.Print(nic.SubnetMask);

                 if (NTPTime("ntp.cesnet.cz", +60))
                {
                    Debug.Print(DateTime.Now.ToString());
                }
            }

And I get this output:

Using mainboard GHI Electronics FEZHydra version 1.2
192.168.1.234
192.168.1.1
212.24.128.8
255.255.255.0
11/21/2012 12:31:19

On Spider I run this code:


            if( !ethernet.IsOpen)
                ethernet.Open();

            NetworkInterfaceExtension.AssignNetworkingStackTo(ethernet);
 
            var nics = NetworkInterface.GetAllNetworkInterfaces();

            if (nics.Length > 0)
            {
                var nic = nics[0];

                nic.PhysicalAddress = NTP.MACAddressToBytes("00-21-03-80-4A-C6"); // MAC from the mainboard
                nic.EnableStaticIP("192.168.1.234", "255.255.255.0", "192.168.1.1");
                nic.EnableStaticDns(new[] {"212.24.128.8", "212.24.132.132"});

                Debug.Print(nic.IPAddress.ToString());
                Debug.Print(nic.GatewayAddress.ToString());
                Debug.Print(nic.DnsAddresses[0]);
                Debug.Print(nic.SubnetMask);

                if (NTPTime("ntp.cesnet.cz", +60))
                {
                    Debug.Print(DateTime.Now.ToString());
                }
                else
                {
                    Debug.Print("Timeout");
                }
            }

And I get this output:

Using mainboard GHI Electronics FEZSpider version 1.0
192.168.1.234
192.168.1.1
212.24.128.8
255.255.255.0
WARN: Total initialization time exceeds 10 seconds.
: ProgramStarted is blocking execution, which means events and timers will not run properly.
: Make sure not to use blocking code such as while(true) - use a GT.Timer instead.
WARN: Total initialization time exceeds 20 seconds.
: ProgramStarted is blocking execution, which means events and timers will not run properly.
: Make sure not to use blocking code such as while(true) - use a GT.Timer instead.
WARN: Total initialization time exceeds 30 seconds.
: ProgramStarted is blocking execution, which means events and timers will not run properly.
: Make sure not to use blocking code such as while(true) - use a GT.Timer instead.
Timeout

So I don’t think networking stack on my spider is working :frowning:

Also MFDeploy network configuration does not work.

On Update button It just displays message “Invalid configuration data from Plug-In”.

Compare your code with what Gus is using in this example: http://www.tinyclr.com/codeshare/entry/588

When I run his code, I get this:

Using mainboard GHI Electronics FEZSpider version 1.0
#### Exception GHI.Premium.Net.NetworkInterfaceExtensionException - 0x00000000 (1) ####
#### Message:
#### GHI.Premium.Net.NetworkInterfaceExtension::Activate [IP: 001a] ####
#### HttpServer.Program::ProgramStarted [IP: 000e] ####
#### HttpServer.Program::Main [IP: 0015] ####
A first chance exception of type ‘GHI.Premium.Net.NetworkInterfaceExtensionException’ occurred in GHI.Premium.Net.dll
An unhandled exception of type ‘GHI.Premium.Net.NetworkInterfaceExtensionException’ occurred in GHI.Premium.Net.dll

Because network interface is already assigned - it works only first time after power on. Anyway, if I skip this call and enable DHCP call then I get this:

Using mainboard GHI Electronics FEZSpider version 1.0
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
WARN: Total initialization time exceeds 10 seconds.
: ProgramStarted is blocking execution, which means events and timers will not run properly.
: Make sure not to use blocking code such as while(true) - use a GT.Timer instead.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.

etc etc etc

And yes, I have working DHCP server on my network! The pc I use to write this message got dhcp address!

For the moment, put your code aside and run the Gus’s project. The output
you are showing is from a Gadgeteer project.

The goal is to get working code first, and then migrate it to your project

Have you set the MAC address of the EMX module using MFDeploy?

Mike, regarding MFDeploy - this does not work for me with spider (hydra is ok) - I just get message “Invalid configuration data from Plug-In” whenever I try to setup network configuration.

Do you have the latest TinyBooter and latest firmware.

Yes, I am having the same issue with MFDeploy and a Spider.

I decided to try Gus’s code on my office Spider this morning, and was having a problem get an address with DHCP. I then tried to change some of the device network configuration parameters using MFDeploy, but was unable to make the change due to the plug-in message. I am unable to change the default MAC address, which might be an issue with the DHCP server.

At home, I was able to get the code Gus posted working on my network, with the same Spider, without any problems. I will be taking the Spider home tonight and see if there is some DHCP server sensitivity issue, such as MAC address.

I do…

ok will get right on it and see what is going on

Yes, sure I have latest everything.

When I power on the spider then MFDeploy network configuration shows some random values. Once I assign in code interface to stack and setup all parameters including MAC address I can see them all in MFDeploy, but still it is not possible to edit it.

In the link to Gus’s code is just c# file, no project. What kind of project should I start with? If I try MFConsole application I get exception right on the line
NetworkInterfaceExtension.AssignNetworkingStackTo(Eth1);

The thread ‘’ (0x2) has exited with code 0 (0x0).
#### Exception GHI.Premium.Net.NetworkInterfaceExtensionException - 0x00000000 (1) ####
#### Message:
#### GHI.Premium.Net.NetworkInterfaceExtension::Activate [IP: 001a] ####
#### SimpleHttpServer.Program::Main [IP: 000e] ####
A first chance exception of type ‘GHI.Premium.Net.NetworkInterfaceExtensionException’ occurred in GHI.Premium.Net.dll
An unhandled exception of type ‘GHI.Premium.Net.NetworkInterfaceExtensionException’ occurred in GHI.Premium.Net.dll

The program ‘[2] Micro Framework application: Managed’ has exited with code 0 (0x0).

I used an EMX Application.

I have the same issue with my fez spider now.
Yesterday, i tried “Simple HTTP server using GHI’s Premium Net library” with static ip and get “IP address is not set yet.” (Project: .NET Gadgeteer Application (NETMF 4.2))
After removing “while (!IPAddressSetResetEvent.WaitOne(500, false))” the webserver works.
Today, same code i get the “NetworkInterfaceExtensionException”.

if i call “NetworkInterfaceExtension.AssignNetworkingStackTo(Eth1)” a second time, i get first time an exception, but it works !?


try
{
    NetworkInterfaceExtension.AssignNetworkingStackTo(Eth1);
}
catch (Exception ex)
{
    Debug.Print(ex.Message);
}
NetworkInterfaceExtension.AssignNetworkingStackTo(Eth1);

same issue with my spider

TinyBooter: 4.2.0.0
Firmware: 4.2.5.0

EDIT:
Ethernet Module: J11D

Ok, I recreated it as EMX Application. No change. With the try catch around Assign I get this (exact copy of Gus’s code):

‘Microsoft.SPOT.Debugger.CorDebug.dll’ (Managed): Loaded ‘C:\Projects\EMX Application2\EMX Application2\bin\Debug\le\EMX Application.exe’, Symbols loaded.
The thread ‘’ (0x2) has exited with code 0 (0x0).
#### Exception GHI.Premium.Net.NetworkInterfaceExtensionException - 0x00000000 (1) ####
#### Message:
#### GHI.Premium.Net.NetworkInterfaceExtension::Activate [IP: 001a] ####
#### EMX_Application2.Program::Main [IP: 000f] ####
A first chance exception of type ‘GHI.Premium.Net.NetworkInterfaceExtensionException’ occurred in GHI.Premium.Net.dll
Exception was thrown: GHI.Premium.Net.NetworkInterfaceExtensionException
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
IP address is not set yet.
etc