Exemple #1
0
 /// <summary>
 /// Send string data to the active socket connection.
 /// </summary>
 /// <param name="data">Data string to send.</param>
 public static void Send(string data)
 {
     try
     {
         Socket.Send(Encoding.UTF8.GetBytes(data));
     }
     catch (Exception ex)
     {
         myConnected = false;
         throw ex;
     }
 }
        /// <summary>
        /// Processes the request.
        /// </summary>
        private void ProcessRequest()
        {
            try
            {
                const Int32 c_microsecondsPerSecond = 1000000;
                // 'using' ensures that the client's socket gets closed.
                using (m_clientSocket)
                {
                    // Wait for the client request to start to arrive.
                    Byte[] buffer = new Byte[1024];
                    if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
                                            SelectMode.SelectRead))
                    {
                        // If 0 bytes in buffer, then the connection has been closed,
                        // reset, or terminated.
                        if (m_clientSocket.Available == 0)
                        {
                            return;
                        }
                        // Read the first chunk of the request (we don't actually do
                        // anything with it).
                        Int32 bytesRead = m_clientSocket.Receive(buffer,
                                                                 m_clientSocket.Available, SocketFlags.None);
                        // Return a static HTML document to the client.

                        var comandoRecebido = new string(Encoding.UTF8.GetChars(buffer));
                        Debug.Print("Receive data from Server: " + comandoRecebido);
                        string ret = PressButton(comandoRecebido);
                        //String s = "Comando realizado com Sucesso";

                        byte[] buf    = Encoding.UTF8.GetBytes(ret);
                        int    result = m_clientSocket.Send(buf);
                        Debug.Print("Send data from Server: " + ret);
                        m_clientSocket.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }
        }
