Computer client remote control Hongmeng development board

Project requirements

When we usually develop projects related to the Internet of things, wireless control is a function we must have. We can control our development board to carry out corresponding operations in real time through the computer client written by us. For example, control a series of operations such as lighting, fan and humidifier of smart home.

development environment

  1. VS Code
  2. HUAWEI DevEco Device Tool(HarmonyOS one-stop integrated development environment for intelligent device developers)
  3. Hiburn (for burning)
  4. VMware
  5. Ubuntu (Linux system)
  6. VS

Technology used

Technology used

UDP

Internet protocol set supports a connectionless transmission protocol, which is called User Datagram Protocol (UDP). UDP provides a method for applications to send encapsulated IP packets without establishing a connection.
The transport layer of Internet has two main protocols, which complement each other. Connectionless is UDP, which does little special except to send packets to applications and allow them to architecture their own protocols at the required level. Connection oriented is TCP, which does almost everything.
UDP protocol is the same as TCP protocol for processing data packets. In the OSI model, both are located at the transport layer and the upper layer of IP protocol. UDP does not provide packet Grouping, assembly and sorting. That is to say, after the message is sent, it is impossible to know whether it arrives safely and completely. UDP is used to support network applications that need to transfer data between computers. Many client / server mode network applications, including network video conference system, need to use UDP protocol. UDP protocol has been used for many years since it came out. Although its initial glory has been covered by some similar protocols, UDP is still a very practical and feasible network transport layer protocol even today.
Method description
Close close UDP connection
Connect establishes a connection to a remote host
DropMulticastGroup exit multicast group
JoinMulticastGroup adds UdpClient to multicast group
Receive returns the UDP datagram sent by the remote host
Send sends the UDP datagram to the remote host

methodexplain
CloseClose UDP connection
ConnectEstablish connection with remote host
DropMulticastGroupExit multicast group
JoinMulticastGroupAdd UdpClient to multicast group
ReceiveReturns the UDP datagram sent by the remote host
SendSend UDP datagram to remote host

Create listening example:

UdpClient udpserver;
private void udpListen()
{
    udpserver = new UdpClient(8888);//The parameter is the port for UDP listening
}

Examples of received data:

private void getMsg()//Start an asynchronous thread to execute the method
{
    //Define an IPEndPoint object to load the IP and port information of the data source
    IPEndPoint remoteIpAndPort = new IPEndPoint(IPAddress.Any, 0);
    while (true)
    {
        //Wait for the message. Note that using this method will block the thread while waiting for the message
        byte[] msgBytes = udpserver.Receive(ref remoteIpAndPort)
        string receivedStr = System.Text.Encoding.UTF8.GetString(msgBytes);
    }
}
 

Example of sending data:

 private void buttonSend_Click(object sender, EventArgs e)
        {
            //Convert the data to be sent into byte array
            byte[] b = System.Text.Encoding.UTF8.GetBytes("Hello");
            //Create target IP port information
            IPEndPoint sendTo = new IPEndPoint(IPAddress.Parse("192.168.1.233"),1234);
            //send data
            this.udpserver.Send(b, b.Length, sendTo);
        }

JSON

JSON introduction

JSON (JavaScript object notation) is a lightweight data exchange format. Based on a subset of ECMAScript (js specification formulated by the European Computer Association), it uses a text format completely independent of the programming language to store and represent data. The concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

JSON syntax rules

JSON is a sequence of tags. This set of tags contains six construction characters, strings, numbers, and three literal names.
JSON is a serialized object or array.

  1. Six construction characters:
    begin-array = ws %x5B ws ; [left square bracket]
    begin-object = ws %x7B ws ; {left brace
    end-array = ws %x5D ws ; ] Right square bracket
    end-object = ws %x7D ws ; } Right brace
    name-separator = ws %x3A ws ; : colon
    value-separator = ws %x2C ws ; , comma
  2. Meaningless white space (ws) is allowed before or after these six construction characters:
    ws = * (% x20 /; space
    %x09 /; Horizontal label
    %x0A /; Line feed or line feed
    %x0D); return trip
  3. JSON value
    Composition of JSON: ws value ws [1]
    The value can be an object, an array, a number, a string, or one of three literals (false, null, true). Literals in values must be lowercase in English.
    The object is composed of comma separated members enclosed in curly braces. The members are string keys and the values described above, which are composed of comma separated key value pairs, such as:
    1

{"name": "John Doe", "age": 18, "address": {"country" : "china", "zip-code": "10000"}}

An array is a set of values enclosed in square brackets, such as:

[3, 1, 4, 1, 5, 9, 2, 6]

Strings are very similar to C or Java strings. A string is a collection of any number of Unicode characters surrounded by double quotes, escaped with a backslash. A character is a single character string.
Numbers are also very similar to those in C or Java. Remove unused octal and hexadecimal formats. Remove some coding details.
Some legal JSON instances:

{"a": 1, "b": [1, 2, 3]}
[1, 2, "3", {"a": 4}]
3.14
"wulianwangzhishi"

Specific design

Function introduction

When the button on the computer side is pressed, the command is issued through UDP, the development board is connected through WiFi module, then the command sent by the computer side is analyzed, and then the corresponding operation is performed on the corresponding command.

Computer client

Page design

