Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Windows Form + Netduino+ trouble


  • Please log in to reply
4 replies to this topic

#1 Björn Nilsson

Björn Nilsson

    New Member

  • Members
  • Pip
  • 7 posts

Posted 28 July 2011 - 06:53 PM

Hi,

I'm trying to create a windows form app with which i plan (i.e. hope) to control my N+ through a Cross-over ethernet cable (static IP). So far I've managed to get my program to send a command using socket.send()to my N+ in order to turn on/off the on-board LED, and amazingly (I'm no coder as you'll probably notice from my code) it works! But only once before the software on my N+ throws an "System.ObjectDisposedException" related to the socket.Accept() function.

To be honest, I have limited understanding on what I'm doing. My code contains bits and pieces I've collected on this forum and other internet resources and I've just recently started to grasp system.net.socket functions (the basic).

Most of the code here is based on an project by Bill french(on this forum to whom I owe many thanks)

Posted Image

Anyone care to have a look comment on what I might be lacking/doing wrong? Many thanks in advance! =)

The code for my Windows Form seems to work fine; simple program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

namespace WindowsFormNetduinoPlusLED
{
    public partial class ONOFFLedForm : Form
    {
        string NetduinoIP = "192.168.5.100";
        public int Port = 80;
        
        public ONOFFLedForm()
        {
            InitializeComponent();
        }

        public void SendLEDCommand(String LEDCommand)
        {
            if (NetduinoIP != null && Port > 0)
            {
                using (System.Net.Sockets.Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {

                    IPAddress hostAddress = System.Net.IPAddress.Parse("192.168.5.100");
                    IPEndPoint endpoint = new IPEndPoint(hostAddress, 8000);
                    
                    try
                    {
                        socket.Connect(endpoint);
                        socket.Send(Encoding.UTF8.GetBytes(LEDCommand));
                        socket.Close();
                    }
                    catch (SocketException se)
                    {
                        Debug.Print("Socket Exception!  Probably no server or bad ip?");
                        Debug.Print(se.StackTrace);
                    }
                }
            }
        }

        private void ONButton_Click(object sender, EventArgs e)
        {
            SendLEDCommand("LEDON");
        }

        private void OFFButton_Click(object sender, EventArgs e)
        {
            SendLEDCommand("LEDOFF");
        }

    }
}


This is my N+ program which fails after receiving the first command and turning on/off the led... =/

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using Microsoft.SPOT.Net.NetworkInformation;
using System.Text;

namespace ListenForLedCommand
{
    public class Program
    {
        
        static bool SocketConnected(Socket s)
        {
            bool part1 = s.Poll(1000, SelectMode.SelectRead);
            bool part2 = (s.Available == 0);
            if (part1 & part2)
            {//connection is closed
                return false;
            }
            return true;
        }

        public static void Main()
        {
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, true);
            //Socket socket = null;
            //String NetduinoIP = "192.168.5.100";
                        
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.5.100"), 8000));
            socket.Listen(10);

            String receivedStr = "";


            while (true)
            {

                socket = socket.Accept();

                using (socket)
                {
                    while (SocketConnected(socket))
                    {
                        int availablebytes = socket.Available;
                        byte[] buffer = new byte[availablebytes];
                        socket.Receive(buffer);
                        if (buffer.Length > 0)
                        {
                            receivedStr = new String(Encoding.UTF8.GetChars(buffer));
                        }
                        
                    }
                                                
                }

                if (receivedStr == "LEDON") 
                {
                    led.Write(true);
                }
                if (receivedStr == "LEDOFF") 
                {
                    led.Write(false);
                }
            }
        }

    }
}

Attached Files



#2 Glen

Glen

    Member

  • Members
  • PipPip
  • 26 posts

Posted 28 July 2011 - 08:46 PM

Try moving this section of code

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.5.100"), 8000));
            socket.Listen(10);

to be inside of the while statement where you are doing the .Accept(). I could be reading it wrong, but it sounds like you can only call it once per socket. You shouldn't assign the return socket from the .accept() to the same socket you are listening on. I think you are overwriting your listening socket with the returned socket.

Accept synchronously extracts the first pending connection request from the connection request queue of the listening socket, and then creates and returns a new Socket. You cannot use this returned Socket to accept any additional connections from the connection queue.


It would be better to leave the initial listen socket alone and create a new one inside the while loop like
Socket tempSocket = socket.Accept();

Also I think the using(socket) statement is causing your socket to be disposed after it's done the first time through, so it definitely can't be used again when the loop restarts. Switching it to a using(tempSocket) would be fine as the tempSocket would get created at the start of the loop and disposed at the end each time.

#3 Michael Walker

Michael Walker

    New Member

  • Members
  • Pip
  • 2 posts
  • LocationBrisbane, Australia

Posted 29 July 2011 - 05:00 AM

Hey,

You are firstly overwriting your variable socket with the client socket after Accept is triggered, secondly you are putting the socket in the using scope which will call dispose on the closing }.

As mentioned above create a new variable from the socket.Accept(), should look something like:

while (true)
            {
                string message;

                using (var clientSocket = socket.Accept())
                {

                    //Get request
                    var bufferRequest = new byte[256];
                    int bytes;

                    do
                    {
                        bytes = clientSocket.Receive(bufferRequest, bufferRequest.Length, 0);

                    } while (bytes > 0);

                    message = new String(Encoding.UTF8.GetChars(bufferRequest));
                }

               
                //ToDo: your LED logic here...
            }


Hope this helps :D

Michael

#4 Björn Nilsson

Björn Nilsson

    New Member

  • Members
  • Pip
  • 7 posts

Posted 29 July 2011 - 07:56 AM

Thanks for the help guys! I'll look into this when I get home from work and will report back later on. :P

#5 Björn Nilsson

Björn Nilsson

    New Member

  • Members
  • Pip
  • 7 posts

Posted 29 July 2011 - 02:03 PM

I got it working! Thanks guys! :lol:

It's not really good code but available for anyone who'd like to try it out =)
There's probably 1.0e100 better ways of doing this but hey, I'm new to the game
and just happy it works :P


using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using Microsoft.SPOT.Net.NetworkInformation;
using System.Text;

namespace ListenForLedCommand
{
    public class Program
    {
        
        static bool SocketConnected(Socket s)
        {
            bool part1 = s.Poll(1000, SelectMode.SelectRead);
            bool part2 = (s.Available == 0);
            if (part1 & part2)
            {//connection is closed
                return false;
            }
            return true;
        }

        public static void Main()
        {
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
            //Socket socket = null;
            //String NetduinoIP = "192.168.5.100";
                        
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.5.100"), 8000));
            socket.Listen(10);

            


            while (true)
            {
                String receivedStr = "";

                //Socket ClientSocket = socket.Accept();

                using (var ClientSocket = socket.Accept())
                {
                    while (SocketConnected(socket))
                    {
                        int availablebytes = ClientSocket.Available;
                        byte[] buffer = new byte[availablebytes];
                        ClientSocket.Receive(buffer);
                        if (buffer.Length > 0)
                        {
                            receivedStr = new String(Encoding.UTF8.GetChars(buffer));
                        }

                        if (receivedStr == "LEDON")
                        {
                            led.Write(true);
                        }

                        if (receivedStr == "LEDOFF")
                        {
                            led.Write(false);
                        }
                    }
                                                
                }


            }
        }

    }
}

Attached Files






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.