echo '' ;

ESP8266 NodeMCU Module – NET

The “ESP8266 NodeMCU Module NET” introduces a comprehensive set of functionalities for network communication on the ESP8266 platform using the NodeMCU firmware. This module empowers developers to create versatile IoT applications by enabling connections over Wi-Fi, TCP/IP, and UDP protocols.

Read more: ESP8266 NodeMCU Module – NET

With the NET module, developers can perform various networking tasks such as creating clients and servers, establishing UDP sockets, managing multicast groups, and interacting with DNS servers. This module provides a wide range of functions for initiating, managing, and terminating network connections, as well as for resolving hostnames and configuring DNS servers.

Whether it’s setting up a web server, connecting to cloud services, or implementing peer-to-peer communication, the ESP8266 NodeMCU Module NET offers the necessary tools and capabilities to facilitate seamless networking operations. It serves as a foundational component for building connected devices and IoT solutions powered by the ESP8266 platform.

NET Module Functions for ESP8266 NodeMCU

ConstantDescription
net.createConnection()Creates a client.
net.createServer()Creates a server.
net.createUDPSocket()Creates a UDP socket.
net.multicastJoin()Join multicast group.
net.multicastLeave()Leave multicast group.
net.server:close()Closes the server.
net.server:listen()Listen on port from IP address.
net.server:getaddr()Returns server local address/port.
net.socket:close()Closes socket.
net.socket:connect()Connect to a remote server.
net.socket:dns()Provides DNS resolution for a hostname.
net.socket:getpeer()Retrieve port and IP of remote peer.
net.socket:getaddr()Retrieve local port and IP of socket.
net.socket:hold()Throttle data reception by placing a request to block the TCP receive function.
net.socket:on()Register callback functions for specific events.
net.socket:send()Sends data to remote peer.
net.socket:ttl()Changes or retrieves Time-To-Live value on socket.
net.socket:unhold()Unblock TCP receiving data by revocation of a preceding hold().
net.udpsocket:close()Closes UDP socket.
net.udpsocket:listen()Listen on port from IP address.
net.udpsocket:on()Register callback functions for specific events.
net.udpsocket:send()Sends data to specific remote peer.
net.udpsocket:dns()Provides DNS resolution for a hostname.
net.udpsocket:getaddr()Retrieve local port and IP of socket.
net.udpsocket:ttl()Changes or retrieves Time-To-Live value on socket.
net.dns.getdnsserver()Gets the IP address of the DNS server used to resolve hostnames.
net.dns.resolve()Resolve a hostname to an IP address.
net.dns.setdnsserver()Sets the IP of the DNS server used to resolve hostnames.

Example :1 TCP Connection in local

The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends a message to the server. It also includes event handlers to handle Wi-Fi connection events.

  • Create a TCP connection and communicate with TCP server
  • Set IP of Server

Code

-- www.ArunEworld.com
print("ArunEworld : TCP Example")

-- Connect to Access Point (DO NOT save config to flash)
wifi.setmode(wifi.STATIONAP)

station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "ArunEworld.com"
wifi.sta.config(station_cfg)
wifi.sta.connect()

function TCP_CONNECTION_func()
    TCP_Conn = net.createConnection(net.TCP, 0)
    TCP_Conn:connect(80, '192.168.1.102') -- Change your server IP

    TCP_Conn:on("connection", function(TCP_Conn, payload)
        print("Connection_func : ")
        print(payload)
    end)

    TCP_Conn:on("receive", function(TCP_Conn, payload)
        print("Received : " .. payload)
    end)

    TCP_Conn:send("ArunEworld : This ESP8266 is Connected to TCP Server\n")
end

-- Wifi Event Monitoring
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
    print("\n\tSTA - CONNECTED" ..
          "\n\tSSID: " .. T.SSID ..
          "\n\tBSSID: " .. T.BSSID ..
          "\n\tChannel: " .. T.channel)
end)

wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
    print("\n\tSTA - DISCONNECTED" ..
          "\n\tSSID: " .. T.SSID ..
          "\n\tBSSID: " .. T.BSSID ..
          "\n\tReason: " .. T.reason)
    TCP_Conn = nil
end)

wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
    print("\n\tSTA - GOT IP" ..
          "\n\tStation IP: " .. T.IP ..
          "\n\tSubnet Mask: " .. T.netmask ..
          "\n\tGateway IP: " .. T.gateway)
    TCP_CONNECTION_func()
end)

Code Explanation

Certainly! Here’s an explanation of the provided Lua code:

  1. Print Statement:
   print("ArunEworld : TCP Example")

This line prints out the string "ArunEworld : TCP Example". It serves as an informational message indicating the purpose of the code.

  1. Wi-Fi Configuration:
   wifi.setmode(wifi.STATIONAP)

This line sets the Wi-Fi mode to STATIONAP, allowing the device to connect to an existing Wi-Fi network as a station while also creating an access point.

   station_cfg = {}
   station_cfg.ssid = "ArunEworld"
   station_cfg.pwd = "ArunEworld.com"
   wifi.sta.config(station_cfg)
   wifi.sta.connect()

