From c7ef40fa85c2b4c894dbba1f872a008046b49270 Mon Sep 17 00:00:00 2001 From: emqx-ci-robot Date: Thu, 26 Dec 2024 11:03:32 +0000 Subject: [PATCH] sync blog --- README.md | 4 +- en/202010/how-to-use-mqtt-in-vue.md | 278 ----------------- .../how-to-use-mqtt-in-electron.md | 295 ++++++++---------- en/202411/how-to-use-mqtt-in-vue.md | 212 +++++++++++++ 4 files changed, 352 insertions(+), 437 deletions(-) delete mode 100644 en/202010/how-to-use-mqtt-in-vue.md rename en/{202010 => 202411}/how-to-use-mqtt-in-electron.md (52%) create mode 100644 en/202411/how-to-use-mqtt-in-vue.md diff --git a/README.md b/README.md index a0778ba4..669a385e 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,8 @@ Get to know the preferred protocol in IoT from beginner to master. ## [MQTT Programming](https://www.emqx.com/en/blog/category/mqtt-programming) Best practice of MQTT in various clients. +- [How to Integrate MQTT in Your Electron Project](https://www.emqx.com/en/blog/how-to-use-mqtt-in-electron) ([Edit](https://github.com/emqx/blog/blob/main/en/202411/how-to-use-mqtt-in-electron.md)) +- [How to Use MQTT in Vue Projects](https://www.emqx.com/en/blog/how-to-use-mqtt-in-vue) ([Edit](https://github.com/emqx/blog/blob/main/en/202411/how-to-use-mqtt-in-vue.md)) - [How to Use MQTT with PHP: A Guide for Real-Time Messaging](https://www.emqx.com/en/blog/how-to-use-mqtt-in-php) ([Edit](https://github.com/emqx/blog/blob/main/en/202411/how-to-use-mqtt-in-php.md)) - [A Guide on Collecting and Reporting Soil Moisture with ESP32 and Sensor through MQTT](https://www.emqx.com/en/blog/hands-on-guide-on-esp32) ([Edit](https://github.com/emqx/blog/blob/main/en/202408/hands-on-guide-on-esp32.md)) - [MQTT on ESP32: A Beginner's Guide](https://www.emqx.com/en/blog/esp32-connects-to-the-free-public-mqtt-broker) ([Edit](https://github.com/emqx/blog/blob/main/en/202408/esp32-connects-to-the-free-public-mqtt-broker.md)) @@ -139,8 +141,6 @@ Best practice of MQTT in various clients. - [How to Use MQTT in The React Native Project](https://www.emqx.com/en/blog/how-to-use-mqtt-in-react-native) ([Edit](https://github.com/emqx/blog/blob/main/en/202206/how-to-use-mqtt-in-react-native.md)) - [How to use MQTT in Flask](https://www.emqx.com/en/blog/how-to-use-mqtt-in-flask) ([Edit](https://github.com/emqx/blog/blob/main/en/202205/how-to-use-mqtt-in-flask.md)) - [Python MQTT Asynchronous Framework - HBMQTT](https://www.emqx.com/en/blog/python-async-mqtt-client-hbmqtt) ([Edit](https://github.com/emqx/blog/blob/main/en/202104/python-async-mqtt-client-hbmqtt.md)) -- [How to use MQTT in the Electron project](https://www.emqx.com/en/blog/how-to-use-mqtt-in-electron) ([Edit](https://github.com/emqx/blog/blob/main/en/202010/how-to-use-mqtt-in-electron.md)) -- [How to use MQTT in the Vue project](https://www.emqx.com/en/blog/how-to-use-mqtt-in-vue) ([Edit](https://github.com/emqx/blog/blob/main/en/202010/how-to-use-mqtt-in-vue.md)) - [Comparison of Python MQTT Clients](https://www.emqx.com/en/blog/comparision-of-python-mqtt-client) ([Edit](https://github.com/emqx/blog/blob/main/en/202010/comparision-of-python-mqtt-client.md)) - [Android and MQTT: Step by Step Guide](https://www.emqx.com/en/blog/android-connects-mqtt-using-kotlin) ([Edit](https://github.com/emqx/blog/blob/main/en/202006/android-connects-mqtt-using-kotlin.md)) - [Upload Sensor Data to MQTT Cloud Service via NodeMCU (ESP8266)](https://www.emqx.com/en/blog/upload-sensor-data-to-mqtt-cloud-service-via-nodemcu-esp8266) ([Edit](https://github.com/emqx/blog/blob/main/en/201912/upload-sensor-data-to-mqtt-cloud-service-via-nodemcu-esp8266.md)) diff --git a/en/202010/how-to-use-mqtt-in-vue.md b/en/202010/how-to-use-mqtt-in-vue.md deleted file mode 100644 index cf82605e..00000000 --- a/en/202010/how-to-use-mqtt-in-vue.md +++ /dev/null @@ -1,278 +0,0 @@ -[Vue](https://vuejs.org) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries. - -[MQTT](https://mqtt.org/) is a kind of **lightweight IoT messaging protocol** based on the publish/subscribe model. This protocol provides one-to-many message distribution and decoupling of applications. It has several advantages which are low transmission consumption and protocol data exchange, minimized network traffic, and three different service quality levels of messages which can meet different delivery needs. - -This article mainly introduces how to use MQTT in the Vue project, and implements the connection, subscription, messaging, unsubscribing and other functions between the client and MQTT broker. - -> To create an MQTT connection in Vue 3 application using MQTT.js, please refer to https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Vue3.js - -## Project initialization - -### Create project - -The reference link is as follows: - -- [Use Vue CLI create Vue project](https://cli.vuejs.org/guide/creating-a-project.html#vue-create) -- [Create Vue project through introduce Vue.js](https://vuejs.org/v2/guide/installation.html) - -Examples: - -```shell -vue create vue-mqtt-test -``` - -### Install MQTT client library - -> The following method 2 and 3 are more suitable for the project that directly introduces Vue.js. - -1. Installed from the command line, either using npm or yarn (one or the other) - - ``` - npm install mqtt --save - # or yarn - yarn add mqtt - ``` - -2. Import via CDN - - ```html - - ``` - -3. Download locally, then import using relative paths - - ```html - - ``` - - - -## The use of MQTT - -### Connect to the MQTT broker - -This article will use the [free public MQTT broker](https://www.emqx.com/en/mqtt/public-mqtt5-broker) provided by EMQX. This service was created based on the EMQX [MQTT IoT cloud platform](https://www.emqx.com/en/cloud). The information about broker access is as follows: - -- Broker: **broker.emqx.io** -- TCP Port: **1883** -- WebSocket Port: **8083** -- WebSocket Secure Port: **8084** - -
-
- Open Manufacturing Hub -
-
-
- A Practical Guide to MQTT Broker Selection -
-
- Download this practical guide and learn what to consider when choosing an MQTT broker. -
- Get the eBook → -
-
- -The key code of connection: - -```vue - -``` - -### Subscribe topic - -```js -doSubscribe() { - const { topic, qos } = this.subscription - this.client.subscribe(topic, { qos }, (error, res) => { - if (error) { - console.log('Subscribe to topics error', error) - return - } - this.subscribeSuccess = true - console.log('Subscribe to topics res', res) - }) -} -``` - -### Unsubscribe - -```js -doUnSubscribe() { - const { topic } = this.subscription - this.client.unsubscribe(topic, error => { - if (error) { - console.log('Unsubscribe error', error) - } - }) -} -``` - -### Publish messages - -```js -doPublish() { - const { topic, qos, payload } = this.publish - this.client.publish(topic, payload, { qos }, error => { - if (error) { - console.log('Publish error', error) - } - }) -} -``` - -### Disconnect - -```js -destroyConnection() { - if (this.client.connected) { - try { - this.client.end(false, () => { - this.initData() - console.log('Successfully disconnected!') - }) - } catch (error) { - console.log('Disconnect failed', error.toString()) - } - } -} -``` - - - -## Test - -We use Vue to write the following simple browser application. This application has: create connections, subscribe topics, messaging, unsubscribe, disconnect and other functions. - -The complete code for this project: [https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Vue.js](https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Vue.js)。 - -![vueui.png](https://assets.emqx.com/images/b6563b0eb66eb51a2a02776889016a18.png) - - - -Use [MQTT 5.0 client tool - MQTTX](https://mqttx.app/) as another client to test messaging. - -![vuemqttx.png](https://assets.emqx.com/images/2013cbab1bdffcae69b817bfebb4a33f.png) - -If you unsubscribe on the browser side, before MQTTX sends the second message, the browser will not receive the subsequent messages from MQTTX. - - - -## Summary - -In summary, we have implemented the creation of an MQTT connection in a Vue project, simulated subscribing, sending and receiving messages, unsubscribing, and disconnecting between the client and MQTT broker. - -As one of the three most popular front-end frames, Vue can be used on the browser-side, and can also be used on the mobile side. Combining the MQTT protocol and [MQTT cloud service](https://www.emqx.com/en/cloud), can develop many interesting applications, for example, a customer service chat system or a management system that monitors IoT device information in real-time. - -Next, you can check out [The Easy-to-understand Guide to MQTT Protocol](https://www.emqx.com/en/mqtt-guide) series of articles provided by EMQ to learn about MQTT protocol features, explore more advanced applications of MQTT, and get started with MQTT application and service development. - -## Resources - -- [How to Use MQTT in React](https://www.emqx.com/en/blog/how-to-use-mqtt-in-react) -- [How to Use MQTT in Angular](https://www.emqx.com/en/blog/how-to-use-mqtt-in-angular) -- [How to Use MQTT in Electron](https://www.emqx.com/en/blog/how-to-use-mqtt-in-electron) -- [How to Use MQTT in Node.js](https://www.emqx.com/en/blog/how-to-use-mqtt-in-nodejs) -- [A Quickstart Guide to Using MQTT over WebSocket](https://www.emqx.com/en/blog/connect-to-mqtt-broker-with-websocket) - - -
-
- Try EMQX Cloud for Free -
No credit card required
-
- Get Started → -
diff --git a/en/202010/how-to-use-mqtt-in-electron.md b/en/202411/how-to-use-mqtt-in-electron.md similarity index 52% rename from en/202010/how-to-use-mqtt-in-electron.md rename to en/202411/how-to-use-mqtt-in-electron.md index 0c4b38cd..f65b984e 100644 --- a/en/202010/how-to-use-mqtt-in-electron.md +++ b/en/202411/how-to-use-mqtt-in-electron.md @@ -1,32 +1,36 @@ -[Electron](https://www.electronjs.org/) is an open-source software framework developed and maintained by GitHub. It allows for the development of desktop GUI applications using web technologies: it combines the Chromium rendering engine and the Node.js runtime. Electron is the main GUI framework behind several notable open-source projects including Atom, GitHub Desktop, Light Table, Visual Studio Code, and WordPress Desktop.[^1] +## Introduction -A basic Electron includes three files: `package.json` (metadata) `main.js` (code) and `index.html` (graphical user interface). The frame is provided by the Electron executable file (electron.exe on Windows, electron.app on macOS, electron on Linux). Developers are free to add flags, customize icons, rename or edit Electron executable files. +[Electron](https://www.electronjs.org/) is an open-source software framework developed and maintained by GitHub. It enables developers to create desktop GUI applications using web technologies by combining the Chromium rendering engine and the Node.js runtime. Electron is the main GUI framework behind several notable projects including open-source applications like Visual Studio Code and GitHub Desktop, as well as commercial applications such as Slack, Discord, and Microsoft Teams. -This article mainly introduces how to use [MQTT](https://www.emqx.com/en/mqtt-guide) in Electron projects, and complete a simple MQTT desktop client, and implement the connection, subscription, unsubscribe, messaging and other functions between the client and [MQTT broker](https://www.emqx.com/en/products/emqx). +A basic Electron includes three files: `package.json` (metadata), `main.js` (code), and `index.html` (graphical user interface). The frame is provided by the Electron executable file (electron.exe on Windows, electron.app on macOS, electron on Linux). Developers are free to add flags, customize icons, rename or edit Electron executable files. -## Project initialization +[**MQTT**](https://www.emqx.com/en/blog/the-easiest-guide-to-getting-started-with-mqtt) (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for fast, efficient, and reliable communication between devices, particularly in IoT ecosystems. By integrating MQTT into Electron, developers can take advantage of its low overhead, high performance, and ease of use to manage communication between the desktop client and various connected devices or services in a seamless and responsive manner. -### New project +This article explains how to use MQTT in Electron projects, creating a simple MQTT desktop client that implements connection, subscription, unsubscription, messaging, and other functions between the client and the [MQTT broker](https://www.emqx.com/en/blog/the-ultimate-guide-to-mqtt-broker-comparison). + +## Project Initialization + +### New Project There are many ways to build a new project, but here is a brief list of a few: -- To create manually, do the following in the self-built project directory +#### Create Manually - ```shell - cd your-project +Do the following in the self-built project directory - npm init +```shell +cd your-project - npm i -D electron@lates - ``` +npm init - Also, refer to the following documentation for the steps to build the project. +npm i -D electron@lates +``` - Address: [https://www.electronjs.org/docs/tutorial/first-app](https://www.electronjs.org/docs/tutorial/first-app) +Alternatively, you can follow the official Electron documentation to build your project: [https://www.electronjs.org/docs/tutorial/first-app](https://www.electronjs.org/docs/tutorial/first-app) -- Rapid development with the official template projects `electron-qucik-start`. +#### Rapid Development with the Official Template Projects - Address: [https://github.com/electron/electron-quick-start](https://github.com/electron/electron-quick-start) +- `electron-qucik-start`: [https://github.com/electron/electron-quick-start](https://github.com/electron/electron-quick-start) ```shell # Clone this repository @@ -39,9 +43,7 @@ There are many ways to build a new project, but here is a brief list of a few: npm start ``` -- Rapid development builds with the template project `electron-react-bolierplate`, which can be developed using `React.js`. - - Address: https://github.com/electron-react-boilerplate/electron-react-boilerplate +- `electron-react-bolierplate`: [https://github.com/electron-react-boilerplate/electron-react-boilerplate](https://github.com/electron-react-boilerplate/electron-react-boilerplate) ```shell git clone --depth 1 --single-branch https://github.com/electron-react-boilerplate/electron-react-boilerplate.git your-project-name @@ -49,29 +51,27 @@ There are many ways to build a new project, but here is a brief list of a few: yarn ``` -- The rapid development build of the project via `electron-vue` will be coupled with project initialization using the `vue-cli` tool, which can be developed using `Vue.js`. - - Address: https://github.com/SimulatedGREG/electron-vue +- `electron-vue` : [https://github.com/SimulatedGREG/electron-vue](https://github.com/SimulatedGREG/electron-vue) ```shell # Install vue-cli and scaffold boilerplate npm install -g vue-cli vue init simulatedgreg/electron-vue my-project - + # Install dependencies and run your app cd my-project yarn # or npm install yarn run dev # or npm run dev ``` -In this article, the official electron quick start project template will be used to initialize the project in order to quickly build the example project. +For this article, we'll use the official Electron quick start project template to quickly initialize our example project. -### Installation dependencies +### Installing MQTT in Your Electron Project -Installation through the command line +To get started with MQTT integration in your Electron project, you need to install the [MQTT.js library](https://github.com/mqttjs/MQTT.js). This can be done easily via the command line using npm: ```shell -npm install mqtt --save +npm install mqtt --save ``` After the dependencies are installed, if you want to open the console for debugging, you need to modify the code in `main.js` and uncomment `win.webContents.openDevTools()`. @@ -79,6 +79,7 @@ After the dependencies are installed, if you want to open the console for debugg ```javascript // Open the DevTools. mainWindow.webContents.openDevTools() + ``` In this case, the locally installed `MQTT.js` module cannot be loaded directly into `renderer.js` without using the front-end builder to package the front-end page. In addition to using the build tool method, there are two other ways to solve this: @@ -98,94 +99,74 @@ In this case, the locally installed `MQTT.js` module cannot be loaded directly i 2. The [MQTT.js](https://www.emqx.com/en/blog/mqtt-js-tutorial) module can be imported in preload.js. When there is no node integration, this script still can access all Node APIs. However, when this script execution completes, global objects injected via Node will be removed. -3. The [MQTT.js](https://www.emqx.com/en/blog/mqtt-js-tutorial) module can be imported in main process and connected. In Electron, processes communicate by passing messages through developer-defined "channels" with the [`ipcMain`](https://www.electronjs.org/docs/latest/api/ipc-main) and [`ipcRenderer`](https://www.electronjs.org/docs/latest/api/ipc-renderer) modules. These channels are **arbitrary** (you can name them anything you want) and **bidirectional** (you can use the same channel name for both modules). For usage examples, check out the [IPC tutorial](https://www.electronjs.org/docs/latest/tutorial/ipc). +3. The [MQTT.js](https://www.emqx.com/en/blog/mqtt-js-tutorial) module can be imported in main process and connected. In Electron, processes communicate by passing messages through developer-defined "channels" with the `ipcMain` and `ipcRenderer` modules. These channels are **arbitrary** (you can name them anything you want) and **bidirectional** (you can use the same channel name for both modules). For usage examples, check out the [IPC tutorial](https://www.electronjs.org/docs/latest/tutorial/ipc). For example, in the main process, ipcMain listens for connection operations. When the user clicks the connection, the corresponding configuration information collected in the render process is transferred to the main process through ipcRenderer to connect: - Receive the connection data sent by the rendering process in the main process and make MQTT connection: - ```js - // main.js - ipcMain.on('onConnect', (event, connectUrl, connectOpt) => { - client = mqtt.connect(connectUrl, connectOpt) - client.on('connect', () => { - console.log('Client connected:' + options.clientId) - }) - client.on('message', (topic, message) => { - console.log(`${message.toString()}\nOn topic: ${topic}`) + ```javascript + // main.js + ipcMain.on('onConnect', (event, connectUrl, connectOpt) => { + client = mqtt.connect(connectUrl, connectOpt) + client.on('connect', () => { + console.log('Client connected:' + options.clientId) + }) + client.on('message', (topic, message) => { + console.log(`${message.toString()}\nOn topic: ${topic}`) + }) }) - }) - ``` + ``` - Click to connect in the rendering process, get the connection data from the page and send it to the main process: - ```js - // render.js - function onConnect() { - const { host, port, clientId, username, password } = connection - const connectUrl = `mqtt://${host.value}:${port.value}` - const options = { - keepalive: 30, - protocolId: 'MQTT', - clean: true, - reconnectPeriod: 1000, - connectTimeout: 30 * 1000, - rejectUnauthorized: false, - clientId, - username, - password, + ```javascript + // render.js + function onConnect() { + const { host, port, clientId, username, password } = connection + const connectUrl = `mqtt://${host.value}:${port.value}` + const options = { + keepalive: 30, + protocolId: 'MQTT', + clean: true, + reconnectPeriod: 1000, + connectTimeout: 30 * 1000, + rejectUnauthorized: false, + clientId, + username, + password, + } + console.log('connecting mqtt client') + window.electronAPI.onConnect(connectUrl, options) } - console.log('connecting mqtt client') - window.electronAPI.onConnect(connectUrl, options) - } - ``` + ``` - In preload.js, the API method for interprocess IPC communication is implemented, and the channel is established: - ```js - // preload.js - contextBridge.exposeInMainWorld('electronAPI', { - onConnect: (data) => ipcRenderer.send('onConnect', data), - }) - ``` + ```javascript + // preload.js + contextBridge.exposeInMainWorld('electronAPI', { + onConnect: (data) => ipcRenderer.send('onConnect', data), + }) + ``` -## The use of MQTT +## Using MQTT in the Electron Project ### Connect to the MQTT broker -This article will use the [free public MQTT broker](https://www.emqx.com/en/mqtt/public-mqtt5-broker) provided by EMQX. This service was created based on the EMQX [MQTT IoT cloud platform](https://www.emqx.com/en/cloud). The information about broker access is as follows: +This article will use the [free public MQTT broker](https://www.emqx.com/en/mqtt/public-mqtt5-broker) provided by EMQX. This service was created based on the EMQX [MQTT platform](https://www.emqx.com/en/cloud). The information about broker access is as follows: - Broker: **broker.emqx.io** - TCP Port: **1883** - Websocket Port: **8083** -
-
- Open Manufacturing Hub -
-
-
- A Practical Guide to MQTT Broker Selection -
-
- Download this practical guide and learn what to consider when choosing an MQTT broker. -
- Get the eBook → -
-
- To illustrate more intuitive, the key connection code for the example will be written in the renderer.js file. With the consideration of security, the installed MQTT module will be loaded via the require method of the Node.js API, in the preload.js file (using method 2 above). Also, this method injecting it in the global window object. -> **Note:** [Context isolation (contextIsolation)](https://www.electronjs.org/docs/latest/tutorial/context-isolation) has been enabled by default since Electron 12, Although preload scripts share a `window` global with the renderer they're attached to, you cannot directly attach any variables from the preload script to `window` because of the [`contextIsolation`](https://www.electronjs.org/docs/latest/tutorial/context-isolation) default. +> **Note:** [Context isolation (contextIsolation)](https://www.electronjs.org/docs/latest/tutorial/context-isolation) has been enabled by default since Electron 12, Although preload scripts share a `window` global with the renderer they're attached to, you cannot directly attach any variables from the preload script to `window` *because of the* `contextIsolation` default. Therefore, we need to set `contextIsolation: false` in webPreferences to close: -```js +```javascript const mainWindow = new BrowserWindow({ width: 800, height: 600, @@ -200,69 +181,69 @@ So that the loaded module can be accessed directly in `renderer.js`: - Import MQTT module -```javascript -// preload.js -const mqtt = require('mqtt') -window.mqtt = mqtt -``` + ```javascript + // preload.js + const mqtt = require('mqtt') + window.mqtt = mqtt + ``` - Configure and test MQTT module -```javascript -// renderer.js -const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8) - -const host = 'mqtt://broker.emqx.io:1883' - -const options = { - keepalive: 30, - clientId: clientId, - protocolId: 'MQTT', - protocolVersion: 4, - clean: true, - reconnectPeriod: 1000, - connectTimeout: 30 * 1000, - will: { - topic: 'WillMsg', - payload: 'Connection Closed abnormally..!', - qos: 0, - retain: false, - }, - rejectUnauthorized: false, -} - -// Information about the mqtt module is available -console.log(mqtt) - -console.log('connecting mqtt client') -const client = mqtt.connect(host, options) - -client.on('error', (err) => { - console.log('Connection error: ', err) - client.end() -}) - -client.on('reconnect', () => { - console.log('Reconnecting...') -}) - -client.on('connect', () => { - console.log('Client connected:' + clientId) - client.subscribe('testtopic/electron', { - qos: 0, + ```javascript + // renderer.js + const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8) + + const host = 'mqtt://broker.emqx.io:1883' + + const options = { + keepalive: 30, + clientId: clientId, + protocolId: 'MQTT', + protocolVersion: 4, + clean: true, + reconnectPeriod: 1000, + connectTimeout: 30 * 1000, + will: { + topic: 'WillMsg', + payload: 'Connection Closed abnormally..!', + qos: 0, + retain: false, + }, + rejectUnauthorized: false, + } + + // Information about the mqtt module is available + console.log(mqtt) + + console.log('connecting mqtt client') + const client = mqtt.connect(host, options) + + client.on('error', (err) => { + console.log('Connection error: ', err) + client.end() }) - client.publish('testtopic/electron', 'Electron connection demo...!', { - qos: 0, - retain: false, + + client.on('reconnect', () => { + console.log('Reconnecting...') }) -}) - -client.on('message', (topic, message, packet) => { - console.log( - 'Received Message: ' + message.toString() + '\nOn topic: ' + topic - ) -}) -``` + + client.on('connect', () => { + console.log('Client connected:' + clientId) + client.subscribe('testtopic/electron', { + qos: 0, + }) + client.publish('testtopic/electron', 'Electron connection demo...!', { + qos: 0, + retain: false, + }) + }) + + client.on('message', (topic, message, packet) => { + console.log( + 'Received Message: ' + message.toString() + '\nOn topic: ' + topic + ) + }) + ``` We can see the following output on the console after writing the above code and running the project: @@ -274,9 +255,9 @@ The MQTT module works fine. After setting up the module, we can write a simple U ![electronui.png](https://assets.emqx.com/images/f628816b73b31e6d3c695cd39c439ca6.png) -The complete code is available here: [https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Electron](https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Electron). +The complete code is available here: [MQTT-Client-Examples/mqtt-client-Electron at master · emqx/MQTT-Client-Examples](https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Electron). -### Key code +### Key Code Snippets for MQTT Integration #### Connect @@ -399,9 +380,9 @@ function onDisconnect() { } ``` -### Client test +### Testing the MQTT Connection in Electron -At this point, we test the sending and receiving of messages with a [MQTT 5.0 client tool - MQTTX](https://mqttx.app), also written in Electron. +Once you have set up the MQTT client, you can test your connection using [MQTTX](https://mqttx.app/), a popular all-in-one MQTT 5.0 client. In this test, you’ll send and receive messages between your Electron app and MQTT broker. When using MQTTX to send a message to the client, you can see that the message is received properly: @@ -413,23 +394,23 @@ Send a message to MQTTX using the client you wrote yourself, and now you can see ## Summary -So far, we have completed that use Electron to create a simple MQTT desktop client, and simulate the connection, messaging, unsubscribe and disconnect scenarios between the client and MQTT broker. It is also worth noting that since the Electron project includes both a browser environment and a Node.js environment, it is possible to use the browser's WebSocket API to implement an MQTT over WebSocket connection by modifying the connection protocol and port number in the above code. +In this tutorial, we demonstrated how to create an MQTT desktop client using Electron, enabling seamless communication with MQTT brokers for IoT applications. By following these steps, you can integrate MQTT into your own Electron-based desktop apps, enabling real-time messaging and device communication. + +It is also worth noting that since the Electron project includes both a browser environment and a Node.js environment, it is possible to use the browser's WebSocket API to implement an MQTT over WebSocket connection by modifying the connection protocol and port number in the above code. ## Resources -- [How to Use MQTT in Vue](https://www.emqx.com/en/blog/how-to-use-mqtt-in-vue) -- [How to Use MQTT in React](https://www.emqx.com/en/blog/how-to-use-mqtt-in-react) -- [How to Use MQTT in Angular](https://www.emqx.com/en/blog/how-to-use-mqtt-in-angular) +- [How to Use MQTT in Vue Projects](https://www.emqx.com/en/blog/how-to-use-mqtt-in-vue) +- [How to Use MQTT in React Projects](https://www.emqx.com/en/blog/how-to-use-mqtt-in-react) +- [How to Use MQTT in Angular Projects](https://www.emqx.com/en/blog/how-to-use-mqtt-in-angular) - [How to Use MQTT in Node.js](https://www.emqx.com/en/blog/how-to-use-mqtt-in-nodejs) - [A Quickstart Guide to Using MQTT over WebSocket](https://www.emqx.com/en/blog/connect-to-mqtt-broker-with-websocket) -[^1]: https://en.wikipedia.org/wiki/Electron_(software_framework)
- Try EMQX Cloud for Free -
A fully managed, cloud-native MQTT service
+ Talk to an Expert
- Get Started → + Contact Us →
diff --git a/en/202411/how-to-use-mqtt-in-vue.md b/en/202411/how-to-use-mqtt-in-vue.md new file mode 100644 index 00000000..91fdec52 --- /dev/null +++ b/en/202411/how-to-use-mqtt-in-vue.md @@ -0,0 +1,212 @@ +[Vue](https://vuejs.org/), one of the most popular frameworks for building user interfaces, is highly flexible and ideal for incremental adoption. With its focus on the view layer, Vue is easy to integrate into existing projects or use with complementary libraries. When paired with modern tooling, Vue excels at creating advanced Single-Page Applications (SPAs). + +[MQTT](https://www.emqx.com/en/blog/the-easiest-guide-to-getting-started-with-mqtt) (Message Queuing Telemetry Transport) is a lightweight messaging protocol tailored for IoT applications. Using the publish/subscribe model, MQTT efficiently enables one-to-many communication and decouples application logic. Its key advantages include low transmission overhead, minimal network traffic, and support for three Quality of Service (QoS) levels to cater to diverse message delivery needs. + +In this tutorial, we’ll demonstrate how to integrate MQTT into your Vue project to quickly build MQTT Web application and enable seamless real-time IoT communication, covering essential operations like establishing a connection, subscribing to topics, publishing messages, and managing disconnections. + +> To create an MQTT connection in Vue 3 application using MQTT.js, please refer to [MQTT-Client-Examples/mqtt-client-Vue3.js at master · emqx/MQTT-Client-Examples](https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Vue3.js) + +## Setting Up Your Vue Project with MQTT + +### Initialize Your Vue Project + +To create a Vue application, you can refer to the [Creating a Vue Application](https://vuejs.org/guide/quick-start.html#creating-a-vue-application) section in the Vue documentation. + +Examples: + +```shell +npm create vue@latest +``` + +### Install the MQTT Client Library + +To use MQTT in your Vue project, you'll need to install the [MQTT.js library](https://github.com/mqttjs/MQTT.js). There are several ways to do this: + +1. Installed from the command line, either using npm or yarn (one or the other) + + ```shell + npm install mqtt --save + # or yarn + yarn add mqtt + # or pnpm + pnpm add mqtt + ``` + +2. Import via CDN + + ```html + + ``` + +3. Download locally, then import using relative paths + + ```html + + ``` + +> *The method 2 and 3 are more suitable for the project that directly introduces Vue.js.* + +## Implementing MQTT in Your Vue Project + +### Connect to an MQTT Broker + +This article will use the [free public MQTT broker](https://www.emqx.com/en/mqtt/public-mqtt5-broker) provided by EMQX. This service was created based on the EMQX [MQTT platform](https://www.emqx.com/en/cloud). The information about broker access is as follows: + +- Broker: **broker.emqx.io** +- TCP Port: **1883** +- WebSocket Port: **8083** +- WebSocket Secure Port: **8084** + +Here's the code to establish a connection: + +#### Connect over WebSocket Port + +You can set a client ID, username, and password with the following code. The client ID should be unique. + +```javascript +const connection = reactive({ + clientId: "emqx_vue3_" + Math.random().toString(16).substring(2, 8), + username: "emqx_test", + password: "emqx_test", + // ...other connection options +}); +const { ...options } = connection +``` + +You can establish a connection between the client and the MQTT broker using the following code: + +```javascript +const client = mqtt.connect("ws://broker.emqx.io:8083/mqtt", options); +``` + +#### Connect over WebSocket Secure Port + +If TLS/SSL encryption is enabled, the connection [parameter options](https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options) are the same as for establishing a connection via the WebSocket port, you just need to be careful to change the protocol to `wss` and match the correct port number. + +You can establish a connection between the client and the MQTT broker using the following code: + +```javascript +const client = mqtt.connect("wss://broker.emqx.io:8084/mqtt", options); +``` + +### Subscribe to Topics + +Specify a topic and the corresponding [QoS level](https://www.emqx.com/en/blog/introduction-to-mqtt-qos) to be subscribed. + +```javascript +// Topic & QoS +const subscription = ref({ + topic: "topic/mqttx", + qos: 0 as mqtt.QoS, +}); + +const doSubscribe = () => { + const { topic, qos } = subscription.value; + client.subscribe( + topic, + { qos }, + (error: Error, granted: mqtt.ISubscriptionGrant[]) => { + if (error) { + console.log("subscribe error:", error); + return; + } + console.log("subscribe successfully:", granted); + } + ); +}; +``` + +### Unsubscribe + +You can unsubscribe using the following code, specifying the topic and corresponding QoS level to be unsubscribed. + +```javascript +const doUnSubscribe = () => { + const { topic, qos } = subscription.value; + client.unsubscribe(topic, { qos }, (error) => { + if (error) { + console.log("unsubscribe error:", error); + return; + } + console.log(`unsubscribed topic: ${topic}`); + }); +}; +``` + +### Publish Messages + +When publishing a message, the MQTT broker must be provided with information about the target topic and message content. + +```javascript +const publish = ref({ + topic: "topic/browser", + payload: '{ "msg": "Hello, I am browser." }', + qos: 0 as mqtt.QoS, +}); + +const doPublish = () => { + const { topic, qos, payload } = publish.value; + client.publish(topic, payload, { qos }, (error) => { + if (error) { + console.log("publish error:", error); + return; + } + console.log(`published message: ${payload}`); + }); +}; +``` + +### Disconnect from the Broker + +To disconnect the client from the broker, use the following code: + +```javascript +const destroyConnection = () => { + if (client.connected) { + try { + client.end(false, () => { + console.log("disconnected successfully"); + }); + } catch (error) { + console.log("disconnect error:", error); + } + } +}; +``` + +## Testing the MQTT Connection in Vue + +We use Vue to write the following simple browser application. This application has: create connections, subscribe topics, messaging, unsubscribe, disconnect and other functions. + +The complete code for this project: [MQTT-Client-Examples/mqtt-client-Vue.js at master · emqx/MQTT-Client-Examples](https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Vue.js). + +![vueui.png](https://assets.emqx.com/images/b6563b0eb66eb51a2a02776889016a18.png) + +Use [MQTT 5.0 client tool - MQTTX](https://mqttx.app/) as another client to test messaging. + +![vuemqttx.png](https://assets.emqx.com/images/2013cbab1bdffcae69b817bfebb4a33f.png) + +If you unsubscribe on the browser side, the browser will not receive the subsequent messages from MQTTX before MQTTX sends the second message. + +## Summary + +In this guide, we demonstrated how to integrate MQTT with Vue to create a real-time IoT Web Web application. From establishing a connection to managing subscriptions and messages, the combination of Vue and MQTT opens up endless possibilities for developing robust IoT solutions. + +Want to dive deeper into MQTT? Check out EMQ's [Easy-to-understand Guide to MQTT Protocol](https://www.emqx.com/en/mqtt-guide) for more insights and advanced use cases. + +## Resources + +- [How to Use MQTT in React Projects](https://www.emqx.com/en/blog/how-to-use-mqtt-in-react) +- [How to Use MQTT in Angular Projects](https://www.emqx.com/en/blog/how-to-use-mqtt-in-angular) +- [How to Use MQTT in Node.js](https://www.emqx.com/en/blog/how-to-use-mqtt-in-nodejs) +- [How to Integrate MQTT in Your Electron Project](https://www.emqx.com/en/blog/how-to-use-mqtt-in-electron) +- [A Quickstart Guide to Using MQTT over WebSocket](https://www.emqx.com/en/blog/connect-to-mqtt-broker-with-websocket) + + + +
+
+ Talk to an Expert +
+ Contact Us → +