简体   繁体   中英

Connect NodeMCU server using C#

I have a NodeMCU 0.9 board with ESP8266E chip. I can turn on and turn off a LED using simple code bellow. This code written using Arduino IDE.

            #include <ESP8266WiFi.h>

            const char* ssid = "iPhone";
            const char* password = "1234567890ABCD";

            int ledPin = D0; // GPIO16
            WiFiServer server(80);

            void setup() {
              Serial.begin(9600);
              delay(10);

              pinMode(ledPin, OUTPUT);
              digitalWrite(ledPin, LOW);

              // Connect to WiFi network
              Serial.println();
              Serial.println();
              Serial.print("Connecting to ");
              Serial.println(ssid);

              WiFi.begin(ssid, password);

              while (WiFi.status() != WL_CONNECTED) {
                delay(500);
                Serial.print(".");
              }
              Serial.println("");
              Serial.println("WiFi connected");

              // Start the server
              server.begin();
              Serial.println("Server started");

              // Print the IP address
              Serial.print("Use this URL to connect: ");
              Serial.print("http://");
              Serial.print(WiFi.localIP());
              Serial.println("/");

            }

            void loop() {
              // Check if a client has connected
              WiFiClient client = server.available();
              if (!client) {
                return;
              }

              // Wait until the client sends some data
              Serial.println("new client");
              while(!client.available()){
                delay(1);
              }

              // Read the first line of the request
              //String request = client.readStringUntil('\r');
              String request = client.readString();
              Serial.println(request);
              client.flush();

              // Match the request

              int value = LOW;
              if (request.indexOf("/LED=ON") != -1)  {
                digitalWrite(ledPin, LOW);
                value = LOW;
              }
              if (request.indexOf("/LED=OFF") != -1)  {
                digitalWrite(ledPin, HIGH);
                value = HIGH;
              }

            // Set ledPin according to the request
            //digitalWrite(ledPin, value);

              // Return the response
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println(""); //  do not forget this one
              client.println("<!DOCTYPE HTML>");
              client.println("<html>");

              client.print("Led pin is now: ");

              if(value == LOW) {
                client.print("On");
              } else {
                client.print("Off");
              }
              client.println("<br><br>");
              client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
              client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />");  
              client.println("</html>");

              delay(1);
              Serial.println("Client disonnected");
              Serial.println("");

            }

Then I can connect to the NodeMCU using my web browser and turn on and off the LED.NodeMCU also send LED status data to the browser. But,I want to do that using C# form application. I tried with this code. It didn't give any compilation error in Visual Studio 2013. But, It cant connect to the NodeMCU server.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net.Sockets;
    using System.Net;


    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {

            static TcpClient tcpClient = new TcpClient();
            public static readonly byte[] ip = new byte[] { 172, 20, 10, 2 };

            static IPAddress ipAddress = new IPAddress(ip);
            IPEndPoint hostEndPoint = new IPEndPoint(ipAddress, 80);
            static Socket soc = new Socket(AddressFamily.InterNetwork,  SocketType.Stream, ProtocolType.IP);
            ASCIIEncoding asen = new ASCIIEncoding();


            public Form1()
            {

                InitializeComponent();

            }


            private void button2_Click(object sender, EventArgs e)
            {
                soc.Connect(ipAddress, 80);
                NetworkStream stm = new NetworkStream(soc);
                tcpClient.Connect(ipAddress, 80);
                stm = tcpClient.GetStream();
                byte[] ba = asen.GetBytes("/LED=ON/r");
                stm.Write(ba,0,ba.Length);
            }

            private void button3_Click(object sender, EventArgs e)
            {
                soc.Connect(ipAddress, 80);
                NetworkStream stm = new NetworkStream(soc);
                tcpClient.Connect(ipAddress, 80);
                stm = tcpClient.GetStream();
                byte[] ba = asen.GetBytes("/LED=OFF/r");
                stm.Write(ba, 0, ba.Length);
            }
        }
    }

Help me to implement a code in C#.

Although you can make HTTP requests using low level APIs, your much better of using the HttpClient class: https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx

Here is a simple example for your button2 event handler:

private async void button2_Click(object sender, EventArgs e)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage request = await client.GetAsync("http://172.16.20.10/LED=on");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM