The background,

In the era of the Internet of Things, the technology began to serve the public on a large scale, and it is particularly important to be convenient and quick. WIFI direct connection is a typical case.

At present, there are two mainstream WIFI configuration modes:

1. Smart hardware is in AP mode (similar to router, forming LAN), and mobile phone is in STA mode

After the mobile phone is connected to the intelligent hardware in AP mode, the LAN is formed. The mobile phone sends the SSID and password that need to be connected to the intelligent hardware, and the intelligent hardware initiatively connects to the specified route to complete the network configuration

2. One-click Network configuration (smartConfig) mode

Intelligent hardware monitors all packets in the network in promiscuous mode. The MOBILE phone APP encodes the SSID and password into UDP packets and sends them through broadcast packets or multicast packets. After receiving the UDP packets, the intelligent hardware decodes the packets to obtain the correct SSID and password, and then initiatively connects the route of the specified SSID to complete the connection.

AP mode:

AP stands for (Wireless) Access Point. Simply speaking, it is like a wireless router. When the device is turned on and entered AP mode, the SSID similar to TPLINK_XXX can be searched in the network list of the mobile phone.

Connection steps:

1. Initialize the smart hardware device and enter AP mode. After detecting the intelligent hardware device (SSID), connect to the intelligent hardware device and send the SSID /password/ Token encrypted by AES through UDP. 3. The intelligent hardware device obtains configuration information through UDP packet, switches network mode, connects to WIFI, and completes network configuration

SmartConfig mode:

This fast connection mode is more close to the market than AP mode connection

1. Connect the mobile phone to WiFi, open the smart hardware designated APP, enter the configuration interface, and enter the WiFi password of the mobile phone. 3. Mobile phone sends ssiD /password/ TOKEN through broadcast and multicast loop. 4. Hardware device obtains configuration information through UDP packet (length) and captures SSID /password/ TOKEN. Connect to router (broadcast based on UDP packet length, multicast based on IP address information)

In principle, as long as the chip driver supports WiFi Promiscuous mode, one-click network interface can be supported

Mobile phone encoding and transmission can be UDP multicast or broadcast. Different sending methods and encoding have different decoding processes

1. Broadcast:

The sender can control by changing the Length of the packet it needs to send. Therefore, as long as a communication protocol using Length coding is specified, the Length field of the packet can be used for data transmission

2. Multicast:

Multicast addresses are reserved for class D addresses ranging from 224.0.0.0 to 239.255.255.255

The mapping between THE IP address and MAC address is as follows: Set the first 25 bits of the MAC address to 01.00.5e, and the last 23 bits of the MAC address to the IP address bit

Therefore, the sender can encode the data in the last 23bit of the multicast IP address, and decode the data through the sending and receiving end of the multicast packet

Ii. Brief analysis of smartConfig principle

If no communication link of any nature is established between the smartConfig technology and other devices, configure the device to access the WIFI network

Normal permission applications do not have the ability to fully control and define the transport layer and the underlying protocol data, the only thing that can be fully controlled is the application layer data

In essence, the data length of UDP packet header is used as smartConfig data. The APP and device can parse the data by sharing a code table

Data structures at the network layer and transport layer in the TCP/IP stack

The most commonly used network-layer protocol is IPv4, whose header is almost always 20 bytes long

The transport layer protocol is UDP because the UDP protocol header has a fixed length of 8 bytes

Plaintext length = 20 + 8 + dataLen

Ciphertext length = 20 + 8 + dataLen + Algorithm constant

Example:

If you want to send an 802.11 frame with a ciphertext length of 500 bytes, you only need to fill the UDP with any (500-20-8 – algorithm always lit) bytes of data

Therefore, just define a code table with controllable ciphertext length (dataLen) and tell the data to any device that knows this code table (IoT hardware device)

To customize an encoding table, the process is as follows:

DataLen –> map 1234 –> start character; Three consecutive starts, used to indicate the beginning of data transfer 1324 –> end; Three consecutive terminators, used to indicate the end of data transfer 110 –> interval; Two consecutive interval characters, used to represent the interval between data characters 1000 –> data characters; Represents ASCII 0x00 1001 –> data character; Represents ASCII 0x01… 1127 –> data character; ASCII 0 x7f said

Suppose we want to tell the camera the string “Jay”, and the process looks something like this:

APP end: Open the mobile APP, fill in the input box with the string “Jay” to be sent, and click Send:

1.1. APP sends three UDP broadcast packets with 1190 bytes of 0x00 data (1234 — 16 — 20 — 8 = 1190), indicating the start of transmission Fill data is 1030 bytes 0x00 data (1074 — 16-20 — 8 = 1030), transfer character J 1.3, APP sends 2 UDP broadcast packets continuously, The fill data is 66 bytes of 0x00 data (110-16-20-8 = 66), indicating that the data interval is 1.4. APP sends 1 UDP broadcast packet. Fill data is 1053 bytes 0x00 data (1097 — 16-20 — 8 = 1053), transmission character 1097 corresponds to a 1.5, APP sends two UDP broadcast packets continuously, The fill data is 66 bytes of 0x00 data (110-16-20-8 = 66), indicating that the data interval is 1.6. APP sends 1 UDP broadcast packet. Fill data is 1077 bytes 0x00 data (1121 — 16-20 — 8 = 1077), transmission character 1121 corresponds to Y 1.7, APP sends three UDP broadcast packets continuously, The filled data contains 1280 bytes of 0x00 data (1324-16-20-8 = 1280), indicating that the transfer is complete

