Front-end development uses the Electron + node-serialpost to realize serialport communication. Recently, there is a demand to directly read loadometer data as far as possible. The current project is a web page project written by vue. Load the written page through iframe, and then communicate with iframe to transmit serial port data. However, it took nearly two weeks to step on all kinds of pits. When we happened to encounter the epidemic, we studied a wave of it. We hereby record the configuration process, mainly to integrate resources and record the whole process.
Install the electron Serialport electronic-rebuild
The installation of ELECTRON may require scientific Internet connection due to the influence of network environment. If scientific Internet connection is not possible, use CNPM.
mkdir my-electron-app && cd my-electron-app\
npm init
Copy the code
cnpm i electron --save-dev
cnpm i serialport
cnpm i electron-rebuild --save-dev
Copy the code
Install dependencies
Node-serialport is a native module that allows node to access a computer’s serialport devices. It requires compilation and is one of the most problematic. Compilation requires some preparation.
- Install Node-gyp, VS2017, and Python
npm install -g node-gyp
npm install --global --production windows-build-tools
npm config setPython python2.7 NPM configset msvs_version 2017
Copy the code
- compile
.\node_modules\.bin\electron-rebuild.cmd
Copy the code
Possible problems
- When I was installing Windows-build-Tools, I was stuck. At this moment, a god found a solution. I followed this step and successfully solved the problem.
- NODE_MOUDLE_VERSION is inconsistent. This error may be thrown while the software is running.
- Other problems, only Baidu, really not Google, many attempts, I spent more than a week to do well…
Success a don’t in the blind toss, let go of the next also let go of their own, I made a new time, the results and encountered all kinds of problems…
Test the serialport
If no hardware device is available, download the virtual serial port tool (VSPD virtual serial port) and serial port debugging tool.
Package. json sets the entry file to main.js
// package.json."main": "main.js".Copy the code
Add main.js and HTML files
Add the test code to main.js, and if the console outputs port information, it is 95.8% successful.
const serialport = require("serialport");
serialport.list().then((ports) = > {
console.log(ports);
});
Copy the code
Use serialPort in HTML
After the success of the previous step, we tried to use serialport in THE HTML page, and found that the console reported an error. After searching various sources, we found that since Electron 9.0, the official recommendation does not use the native NodeJS module in the rendering process, so what should we do?
Given that we can work with the main.js main thread, we can investigate the communication between the main thread and the render thread. Electron provides the ipcMain and ipcRenderer apis, which are described in detail on the online article page. Find an example to share with you: Electron Note Interprocess Communication (IPC)
- HTML Page Set serial port parameters, including the serial port name, baud rate, parity bit, and stop bit. After setting the parameters, send them to the main thread.
- The main thread receives parameters, opens the serial port, and receives data (using serial debugging tools to send data).
- NPM start start the project, find the data, success!
const { ipcMain } = require("electron");
ipcMain.on("open-serialport".(event, args) = > {
const port = new serialport(path, options, errorCallback);
port.on('data'.data= > {
// Return the data received by the serial port to the renderer for display
event.sender.send("send-data".`${data}`);
});
});
Copy the code
Vscode debugs the electron main thread
How can programmers not debug! Refer to this article for debugging.
packaging
Once all of the above has passed, the requirements are satisfied by communicating with iframe. Next, I will study how to package the installation package, because it still involves the update and upgrade of the client. After installing the electron Builder, I will add the package command in package.json and execute the command NPM run build. Big god many very, please refer to the electron- Builder package mining problems summary configuration, a word: good! So once you’re done packing up your dist folder looks like this, and exe is our installer.
npm i electron-builder
Copy the code
// package.json
"build": {
"appId": "com.xxx.app"."productName": "marco-test-app"."publish": [{"provider": "generic"."url": "http://localhost:7777/download"."channel": "latest"}]."mac": {
"target": [
"dmg"."zip"]},"win": {
"target": [
"nsis"."zip"]},"nsis": {
"oneClick": false."allowToChangeInstallationDirectory": true."allowElevation": true."createDesktopShortcut": true."createStartMenuShortcut": true."shortcutName": "marco-app"}},"scripts": {
"start": "electron --inspect=8888 ."."build": "electron-builder --win --x64"
},
Copy the code
Automatically updates the electron-updater
If you give the user an installation package, you have to support the version update.
Json -> build -> publish configure the update address in package.json -> build -> publish. We use Node to configure and update the address locally. We can refer to the Electron application for automatic update to configure the local environment. The packed update file must be placed in the right position, and must have the latest. Json -> build -> publish add “channel”:”latest” to package.json -> build -> publish
Error: dev-app-update.yml file does not exist or update for version X.X.X is not available (latest version X.X.X: X.x, must be disallowed), test create this file locally, Copy the contents of app-update.yml in the packed folder win-unpacked resources. For more errors refer to the electron-updater update electron app.
npm i electron-updater
Copy the code
// main.js
app.whenReady().then(() = > {
createWindow();
checkForUpdates();
});
function checkForUpdates() {
// Update the address, that is, the new version store address
autoUpdater.setFeedURL("http://localhost:7777/download");
autoUpdater.checkForUpdates();
autoUpdater.on("update-available".function (info) {
dialog.showMessageBox({title: 'update'.message: 'Updates available'});
});
autoUpdater.on('update-not-available'.function (info) {
dialog.showMessageBox({title: 'No updates'.message: 'No updates available'});
})
autoUpdater.on("update-downloaded".(info) = > {
dialog.showMessageBox(
{
// icon: __static + "/favicon.png",
type: "info".title: "Software Update".message: 'has been updated to the latest version (${info.version}) Please restart the application. `.// detail: detail,
buttons: ["Sure"],},(idx) = > {
// Perform the update when you click OK
if (idx === 0) { autoUpdater.quitAndInstall(); }}); }); }Copy the code
"build": {
"appId": "com.xxx.app"."productName": "marco-test-app"."publish": [{"provider": "generic"."url": "http://localhost:7777/download"."channel": "latest"}]."mac": {
"target": [
"dmg"."zip"]},"win": {
"target": [
"nsis"."zip"]},"nsis": {
"oneClick": false."allowToChangeInstallationDirectory": true."allowElevation": true."createDesktopShortcut": true."createStartMenuShortcut": true."shortcutName": "marco-app"}}Copy the code
conclusion
A set of process down, want to cry, will encounter all sorts of problems, I have spent nearly two weeks time (less than two hours a day) to do well, it’s too difficult, to give up halfway to don’t have, but he wants to make, the more mistakes I fortunately finally succeeded, cannot guarantee according to the process must be success, only recording process.
Reference article:
The field Electron uses SerialPort to interact with the SerialPort in detail
Python 2.7 is Successfully installed when installing Windows build-tools
The electron report using serialport indicates that the NODE_MOUDLE_VERSION is inconsistent
Electron Note Interprocess Communication (IPC)
How does Electron debug the rendering process and debug using a browser and VSCode
The Electron application implements automatic updates
Electron -updater updates the electron application