[Diao Ye learns programming] MicroPython manual built-in module network - network function module

Insert image description here

MicroPython is a lightweight version of the interpreter designed to run the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control the hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. A powerful module system that provides functions such as file system, network, and graphical interface.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small, and the memory usage is small, which is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

The application scenarios of MicroPython include:
1. Quickly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Pay attention to the following when using MicroPython:
1. The memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.

Insert image description here
MicroPython's built-in module network is a module used to configure and control network interfaces. It can be used to access and control different types of network interfaces on the system, such as WiFi, Ethernet, cellular networks, etc. Its main features are:

1. It can create and operate various network interface-related objects, such as WLAN, LAN, PPP, LTE, etc., to achieve operations such as activation, connection, disconnection, and query of network interfaces.
2. It can use the socket module to communicate through the configured network interface, such as TCP, UDP, HTTP and other protocols.
3. It can use the ssl module to achieve secure network communication, such as TLS, HTTPS and other protocols.
4. It can use the usocket module to implement low-level network communication, such as raw socket, packet socket and other protocols.

The application scenarios of the network module include:

1. Used to connect to different network services or devices, such as routers, servers, sensors, cameras, etc.
2. Used to implement some network-related functions or applications, such as Web development, API calls, data transmission, remote control, etc.
3. Used to learn or teach some network-related knowledge or skills, such as network protocols, network security, Internet of Things, etc.

Notes on the network module include:

1. The network module depends on the network hardware and resources on a specific board. Different MicroPython boards may have different available functions and parameter ranges. You need to check the specific documentation to determine the supported functions and usage methods.
2. The network module provides direct and unrestricted access and control to the network interface. Improper use may cause device failure, lock-up, crash, and in extreme cases, hardware damage. Use caution and follow relevant regulations and guidelines.
3. The callback function used by the network module is executed in the interrupt context 123. It needs to be as short and fast as possible to avoid performing complex or time-consuming operations to avoid affecting system performance and stability.

The following are several practical application cases of MicroPython's built-in module network:

Case 1: Connect to WiFi network using WLAN object

# 导入network模块
import network

# 创建一个WLAN对象,类型为STA_IF(站点接口)
wlan = network.WLAN(network.STA_IF)

# 激活WLAN对象
wlan.active(True)

# 连接到指定的SSID和密码
wlan.connect('your-ssid', 'your-key')

# 等待连接成功
while not wlan.isconnected():
    pass

# 打印当前网络配置信息
print(wlan.ifconfig())

Case 2: Connect to an Ethernet network using LAN objects

# 导入network模块
import network

# 创建一个LAN对象,并指定PHY类型为LAN8720(一种以太网收发器)
lan = network.LAN(mdc=machine.Pin(23), mdio=machine.Pin(18), phy_type=network.PHY_LAN8720, phy_addr=0)

# 激活LAN对象
lan.active(True)

# 等待连接成功
while not lan.isconnected():
    pass

# 打印当前网络配置信息
print(lan.ifconfig())

Case 3: Connecting to a cellular network using LTE objects

# 导入network模块
import network

# 创建一个LTE对象
lte = network.LTE()

# 初始化LTE对象,并设置APN(接入点名称)
lte.init(carrier='standard', apn='your-apn')

# 连接到蜂窝网络
lte.attach()

# 等待连接成功
while not lte.isattached():
    pass

# 建立数据会话
lte.connect()

# 等待会话成功
while not lte.isconnected():
    pass

# 打印当前网络配置信息
print(lte.ifconfig())

Case 4: Connect to Wi-Fi network:

import network

# 连接到Wi-Fi网络
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("SSID", "password")

# 等待连接成功
while not wifi.isconnected():
    pass

# 打印网络信息
print("Connected to Wi-Fi")
print("IP address:", wifi.ifconfig()[0])

In this example, we use the network module's WLAN class to connect to a Wi-Fi network. We first create a WLAN object wifi, and activate the Wi-Fi connection through the active(True) method. Then, use the connect() method to connect to the network by passing the SSID and password of the Wi-Fi network. Next, use a loop to wait for a successful Wi-Fi connection until the isconnected() method returns True. Finally, we print out the network information after the connection is successful, including the IP address.

Case 5: Create and run WebSocket server:

import network
import usocket as socket
import ujson as json

