In the first half of the year, the customer requested to realize bluetooth printing. One searches on the net, article is not much, miscellaneous and incomplete. So the initiation of writing a small program bluetooth printing article, can not say very detailed, can only say better than nothing.
If you don’t have the stomach for a long article, just drag it down and take the demo.
Bluetooth print
Small program or mobile terminal printing is generally two ways, one is cloud printing, the other is Bluetooth printing. In cloud printing, the data to be printed is sent to the remote server connected to the printer. The server sends the printed data to the printer through USB or other means to complete the printing. Ordinary printers can do it this way. Another is Bluetooth printing, more specifically, a special communication protocol that allows the mobile terminal to connect directly to the printer wirelessly, and the program transmits data to the printer to complete printing. Bluetooth printing falls into this category.
Bluetooth profile
Bluetooth I believe you are familiar with. As a wireless short distance communication technology, it has been widely used and has become the main technology to access the Internet of Things (IOT). There are actually different versions of the core of Bluetooth technology. The most common technologies are Bluetooth BR/EDR (basic rate/enhanced data rate) and Bluetooth Low Energy (Bluetooth Low Energy). Bluetooth BR/EDR is mainly used in Bluetooth version 2.0/2.1 and is commonly used in speakers and headsets. The low-power Bluetooth technology is mainly used in Bluetooth 4.0/4.1/4.2, which is mainly used in the latest products on the market, such as bracelets, smart home devices, automotive electronics, medical devices, Beacon sensors (small transmitters that send data through Bluetooth technology), etc. What we use for Bluetooth printing is bluetooth low power.
- Bluetooth technology advantages:
- Everywhere, widely used;
- Low application cost;
- Low latency;
- Strong anti-interference ability
- Disadvantages of Bluetooth:
- Power consumption. Although the transmission process consumes little energy, polling access in the waiting process consumes much energy in order to timely respond to the connection request. This will be mentioned later;
- The connection process is tedious. As a user, it may not feel like it, but as a developer, you know how tedious the whole process can be, from searching for bluetooth devices, to pairing connections, and finally to transmission. This will come back to later;
- Security issues.
Low power Bluetooth connection process
For example
Let’s use an analogy here. Every Bluetooth Device is a company. One Bluetooth device has many services under it, just like a company has many departments under it. These services have many Characteristic characteristics, each with different properties. It is just like that there are different employees in each department with different abilities and responsibilities. The process of connecting the mobile terminal to the Bluetooth printer and printing is just like going to a specific company (Device), a specific department (Service), and Characteristic employees. This employee has the Property to provide printing. See the following figure for details:
Wechat applet method
The specific call method to wechat is as follows:
Graph TD 1([Disconnect Low Power Bluetooth connection]) --> Initialize Bluetooth module --> Search Bluetooth --> Select Bluetooth device --> 2([Stop Search Bluetooth]) --> Connect Low power Bluetooth device --> Transfer data --> Disconnect Bluetooth connection --> Close Bluetooth module
1. Wx. closeBLEConnection If the mobile phone has been connected to a Bluetooth device before, it needs to be disconnected first.
2. Wx. OpenBluetoothAdapter (initialize bluetooth module)
3. Wx. StartBluetoothDevicesDiscovery bluetooth (search) from the official documentation reminder: this operation is consumed system resources, please timely call after the search to the needs of equipment wx. StopBluetoothDevicesDiscovery stop searching.
4. Wx.getbluetoothdevices (Get searched Bluetooth devices: Devices) Obtains all searched Bluetooth devices during the bluetooth module validity period. This includes devices that are already connected to the local machine. Returns a list of devices.
5. Select the device to be connected (deviceId) to obtain the deviceId of the device to be connected.
6. Wx. StopBluetoothDevicesDiscovery (stop search the bluetooth) close search, release of system resources.
7. Wx. createBLEConnection(Connect to bluetooth low-power device) Connect to Bluetooth low-power device. Use the deviceId from Step 5 to set up a low-power Bluetooth connection.
8. Wx. getBLEDeviceServices(Obtaining All Services of the Bluetooth device: (deviceId) => Services) After establishing a Bluetooth connection, obtain all services of the Bluetooth device based on deviceId. Find the service whose isPrimary is true and obtain the serviceId of the service.
9. Wx. GetBLEDeviceCharacteristics (for a bluetooth device in a service: (deviceId all eigenvalues, ServiceId => characteristicId) Obtain the characteristics of a serviceId that contains a Bluetooth low power device. Repeat characteristics to find the properties. Write true value for the characteristicId. Data can be written only because the device supports write.
10. Wx. WriteBLECharacteristicValue (print), now we have got the bluetooth device deviceId, serviceId, characteristicId, then as long as we want to print the contents of the binary data into a bluetooth device can identify, Write to the characteristic value of the low power Bluetooth device. As bluetooth is used for low power consumption, the written data needs to be subcontracted and sent. See Demo for detailed implementation. Content conversion varies according to the instruction set supported by the printing device. The instruction set generally includes printer setup and operation, print content configuration, etc. General printing equipment factory has special instruction set document support, similar to the browser, different manufacturers for the implementation of the standard varies, need to carefully read the document.
11. Disable bluetooth connection wx.closeBLEConnection when leaving the page
12. Close the Wx. CloseBluetoothAdapter
Wechat official also has a more detailed description of this communication process.
It is the process of writing data to a printer that has already been connected.
Instruction set
The print instruction has to be mentioned here. Print command, also known as print control command. The printer receives the printing instruction to complete the corresponding printing operation. No matter the printer Settings, operation or print content Settings, formatting and typesetting, are controlled through this series of printing instructions. The set of instructions recognized by the printer becomes the instruction set. Different printer vendors implement different sets of instructions, just as different browsers have different kernels. At present, the mainstream instruction sets are as follows:
- Epson company
ESC command
Set (ordinary printer) - The HP company
PCL
Command set - Adobe’s PostScript(PS) command set
Others include the CPCL command set (mobile printer) and the TSPL command set (label printer).
The ESC command set is the de facto industry standard for needle printers and ticket printing. The ESC/POS printing command set is a simplified version of the ESC printing control command, and now most of the bills are printed using ESC/POS command set. This demo is based on the ESC/POS instruction set to some commonly used printing functions are encapsulated. A detailed set of ESC/POS instructions can be found here.
Code implementation
In the demo I implemented a constructor for PrinterJobs (referring to another demo and extending it). The instance created by this constructor is used to generate typed array data from the print instructions, which is then converted into an ArrayBuffer and sent to the printer.
For example: Print the text “I’m printing” in center, medium font, and underline.
The code is as follows:
let printerJobs = new PrinterJobs();
printerJobs
.setAlign("ct") / / in the middle
.setFontSize(2.2) // Set the size
.setUnderline(true) // Set the underscore
.println("I'm printing.") // Set the content and print it
let buffer = printerJobs.buffer(); // The ArrayBuffer to write to the printer
doPrint(buffer) // Write data
Copy the code
Let’s print out the type array data, As follows [27, 64, 29, 80, 203, 203, 27, 97, 1, 29, 33, 17, 27, 45, 1, 191, 170, 202, 188, 180, 242, 211, 161, 193, 203, 10]
Let’s take apart this type array from the code.
code | Array of corresponding types | |
---|---|---|
Initialization part | let printerJobs = new PrinterJobs() |
[27, 64, 29, 80, 203, 203] |
In the middle | printerJobs.setAlign("ct") |
[27, 97, 1) |
Set the font size | printerJobs.setFontSize(2, 2) |
[17] 29, 33, |
Set underscores | printerJobs.setUnderline(true) |
[27, 45, 1] |
Print the content | Printerjobs. println(" start printing ") |
Text part:[191, 170, 202, 188, 180, 242, 211, 161, 193, 203] Print instructions: [10] |
How to determine the number in the array, this is to look at the instruction set. Most printers come with instruction set documentation. For example, the middle instruction looks like this:
Image taken from:Reference.epson-biz.com/modules/ref…
Here 27,97 are the starting constants for text alignment, n is the variable, and n = 1 means center. The end result is [27, 97, 1]. Text is encoded, especially for Chinese characters, as shown in text-encoding.
When writing data, note that for low-power Bluetooth devices, the data transfer size is limited. If the data transfer size exceeds the limit, the data transfer may fail. Therefore, it is necessary to delay the transmission of data in blocks. Here is wechat’s official explanation:
When transmitting data with bluetooth devices, you need to pay attention to the MTU (maximum transmission unit). If the amount of data exceeds the MTU, an error may occur. You are advised to fragment data according to the Bluetooth device protocol. An Android device can call wx.setBLEMTU for MTU negotiation. If the MTU is unknown, you are advised to use a 20-byte transmission unit.
Demo
See here: github.com/akizmh/blue…
reference
- The dominant instruction type of the printer
- Wechat applet Bluetooth official API
- Wechat small program bluetooth printing brief introduction
- GitHub Demo – miniprogram-bluetoothprinter
- GitHub Demo – node-escpos
- Epson printer ESC/POS command complete