These lines configure the Wi-Fi station mode with the SSID and password of the target network. It then attempts to connect to the configured network.

  1. TCP Connection Setup:
   function TCP_CONNECTION_func()
       TCP_Conn = net.createConnection(net.TCP, 0)
       TCP_Conn:connect(80, '192.168.1.102') -- Change your server IP
   end

This function sets up a TCP connection to the specified server IP address (192.168.1.102) on port 80.

  1. TCP Event Handlers:
   TCP_Conn:on("connection", function(TCP_Conn, payload)
       print("Connection_func : ")
       print(payload)
   end)

This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which prints out the connection payload.

   TCP_Conn:on("receive", function(TCP_Conn, payload)
       print("Received : " .. payload)
   end)

This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.

  1. Sending Data:
   TCP_Conn:send("ArunEworld : This ESP8266 is Connected to TCP Server\n")

This line sends a message to the TCP server after the connection is established.

  1. Wi-Fi Event Monitoring:
   wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
       -- Event handler for when the Wi-Fi station is connected
       -- Print out details about the connection
   end)

   -- Similar event handlers are registered for other Wi-Fi events like disconnection and obtaining an IP address.

Example :1 TCP Connection to httpbin.org  site (Onlin)

print("ww.ArunEworld.com")
print("wifi init")

--wifi.start() -- commented out

wifi.setmode(wifi.STATIONAP) -- connect to Access Point (DO NOT save config to flash)

station_cfg = {}
station_cfg.ssid = "ArunEworld"
station_cfg.pwd = "ArunEworld.com"
wifi.sta.config(station_cfg)
wifi.sta.connect()

srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c)
    print(c)
end)

-- Wait for connection before sending.
srv:on("connection", function(sck, c)
    -- 'Connection: close' rather than 'Connection: keep-alive' to have server
    -- initiate a close of the connection after final response (frees memory
    -- earlier here), https://tools.ietf.org/html/rfc7230#section-6.6
    sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
end)

srv:connect(80, 'httpbin.org')

Explanation

The code sets up a Wi-Fi connection, establishes a TCP connection to a server, and sends an HTTP GET request to retrieve data from httpbin.org. Any received data is printed to the console.

  1. Print Statements:
   print("ww.ArunEworld.com")
   print("wifi init")

These lines print out the strings "ww.ArunEworld.com" and "wifi init". They are for informational purposes and help indicate the progress of the program.

  1. Wi-Fi Configuration:
   wifi.setmode(wifi.STATIONAP)

This line sets the Wi-Fi mode to STATIONAP, which allows the device to connect to an existing Wi-Fi network as a station while also creating an access point.

   station_cfg = {}
   station_cfg.ssid = "ArunEworld"
   station_cfg.pwd = "ArunEworld.com"
   wifi.sta.config(station_cfg)
   wifi.sta.connect()

These lines configure the Wi-Fi station mode with the SSID and password of the target network. It then attempts to connect to the configured network.

  1. TCP Connection Setup:
   srv = net.createConnection(net.TCP, 0)

This line creates a TCP connection object named srv.

   srv:on("receive", function(sck, c)
       print(c)
   end)

This sets up an event handler for the “receive” event. When data is received over the TCP connection, the provided function is called, which prints out the received data.

   srv:on("connection", function(sck, c)
       sck:send("GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nAccept: */*\r\n\r\n")
   end)

This sets up an event handler for the “connection” event. When the TCP connection is established, the provided function is called, which sends an HTTP GET request to httpbin.org. The request includes the path /get and necessary headers.

  1. Connect to Server:
   srv:connect(80, 'httpbin.org')

This line initiates the connection to the server at httpbin.org on port 80 (the standard HTTP port).


See also


Next

NodeMCU Get Start
NodeMCU Build Firmware
NodeMCU Flash Firmware
NodeMCU IDE
ESP8266 NodeMCU Modules
NodeMCU Module–Firmware Info
NodeMCU Module – GPIO
NodeMCU Module – Node
NodeMCU Module – WiFi
NodeMCU Module – Timer
NodeMCU Module – I2C
NodeMCU Module – File
NodeMCU Module – NET
NodeMCU Module – HTTP
NodeMCU Module – MQTT
ESP8266 NodeMCU Interface
NodeMCU Interface LED
NodeMCU Interface Button
NodeMCU Interface 7 Seg
NodeMCU Interface LCD
NodeMCU Interface ADC
NodeMCU Interface DHT11
NodeMCU Interface MCP23008
NodeMCU Interface MCP23017
NodeMCU Interface ADXL345
NodeMCU Interface DS18B20
ESP8266 NodeMCU Tutorials
NodeMCU Tutorials Google Time
NodeMCU Tutorials WebServer
ESP8266 NodeMCU Projects
Imperial March Ringtone Play
WiFi Router Status Indicator
ESP8266 Home Automation
Others
NodeMCU All Post
Sitemap

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from ArunEworld

Subscribe now to keep reading and get access to the full archive.

Continue reading