Program code

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        UdpClient ctrludpcRecv = null;  //Control command
        IPEndPoint ctrllocalIpep = null;
        public Form1()
        {
            InitializeComponent();
            ctrllocalIpep = new IPEndPoint(IPAddress.Any, 50001); // Native IP and listening port number
            ctrludpcRecv = new UdpClient(ctrllocalIpep);
            ctrludpcRecv.Client.ReceiveBufferSize = 64 * 4096 * 4096;
            ctrludpcRecv.EnableBroadcast = true;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress Adrr;
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                Adrr = IPAddress.Parse("255.255.255.255");
            }
            else
            {
                Adrr = IPAddress.Parse(textBox1.Text);
            }
            IPEndPoint remoteIpep = new IPEndPoint(Adrr, 50001); ;
            JavaScriptSerializer ser = new JavaScriptSerializer();
            CtrlJson rcj = new CtrlJson() { cmd = "RED" };
            string outputJson = ser.Serialize(rcj);
            byte[] sendByte = System.Text.Encoding.Default.GetBytes(outputJson);
            //send out
            ctrludpcRecv.Send(sendByte, sendByte.Length, remoteIpep);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            IPAddress Adrr;
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                Adrr = IPAddress.Parse("255.255.255.255");
            }
            else
            {
                Adrr = IPAddress.Parse(textBox1.Text);
            }
            IPEndPoint remoteIpep = new IPEndPoint(Adrr, 50001); ;
            JavaScriptSerializer ser = new JavaScriptSerializer();
            CtrlJson rcj = new CtrlJson() { cmd = "YELLOW" };
            string outputJson = ser.Serialize(rcj);
            byte[] sendByte = System.Text.Encoding.Default.GetBytes(outputJson);
            //send out
            ctrludpcRecv.Send(sendByte, sendByte.Length, remoteIpep);
        }
        private void button4_Click(object sender, EventArgs e)
        {
            IPAddress Adrr;
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                Adrr = IPAddress.Parse("255.255.255.255");
            }
            else
            {
                Adrr = IPAddress.Parse(textBox1.Text);
            }
            IPEndPoint remoteIpep = new IPEndPoint(Adrr, 50001); ;
            JavaScriptSerializer ser = new JavaScriptSerializer();
            CtrlJson rcj = new CtrlJson() { cmd = "GREEN" };
            string outputJson = ser.Serialize(rcj);
            byte[] sendByte = System.Text.Encoding.Default.GetBytes(outputJson);
            //send out
            ctrludpcRecv.Send(sendByte, sendByte.Length, remoteIpep);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            IPAddress Adrr;
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                Adrr = IPAddress.Parse("255.255.255.255");
            }
            else
            {
                Adrr = IPAddress.Parse(textBox1.Text);
            }
            IPEndPoint remoteIpep = new IPEndPoint(Adrr, 50001); ;
            JavaScriptSerializer ser = new JavaScriptSerializer();
            CtrlJson rcj = new CtrlJson() { cmd = "CLOSE" };
            string outputJson = ser.Serialize(rcj);
            byte[] sendByte = System.Text.Encoding.Default.GetBytes(outputJson);
            //send out
            ctrludpcRecv.Send(sendByte, sendByte.Length, remoteIpep);
        }

    }
}

MCU terminal

Built module

  1. WiFi module
  2. OLED display
  3. Red, green and yellow traffic lights

Main code

char recvline[1024];
void udp_thread(void *pdata)
{
    int ret;
    struct sockaddr_in servaddr;
    cJSON *recvjson;
    pdata = pdata;
    int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
    //Server ip port
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(50001);
    printf("udp_thread \r\n");
    bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    while(1)
    {
        struct sockaddr_in addrClient;
        int sizeClientAddr = sizeof(struct sockaddr_in);
        memset(recvline, sizeof(recvline), 0);
        ret = recvfrom(sockfd, recvline, 1024, 0, (struct sockaddr*)&addrClient,(socklen_t*)&sizeClientAddr);
        if(ret>0)
        {
            char *pClientIP =inet_ntoa(addrClient.sin_addr);
            printf("%s-%d(%d) says:%s\n",pClientIP,ntohs(addrClient.sin_port),addrClient.sin_port, recvline);
            //json parsing
            recvjson = cJSON_Parse(recvline);
            if(recvjson != NULL)
            {
                if(cJSON_GetObjectItem(recvjson, "cmd")->valuestring != NULL)
                {
                    printf("cmd : %s\r\n", cJSON_GetObjectItem(recvjson, "cmd")->valuestring);
                    if(strcmp("RED", cJSON_GetObjectItem(recvjson, "cmd")->valuestring) == 0)
                    {
                        set_LED_status(LED_STATUS_RED);
                        printf("RED\r\n");
                    }
                    if(strcmp("YELLOW", cJSON_GetObjectItem(recvjson, "cmd")->valuestring) == 0)
                    {
                        set_LED_status(LED_STATUS_YELLOW);
                        printf("YELLOW\r\n");
                    }
                    if(strcmp("GREEN", cJSON_GetObjectItem(recvjson, "cmd")->valuestring) == 0)
                    {
                        set_LED_status(LED_STATUS_GREEN);
                        printf("GREEN\r\n");
                    }
                    if(strcmp("CLOSE", cJSON_GetObjectItem(recvjson, "cmd")->valuestring) == 0)
                    {
                        set_LED_status(LED_STATUS_CLOSE);
                        printf("CLOSE\r\n");
                    }
                }             
                cJSON_Delete(recvjson);
            }
		}
    }
}
void start_udp_thread(void)
{
    osThreadAttr_t attr;
    attr.name = "wifi_config_thread";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 2048;
    attr.priority = 36;
    if (osThreadNew((osThreadFunc_t)udp_thread, NULL, &attr) == NULL) {
        printf("[LedExample] Falied to create LedTask!\n");
    }
}

follow-up

Complete source code, you can pay attention to my Programming column.
Or pay attention to WeChat official account, send "computer remote control control Hong Meng development board" to get.

It's not easy to write. Thank you for your support.

Keywords: harmonyos

Added by jkrettek on Sat, 29 Jan 2022 04:39:24 +0200