Application scenarios

Click the button on the browser to control the light, TV, curtain and other operations

Determine the solution

MQTT protocol based on WebSocket is established through the server. Establish a long connection using WebSocket, and then communicate over the WebSocket channel using MQTT protocol. The feasibility of the scheme was verified by investigation and demo.

Why WebSocket

1.WebSocket implements full-duplex communication over a single TCP connection and allows cross-domain communication. 2.WebSocket simplifies the data exchange between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer

steps

1. Register

Follow the message center registration process set up by the company

Required parameters:

AppKey: string udid: string login user id timestamp: Unix timestamp with a time offset greater than 600sCopy the code
2. Establish a long-term connection

Mqtt.js is a client library written in JavaScript that complies with the MQTT protocol and can be used in Node.js and browsers

gitHub: mqtt.js

NPM install MQTT --save or yarn add MQTTCopy the code

Introduce into the project

import mqtt from 'mqtt'; Const options = {connectTimeout: 4000, // Default timeout time 30 * 1000 ms, keepalive: 20, // Heartbeat time, default 60 seconds, set 0 to disable clean:true, // Set tofalseReceive QoS 1 and 2 messages while offline clientId:'abc123wefsa234ddffefe'// clientId username returned after the clientId is registered successfully:'dsdfewfs2912fd50254c798edfef'// Return username password after login:'1dfeefwfsfdfec3f54119fabc123'// Connection password password returned after successful registration} // IP: IP address returned after successful registration: Const client = mqtt.connect(unencrypted connection ws:), 8084(encrypted connection WSS :), this project uses port 8083'ws://ip.xx.xxx.61:8083/mqtt', options);

client.on('reconnect', (error) => {
  console.log('Reconnecting :', error)
});

client.on('error', (error) => {
  console.log('Connection failed :', error)
});

Copy the code
3. Subscribe/publish messages
// Subscribe and publish information after successful connection client.on('connect', (e) => {
  console.log('Connection successful'); Subscribe this.client. Subscribe (subscribe); // Subscribec: Subscribe this.client. // publish: publish under topics returned after registration; PublishMsg: to send the contents of the client. The publish (the publish, publishMsg, (error) = > {the console. The log (error | |'Released successfully'})}) // Receive message client.on('message', (topic, message) => {
  console.log('Received message'); const response = JSON.parse(message.toString()); console.log(response); / /... Business processing})Copy the code

The demo address

MQTT over WebSocket