Repeat step 1.1 until the IoT device times out or connects to WIFI successfully

IoT device side:

The device is powered on and enters promiscuous mode. It starts to monitor all WIFI data frames within the signal coverage range

Capture data frames. If three consecutive ciphertexts are received, dataLen is 1234 bytes, and the data frames are from the same transmitting source channel-A, the next step is performed. Otherwise, the next step is performed

The data frames of the transmitting source channel-A are captured, and the data frames with the length of ciphertext 110 or 1000-1127 are captured until three consecutive data frames with length of ciphertext 1324 are captured

The above data frames are mapped according to the code table. Since the mobile APP is not exclusive to the network, the captured data may be noisy, for example, the decoded result may be (/ indicates separator): mnJ/o@a/ YMmm

If there is no noise, it is recorded as candidate data RC, and X is captured repeatedly for secondary verification. If it passes, it means that the reception is complete. If it fails, channel-A is captured repeatedly.

Intersect this result with the previous one, and repeat until you get a unique result, RC, and then repeat 5

Since the captured data frame header information already contains THE BSSID information of WIFI, “Jay” is used as the password to try to connect to the corresponding WIFI

ESP32 distribution network example:

Mobile phone APP:

ESP-TOUCH

Write device end:

#include “WiFi.h”

void setup() { Serial.begin(115200);

//Init WiFi as Station, start SmartConfig WiFi.mode(WIFI_AP_STA); WiFi.beginSmartConfig();

//Wait for SmartConfig packet from mobile Serial.println(“Waiting for SmartConfig.”); while (! WiFi.smartConfigDone()) { delay(500); Serial.print(“.”); }

Serial.println(“”); Serial.println(“SmartConfig received.”);

//Wait for WiFi to connect to AP Serial.println(“Waiting for WiFi”); while (WiFi.status() ! = WL_CONNECTED) { delay(500); Serial.print(“.”); }

Serial.println(“WiFi Connected.”);

Serial.print(“IP Address: “); Serial.println(WiFi.localIP()); }

void loop() { // put your main code here, to run repeatedly:

} 4. Knowledge expansion

There are three communication modes in current network communication:

Unicast, broadcast, multicast (also called multicast), among which multicast appeared the last time, but with the advantages of unicast and broadcast, the most promising.

Communication mode classification:

1. Unicast: communication between single hosts;

2. Broadcast: communication between a single host and all hosts in the network;

3. Multicast: communication between a single host and a selected group of hosts;

Unicast:

Unicast is the most common in network communication. The communication between network nodes is just like the conversation between people. If one person talks to another person, it is described as “unicast” in network technical terms, in which information is received and transmitted only between two nodes.

1. Unicast advantages:

(1) The server and the response client request;

(2) The server can send different responses to different requests from each client, and it is easy to display personalized services;

2. Disadvantages of unicast:

The server sends a data stream for each client, server traffic = number of clients x client traffic; In the streaming media application with large number of clients and large traffic per client, the server is overwhelmed.

3. Application Scenarios

Unicast has been widely used in the network. Most of the data on the network is transmitted in the form of unicast. For example, when sending and receiving emails and visiting web pages, you must establish a connection with mail server and server.

UDP unicast:

import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress;

Public class ClientTest {private static final int MAXRECEIVED = 255;

public static void main(String[] args) throws IOException { byte[] msg = new String("connect test successfully!!!" ).getBytes(); DatagramSocket client = new DatagramSocket(); InetAddress inetAddr = InetAddress.getLocalHost(); SocketAddress socketAddr = new InetSocketAddress(inetAddr, 8888); DatagramPacket sendPacket = new DatagramPacket(msg, msg.length, socketAddr); client.send(sendPacket); client.close(); }Copy the code

}

import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.util.Arrays;

Public class ServerTest {private static final int MAXREV = 255;

public static void main(String[] args) throws IOException { DatagramSocket server = new DatagramSocket(8888); DatagramPacket recvPacket = new DatagramPacket(new byte[MAXREV], MAXREV); while (true) { server.receive(recvPacket); byte[] receiveMsg = Arrays.copyOfRange(recvPacket.getData(), recvPacket.getOffset(), recvPacket.getOffset() + recvPacket.getLength()); System.out.println("Handing at client " + recvPacket.getAddress().getHostName() + " ip " + recvPacket.getAddress().getHostAddress()); System.out.println("Server Receive Data:" + new String(receiveMsg)); server.send(recvPacket); }}Copy the code

} broadcasting:

Broadcasting can be compared to speaking as one person to all present through a loudspeaker. In other words, broadcasting is a host sending datagrams to all hosts on a network.

The network may be a network, a subnet, or all subnets.

There are two types of broadcasting: local broadcasting and directional broadcasting:

