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

Pull text from a Private Void into a HTTP response


  • Please log in to reply
6 replies to this topic

#1 Buddy

Buddy

    Member

  • Members
  • PipPip
  • 17 posts

Posted 11 July 2013 - 12:58 AM

Sorry if I butcher the terminology here or the code in general. I am not looking for someone to write the code (although that would help), but I am interested in the steps to get text into a response.

 

The setup is a sensor that feeds either 0V or 3.3V into A0, on a N+2.

  • In a "Private Void" I am able to receive the sensor's input and convert it to a text.
  • I have a remote app that comes into the Ethernet interface with a HTTP Get request for status and the status response needs to be the text that is produced in the "Private Void".

With debug I see the text being generated by the Private Void. The problem that I am having is getting the text response out of the Ethernet interface.

 

I think the problem is around lines 65-68, that is about half way down at " IsGarageDoorOpen();"  Yes, that old project...

using System;using Microsoft.SPOT;using System.Net.Sockets;using System.Net;using System.Threading;using System.Text;using Microsoft.SPOT.Hardware;using SecretLabs.NETMF.Hardware.NetduinoPlus;using System.IO;namespace NetduinoGarageDoorOpener{    public class WebServer : IDisposable    {        private Socket socket = null;        //open connection to onbaord led so we can blink it with every request        private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);        private OutputPort Garage2CarOpener = new OutputPort(Pins.GPIO_PIN_D9, false);        private SecretLabs.NETMF.Hardware.AnalogInput garageSensor = new SecretLabs.NETMF.Hardware.AnalogInput(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0);        public WebServer()        {            //Initialize Socket class            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            //Request and bind to an IP from DHCP server            socket.Bind(new IPEndPoint(IPAddress.Any, 80));            //Debug print our IP address            Debug.Print(Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress);            //Start listen for web requests            socket.Listen(10);            ListenForRequest();        }        public void ListenForRequest()        {            while (true)            {                using (Socket clientSocket = socket.Accept())                {                    //Get clients IP                    IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;                    EndPoint clientEndPoint = clientSocket.RemoteEndPoint;                    //int byteCount = cSocket.Available;                    int bytesReceived = clientSocket.Available;                    if (bytesReceived > 0)                    {                        //Get request                        byte[] buffer = new byte[bytesReceived];                        int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);                        string request = new string(Encoding.UTF8.GetChars(buffer));                        string firstLine = request.Substring(0, request.IndexOf('n')); //Example "GET /activatedoor HTTP/1.1"                        string[] words = firstLine.Split(' ');  //Split line into words                        string command = string.Empty;                        if (words.Length > 2)                        {                            string method = words[0]; //First word should be GET                            command = words[1].TrimStart('/'); //Second word is our command - remove the forward slash                            //                        }                        switch (command.ToLower())                        {        // I am trying to figure out how to respond to         // the "checkdoor" request with the text that is produced in the Private Void                           case "checkdoor":                                IsGarageDoorOpen();                                string.response1 = textValue();                                string header1 = "HTTP/1.0 200 OKrnContent-Type: text; charset=utf-8rnContent-Length: " + response1.Length.ToString() + "rnConnection: closernrn";                                clientSocket.Send(Encoding.UTF8.GetBytes(header1), header1.Length, SocketFlags.None);                                clientSocket.Send(Encoding.UTF8.GetBytes(response1), response1.Length, SocketFlags.None);                                break;                            default:                                //Did not recognize command                                response = "Bad commando";                                header = "HTTP/1.0 200 OKrnContent-Type: text; charset=utf-8rnContent-Length: " + response.Length.ToString() + "rnConnection: closernrn";                                clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);                                clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);                                break;                        }                    }                }            }        }        //tried to make this a public void, but that did not fix it.        private void IsGarageDoorOpen()        {            const double maxVoltage = 3.3;            const int maxAdcValue = 4095;            SecretLabs.NETMF.Hardware.AnalogInput garageSensor = new SecretLabs.NETMF.Hardware.AnalogInput(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0);            while (true)            {                int rawValue = garageSensor.Read();                double value = (rawValue * maxVoltage) / maxAdcValue;                {                    String textValue = "";                    {                        if (rawValue > 50)                            textValue = "Open";                        else                            textValue = "Closed";                    }                    Debug.Print(textValue);                }                Thread.Sleep(2500);            }        }        #region IDisposable Members        ~WebServer()        {            Dispose();        }        public void Dispose()        {            if (socket != null)                socket.Close();        }        #endregion    }}


#2 Anthony Glenwright

Anthony Glenwright

    Advanced Member

  • Members
  • PipPipPip
  • 71 posts

Posted 11 July 2013 - 04:29 AM

You could try doing a socket.Poll(1000000, SelectMode.SelectWrite) before each of your send calls, if it isn't that, can you describe what is happening?



#3 NooM

NooM

    Advanced Member

  • Members
  • PipPipPip
  • 490 posts
  • LocationAustria

Posted 11 July 2013 - 07:43 AM

easy. but somehow i dont wanna write your code for you.

some tips:

private void IsGarageDoorOpen(). why you make it void?

you could make the function to return a string...

 

like:

String IsGarageDoorOpen()

{

return "no";

}

 

and than call that in your httprequest funtion and send the return text.

 

also remove the while loop from it and remove the delay.

 

edit: also red more about switch. yours is wrong and i wonder why the compiler doesent complain.

 

its like: switch(blabla)

{

case "xx": { ..... } break;

case "yy": { ..... } break;

default: { ..... } break;

}



#4 nakchak

nakchak

    Advanced Member

  • Members
  • PipPipPip
  • 404 posts
  • LocationBristol, UK

Posted 11 July 2013 - 08:11 AM

two* possible solutions:

 

1) add a private variable at the top of your class to assign a value to in your void method, then read the value of the private variable into your http response

 

2) make your method return a value i.e. a bool (yes/no, true/false value) or a string

 