# 创建WebSocket服务器
websocket = network.WLAN(network.AP_IF)
websocket.active(True)
websocket.config(essid="WebSocket Server", password="password")

# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 80))
server_socket.listen(1)

# 等待客户端连接
print("Waiting for client connection...")
client_socket, client_address = server_socket.accept()
print("Client connected:", client_address)

# 接收和发送数据
while True:
    data = client_socket.recv(1024)
    if not data:
        break

    # 处理接收到的数据
    received_data = json.loads(data)
    print("Received data:", received_data)

    # 发送响应数据
    response_data = {
    
    "message": "Hello, client!"}
    response = json.dumps(response_data)
    client_socket.send(response)

# 关闭套接字
client_socket.close()
server_socket.close()

In this example, we create a WebSocket server using the WLAN class of the network module. We first create a WLAN object websocket, and activate the AP mode through the active(True) method. Then, use the config() method to set the server's ESSID and password. Next, we create a socket and bind it to the IP address and port number. Use the listen() method to start listening for client connections. In a loop, we wait for a client to connect and print out the client's address. Then, we receive the data sent by the client and parse it into JSON format. Next, we process the received data and construct a response data to send back to the client. The loop continues until the client disconnects. Finally, we close the socket.

Case 6: Send HTTP GET request and receive response:

import network
import usocket as socket

# 创建套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 建立连接
client_socket.connect(("example.com", 80))

# 发送HTTP GET请求
request = "GET /api/data HTTP/1.0\r\nHost: example.com\r\n\r\n"
client_socket.send(request.encode())

# 接收响应
response = client_socket.recv(1024)
print("Received response:\n", response.decode())

# 关闭套接字
client_socket.close()

In this example, we use the network module and usocket module to create a socket and connect to the remote server through the connect() method. We send a GET request using the HTTP protocol and receive the server's response. Finally, we print out the received response and close the socket.

Case Seven: Another example of connecting to a Wi-Fi network

import network

# 连接到 Wi-Fi 网络
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("SSID", "password")

# 等待连接成功
while not wifi.isconnected():
    pass

# 打印 IP 地址
print("IP 地址:", wifi.ifconfig()[0])

In this example, we import the network module and use it to initialize a Wi-Fi connection. We create a STA (Station) interface through the network.WLAN class, and then use the active(True) method to enable the interface. Next, we use the connect() method to connect to the Wi-Fi network passing the SSID and password. Then, we use a loop to wait for a successful connection (isconnected() returns True), and finally print the obtained IP address. This example shows how to use the network module to connect to a Wi-Fi network.

Case 8: Create and run HTTP server

import network
import usocket as socket

# 创建 Wi-Fi AP
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid="MicroPython-AP")

# 创建 Socket 服务器
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 80))
server_socket.listen(1)

# 接受连接并发送响应
while True:
    client_socket, client_address = server_socket.accept()
    client_socket.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nHello, World!")
    client_socket.close()

In this example, we imported the network module and usocket module and used them to create a Wi-Fi access point (AP) and a Socket server. First, we create an AP interface through the network.WLAN class and enable the interface using the active(True) method. Then, we use the socket.socket() function to create a TCP Socket server and bind to the IP address and port number. Next, we start listening for connections using the listen() method. In an infinite loop, we accept the client connection, send a simple HTTP response, and close the connection. This example shows how to create and run a simple HTTP server using the network and usocket modules.

Case 9: Using UDP for network communication

import network
import usocket as socket

# 创建 UDP Socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind(("0.0.0.0", 8888))

# 接收数据并发送响应
while True:
    data, address = udp_socket.recvfrom(1024)
    print("接收到的数据:", data.decode())
    
    response = "Hello, Client!"
    udp_socket.sendto(response.encode(), address)

In this example, we import the network module and usocket module and use them to create a UDP Socket. We create a UDP Socket using the socket.socket() function and bind to the IP address and port number using the bind() method. Then, in an infinite loop, we receive the data from the client and print the received data. We then generate a simple response message and send the response back to the client using the sendto() method. This example shows how to use the network and usocket modules for basic UDP network communication.

These examples show the use of the network module in MicroPython in action. The network module provides network-related functionality, such as connecting to a Wi-Fi network, creating a network server, performing network communication, and more. By utilizing the network module, you can implement various network functions in MicroPython.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/132775607