Directed broadcast: sending datagram packets to all hosts on a specific network outside the local network. Most routers on the Internet do not forward directed broadcast messages.

Local broadcast: A router will not forward a packet sent to all hosts on the local network with IPv4 local broadcast address 255.255.255.255.

1. Advantages of radio:

(1) High efficiency of communication, information can be transmitted to all hosts on a certain network.

(2) Because the server does not need to send data to each client individually, the server traffic is relatively low;

2. Disadvantages of radio:

(1) Very occupy the network bandwidth;

(2) Lack of pertinence, and regardless of whether the host really needs to receive the data, it is forced to receive the data;

3. Application Scenarios

Cable TV is a typical broadcast network

UDP broadcast:

import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress;

Public class BroadcastSender {public static void main(String[] args) throws IOException {byte[] MSG = new String(“connection successfully!!!” ).getBytes(); /* * In Java UDP unicast and broadcast code is the same, to implement a program with broadcast function only need to use broadcast address, for example: The local broadcast address */ InetAddress inetAddr = inetaddress.getByName (“255.255.255.255”) is used. DatagramSocket client = new DatagramSocket();

    DatagramPacket sendPack = new DatagramPacket(msg, msg.length, inetAddr,
            8888);

    client.send(sendPack);
    System.out.println("Client send msg complete");
    client.close();
}
Copy the code

}

import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.util.Arrays;

Public class BroadcastReceive {public static void main(String[] args) throws IOException {

    DatagramPacket receive = new DatagramPacket(new byte[1024], 1024);
    DatagramSocket server = new DatagramSocket(8888);

    System.out.println("---------------------------------");
    System.out.println("Server current start......");
    System.out.println("---------------------------------");

    while (true)
    {
        server.receive(receive);

        byte[] recvByte = Arrays.copyOfRange(receive.getData(), 0,
                receive.getLength());

        System.out.println("Server receive msg:" + new String(recvByte));
    }

}
Copy the code

} multicast:

Multicast can be compared to Shouting at the street: ladies get free coupons, women will come, men won’t come (multicast: all the women are a group)

In other words: multicast is a host to send datagram packets to a specified group of hosts, because if unicast mode is adopted, node by node transmission, there will be as many times as there are target nodes transmission process, this method is obviously very low efficiency, is not desirable; If the broadcast mode is adopted, all data can be transmitted at one time, but it obviously fails to distinguish specific data receiving objects and occupies network bandwidth. Using multicast mode, the data of all target nodes can be transmitted at one time, and the data of specific objects can be transmitted only.

Multicast IP addresses are generally implemented by multicast IP addresses, which are class D IP addresses ranging from 224.0.0.0 to 239.255.255.255.

1. Advantages of multicast:

(1) Having all the advantages of broadcasting;

(2) Compared with unicast, it provides the efficiency of sending datagram packet, and reduces network traffic compared with broadcast;

2. Disadvantages of multicast:

Compared with unicast protocol, there is no error correction mechanism, and it is difficult to make up for packet loss and error, but it can be made up through certain fault tolerance mechanism and QOS.

UDP multicast:

import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket;

// Client public class MulticastSender {public static void main(String[] args) throws IOException {int port = 8888; byte[] msg = “Connection successfully!!!” .getBytes();

InetAddress inetRemoteAddr = InetAddress. GetByName (" 224.0.0.5 "); /* * Java UDP multicast applications communicate primarily through MulticastSocket instances, a subclass of DatagramSocket that contains some additional properties for controlling multicast. * * Note: * * Multicast datagram packets can actually be sent over the DatagramSocket by simply specifying a multicast address. * We use MulticastSocket here because it has capabilities that DatagramSocket does not */ MulticastSocket client = new MulticastSocket(); DatagramPacket sendPack = new DatagramPacket(msg, msg.length, inetRemoteAddr, port); client.send(sendPack); System.out.println("Client send msg complete"); client.close(); }Copy the code

}

import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.util.Arrays;

// Server public class MulticastReceive {public static void main(String[] args) throws IOException {InetAddress 224.0.0.5 inetRemoteAddr = InetAddress. GetByName (” “);

DatagramPacket recvPack = new DatagramPacket(new byte[1024], 1024); MulticastSocket server = new MulticastSocket(8888); /* * If you want to send a datagram packet, you can not join the multicast group. If it is to receive datagram packets, it must be added to a multicast group. Here is receiving datagram packet, so must join multicast group; */ server.joinGroup(inetRemoteAddr); System.out.println("---------------------------------"); System.out.println("Server current start......" ); System.out.println("---------------------------------"); while (true) { server.receive(recvPack); byte[] recvByte = Arrays.copyOfRange(recvPack.getData(), 0, recvPack.getLength()); System.out.println("Server receive msg:" + new String(recvByte)); }}Copy the code

} refer:

Wenku.baidu.com/view/ab6bc0… Blog.csdn.net/sadshen/art…

My.oschina.net/u/2396236/b… Blog.csdn.net/li_yangyang… Blog.csdn.net/flyingcys/a…

Blog.csdn.net/dabing69221…