nak.

 

*im not muddying the waters with out arguments on methods...



#5 JoopC

JoopC

    Advanced Member

  • Members
  • PipPipPip
  • 148 posts

Posted 11 July 2013 - 02:15 PM

Maybe this wil help.

Private Sub WebServer()        Const cnstWaitstate As Integer = 5000        Dim bRequestReceived As Boolean = False        Do While True            Try                If Not bRequestReceived Then                    Using sktServer = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)                        sktServer.ReceiveTimeout = cnstWaitstate                        sktServer.SendTimeout = cnstWaitstate                        If Not bRequestReceived Then                            sktServer.Bind(New IPEndPoint(IPAddress.Any, 61234))                            sktServer.Listen(1)                        End If                        While True                            Try                                If Not bRequestReceived Then                                    Using sktConnection As Socket = sktServer.Accept()                                        sktConnection.ReceiveTimeout = cnstWaitstate                                        sktConnection.SendTimeout = cnstWaitstate                                        If sktConnection.Poll(50000, SelectMode.SelectRead) Then                                            Thread.Sleep(1000)                                            Dim bBytes As Byte() = New Byte(sktConnection.Available - 1) {}                                            If sktConnection.Receive(bBytes) > 0 Then                                                Dim strResponse As String = ""                                                If Not bRequestReceived Then                                                    bRequestReceived = True                                                    strResponse = ServerRequest(New String(Encoding.UTF8.GetChars(bBytes)), sktConnection)                                                    bRequestReceived = False                                                End If                                                If strResponse IsNot Nothing Then                                                    sktConnection.Send(Encoding.UTF8.GetBytes(strResponse), 0, strResponse.Length, SocketFlags.None)                                                End If                                            End If                                        End If                                        sktConnection.Close()                                    End Using                                End If                            Catch ex As Exception                                bRequestReceived = False                            End Try                        End While                    End Using                End If            Catch ex As Exception            End Try            Thread.Sleep(500)        Loop    End Sub

and here you can build your response

 Private Function ServerRequest(ByVal strRequest As String, ByVal sktServer As Socket) As String'build your response string'return "message"end Function


#6 Buddy

Buddy

    Member

  • Members
  • PipPip
  • 17 posts

Posted 12 July 2013 - 11:30 AM

This issue is solved and my Happy Dance just made a rare appearance.

  • JoopC, thanks but I could not understand the words coming out of your keyboard, :lol: . But I do plan to try them out over the weekend, thanks.
  • nakchak [edited to correct name] and NooM, one or both of you had what I needed. Thank you.

I will post the code, good or bad and/or ugly, later today.

 

NooM, the way that the switch is built is a problem. If I really pound on the code by opening/closing/checking status very rapidly an exception is thrown, otherwise no exception is thrown (at least for the past 5-10 minutes) and the N+2 & Droid app are performing as expected.



#7 Buddy

Buddy

    Member

  • Members
  • PipPip
  • 17 posts

Posted 13 July 2013 - 07:43 PM

The code started working with the Droid requests yesterday morning as I was basically hacking (in a non-professional sense of course) through to find what was needed to make it work.

 

Although it seems to be working without issue, I still need to figure out both the String and string are needed, so I can clean it up.

 

 

The HTTP response is now, I have to label the response as response1 and the header as header1 for it to work.

                           case "checkdoor":                                IsGarageDoorOpen();                                string response1 = IsGarageDoorOpen(textValue);                                string header1 = "HTTP/1.0 200 OKrnContent-Type: text; charset=utf-8rnContent-Length: " + response1.Length.ToString() + "rnConnection: closernrn";                                clientSocket.Send(Encoding.UTF8.GetBytes(header1), header1.Length, SocketFlags.None);                                clientSocket.Send(Encoding.UTF8.GetBytes(response1), response1.Length, SocketFlags.None);                                break;

This private string is new.

        private string IsGarageDoorOpen(object textValue)        {         //   throw new NotImplementedException(); //NOT NEEDED            {                const double maxVoltage = 3.3;                const int maxAdcValue = 4095;         // NooM suggested removing While loop, done.                //while (true)                {                    int rawValue = garageSensor.Read();                    double value = (rawValue * maxVoltage) / maxAdcValue;                    {                        String textValue1 = "";                        {                            if (rawValue > 50)                                textValue1 = "Open";                            else                                textValue1 = "Closed";                            return textValue1;                        }                       // Debug.Print(textValue1.ToString());                    }   // NooM suggested removing the delay, but it doesn't seem to run without it.                    Thread.Sleep(2500);                }            }        }

And this section is still active as a String, although I will try to remove it.

 //This section was changed from the private void IsGarageDoorOpen(). // Changed it to a String, but I had to also have  // the "private string IsGarageDoorOpen(object textValue)" above to make it work.  // I have not tried to comment out this section, yet..        String IsGarageDoorOpen()        {            const double maxVoltage = 3.3;            const int maxAdcValue = 4095;            //SecretLabs.NETMF.Hardware.AnalogInput garageSensor = new SecretLabs.NETMF.Hardware.AnalogInput(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0);            // NooM said to remove While loop            //while (true)            {                int rawValue = garageSensor.Read();                double value = (rawValue * maxVoltage) / maxAdcValue;                {                    String textValue = "";                    {                        if (rawValue > 50)                            textValue = "Open";                        else                            textValue = "Closed";                        return textValue;                    }                    Debug.Print(textValue.ToString());                }      // NooM suggested removing the delay, need to see if it will run without it                Thread.Sleep(2500);            }        }





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.