Exemple #3
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        private void ProcessRequest()
        {
            const Int32 c_microsecondsPerSecond = 1000000;

            Boolean closeTags = true;     //Do we need to append the closing HTML?

            // 'using' ensures that the client's socket gets closed.
            using (m_clientSocket)
            {
                // Wait for the client request to start to arrive.
                Byte[] buffer = new Byte[1024];
                if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
                                        SelectMode.SelectRead))
                {
                    // If 0 bytes in buffer, then the connection has been closed,
                    // reset, or terminated.
                    if (m_clientSocket.Available == 0)
                    {
                        return;
                    }
                    // Read the first chunk of the request (we don't actually do
                    // anything with it).
                    Int32 bytesRead = m_clientSocket.Receive(buffer,
                                                             m_clientSocket.Available, SocketFlags.None);

                    /* here is where we need to process the request */
                    //Convert the buffer to something more usable
                    String incoming = bytesToString(buffer);
                    //Remove the "\r"s we'll just worry about the "\n"s
                    incoming.Trim('\r');
                    //Slip the request by the "\n"s

                    //Preload the header into the output string
                    String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\ncharset=utf-8\r\n\r\n<html>";

                    /*
                     * These are the data requests
                     */
                    if (incoming.IndexOf("GET /temp") >= 0)
                    {
                        lock (m_tempMgr)
                        {
                            s += "<head><title>TEMP</title></head><body><bold>" + m_tempMgr.getTemp().ToString() + "</bold>";
                        }
                    }
                    else if (incoming.IndexOf("GET /target") >= 0)
                    {
                        lock (m_tempMgr)
                        {
                            s += "<head><title>TARGET</title></head><body><bold>" + m_tempMgr.getTarget().ToString() + "</bold>";
                        }
                    }
                    else if (incoming.IndexOf("GET /pid") >= 0)
                    {
                        lock (m_pid)
                        {
                            s += "<head><title>PID</title></head><body><bold>" + m_pid.getValue().ToString() + "</bold>";
                        }
                    }
                    else if (incoming.IndexOf("GET /dataasxml") >= 0)
                    {
                        M8_DataLog log = new M8_DataLog();

                        log.addTimeStamp();

                        lock (m_tempMgr)
                        {
                            for (int i = 0; i < m_tempMgr.getCount(); i++)
                            {
                                log.addTempData(i, m_tempMgr.getTemp(i), m_tempMgr.getTarget(i));
                            }

                            lock (m_pid)
                                log.addPIDData(m_tempMgr.getPidThermometer(), m_pid.getSSRValue());
                            lock (m_ssr)
                                log.addSSRData(m_tempMgr.getPidThermometer(), m_ssr.getPower());
                        }

                        s  = "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\ncharset=utf-8\r\n\r\n";
                        s += log.dumpData();
                        Debug.Print(s);
                        closeTags = false;     // we're just going to dump the xml out.
                    }

                    /*
                     * These are the form webpages
                     */
                    else if (incoming.IndexOf("GET /control") >= 0)
                    {
                        s += "<head><title>Change PID</title></head><body>Please enter the index of the sensor to use with the PID control<form name=\"input\" action=\"yournewpid\" method=\"get\">Sensor to use: <input type=\"text\" name=\"pid\" /><input type=\"submit\" value=\"Submit\" /></form>";
                    }

                    /*
                     * These are the changes to data
                     */
                    else if (incoming.IndexOf("GET /yournewpid?pid=") >= 0)
                    {
                        //GET /yournewtemp?newTemp=70 HTTP/1.1
                        //try to get the new set temp
                        string tempStr = incoming.Substring(("GET /yournewpid?pid=").Length, incoming.IndexOf(" HTTP/") - ("GET /yournewpid?pid=").Length);
                        int    tempInt = Convert.ToInt32(tempStr);

                        //get rid of the preloaded header, to add a refresh to return the user to the default page
                        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nRefresh: 5; url=http://m8.dyndns-server.com/\r\n\r\n<html><head><title>PID</title></head><body>Setting PID to use sensor <bold>" + tempInt.ToString() + "</bold><br>You will be redirected back";

                        lock (m_tempMgr)
                        {
                            m_tempMgr.setPidThermometer(tempInt);
                        }
                    }
                    else if (incoming.IndexOf("GET /yournewtemp?newTemp=") >= 0)
                    {
                        //GET /yournewtemp?newTemp=70 HTTP/1.1
                        //try to get the new set temp
                        string tempStr = incoming.Substring(("GET /yournewtemp?newTemp=").Length, incoming.IndexOf(" HTTP/") - ("GET /yournewtemp?newTemp=").Length);
                        int    tempInt = Convert.ToInt32(tempStr);

                        //Add refresh to the header to return the user to the default page
                        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nRefresh: 5; url=http://m8.dyndns-server.com/\r\n\r\n<html><head><title>PID</title></head><body>Setting Target Temp to <bold>" + tempInt.ToString() + "</bold><br>You will be redirected back";

                        lock (m_tempMgr)
                        {
                            m_tempMgr.setTarget(tempInt);
                        }
                    }

                    /*
                     * This is the default page
                     */
                    else
                    {
                        //This adds a refresh to the default page
                        //                        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nRefresh: 5; url=http://m8.dyndns-server.com/\r\n\r\n<html>";
                        s += "<head><title>M8 Brewery</title></head><body><table border=\"1\" align=\"center\"><tr><th>Sensor</th><th>Current Temp C</th><th>Target Temp</th><th>PID Result</th><th>PID Control</th></tr>";

                        lock (m_tempMgr)
                            for (int i = 0; i < m_tempMgr.getCount(); i++)
                            {
                                s += "<tr><td>" + i.ToString() + "</td>";
                                s += "<td>" + m_tempMgr.getTemp(i).ToString() + "</td>";
                                s += "<td>" + m_tempMgr.getTarget(i).ToString() + "</td>";

                                s += "<td>";
                                if (m_tempMgr.getPidThermometer() == i)
                                {
                                    lock (m_pid)
                                        s += m_pid.getValue().ToString();
                                }
                                s += "</td>";

                                s += "<td align=\"center\">";
                                if (m_tempMgr.getPidThermometer() == i)
                                {
                                    s += "X";
                                }
                                s += "</td></tr>";
                            }
                        s += "</table><hr><form name=\"input\" action=\"yournewtemp\" method=\"get\">New Target Temp: <input type=\"text\" name=\"newTemp\" /><input type=\"submit\" value=\"Submit\" /></form>";
                    }
                    if (closeTags == true)
                    {
                        //Close the tags
                        s += "<hr>";
                        s += DateTime.Now.ToString();
                        s += "</body></html>";
                    }
                    else
                    {
                        Debug.Print(s);
                    }

                    //We don't have a "facicon.icp" and my browser asks for one right after the page request
                    if (incoming.IndexOf("GET /favicon.ico HTTP/1.1") < 0)
                    {
                        byte[] buf    = Encoding.UTF8.GetBytes(s);
                        int    offset = 0;
                        int    ret    = 0;
                        int    len    = buf.Length;
                        while (len > 0)
                        {
                            ret     = m_clientSocket.Send(buf, offset, len, SocketFlags.None);
                            len    -= ret;
                            offset += ret;
                        }
                    }
                    m_clientSocket.Close();
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// This code will create a TCP socket between this DHCP client and a server node on a specific IP and Port.
        /// ServerIP can be modified to point at the correct Server IP
        /// the main also spins off a serialport thread to monitor the serial port for new GPS Data.
        /// </summary>
        public static void Main()
        {
            SoftwareI2C tempS = new SoftwareI2C((Cpu.Pin)FEZ_Pin.Digital.IO66, (Cpu.Pin)FEZ_Pin.Digital.IO65,400);

                byte[] inBuffer = new byte[2];
                byte[] A = new byte[] { 0x03 }; // A command

                tempS.Transmit(true, false, 0x90); //address
                tempS.Transmit(false, false, 0x00); //register num
                tempS.Transmit(true, false, 0x91); //send read address

                inBuffer[0] = tempS.Receive(true, false);
                inBuffer[1] = tempS.Receive(true, true);

            byte[] mac = { 0x00, 0x26, 0x1c, 0x7b, 0x29, 0xE8 };  //The Network board does not come pre installed with a MAC address
            //Please use(http://www.macvendorlookup.com/) to create a Mac address for you device

            WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di10, (Cpu.Pin)FEZ_Pin.Digital.Di7, true);  //initializes the Panda II hardware to to connect to the FEZ Connect
            //NetworkInterface.EnableStaticIP(ip, subnet, gateway,mac); //This can be used to intialize your client connection if you want to hard code in the network configuration instead of using DHCP
            Dhcp.EnableDhcp(mac, "FEZ");  //Intialize FEZ connect using the mac address "FEZ" is the name of the host change this for multiple clients
            Socket mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  //create network socket
            byte[] ServerIp = { 10, 10, 4, 24 }; //change this to your Server IP
            mysocket.SendTimeout = 3000;
            mysocket.Connect(new IPEndPoint(new IPAddress(ServerIp),9090)); //Connect to server using socket

            OutputPort LED = new OutputPort((Cpu.Pin)69, true);
            LED.Write(!LED.Read());
            string message = "hello Mom\n";
            mysocket.Send(Encoding.UTF8.GetBytes(message));
            InterruptPort IntButton = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.IO4,true,Port.ResistorMode.PullUp,Port.InterruptMode.InterruptEdgeLow); //create button interrupt
            IntButton.OnInterrupt+= new NativeEventHandler(IntButton_ONInterrupt);

            int value;

            while (true)
            {
                if (newstring)
                {
                      Debug.Print(datastring);
                      mysocket.Send(Encoding.UTF8.GetBytes(datastring));        //write string to network socket
                      newstring = false;
                      LED.Write(!LED.Read());
                }
                tempS.Transmit(true, false, 0x90); //send I2C Device write address for dummy write
                tempS.Transmit(false, false, 0x00); //Send Register read address
                tempS.Transmit(true, false, 0x91); //send I2C Device Read address

                inBuffer[0] = tempS.Receive(true, false); //Read MSB (bits 11-4)
                inBuffer[1] = tempS.Receive(true, true);  //Read LSB (bits 0-3 left justified)

                value = (int)inBuffer[0]*256 + inBuffer[0]; //combine MSB and LSB
                value = value>>4;                           //Shift value to right by 4 bits to right justify "value" holds the temperature in deg. C with .0625 Deg. Resolution
                value = (int) ((float)value * .0625);       //The "value" variable now holds the temp in degrees C.
                value = (9 * value) / 5 + 32;               //Convert to deg. f

                Debug.Print(value.ToString());              //Print "value" as a string to the debug port
                if (datastring != (value.ToString() + "\n"))
                {
                    datastring = value.ToString() + "\n";
                    newstring = true;
                }
                Thread.Sleep(500);
            }
        }