当前位置:网站首页>Uniapp wechat applet realizes the function of connecting low-power Bluetooth printing
Uniapp wechat applet realizes the function of connecting low-power Bluetooth printing
2022-07-28 12:25:00 【Pontoon bridge】
Wechat applet project uses Bluetooth connection printing , I made a reference note by referring to the official documents , When using this method, follow the steps to check .
uni-app Bluetooth connectivity
bluetooth :
1、 Initialize Bluetooth
uni.openBluetoothAdapter(OBJECT)
uni.openBluetoothAdapter({
success(res) {
console.log(res)
// Interface calls the successful callback function
},
fail:(res)=>{
// Interface call failed callback function
},
complete:()=>{
// The callback function at the end of the interface call ( Successful call 、 Failure will be carried out )
}
})
error :res.errCode
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
Be careful
- Other Bluetooth related API Must be in
uni.openBluetoothAdapterUse after call . otherwise API Will return an error (errCode=10000). - When the user's Bluetooth switch is not turned on or the mobile phone does not support Bluetooth , call
uni.openBluetoothAdapterWill return an error (errCode=10001), Indicates that the Bluetooth function of the mobile phone is not available . here APP Bluetooth module has been initialized , It can be done byuni.onBluetoothAdapterStateChangeMonitor the change of Bluetooth status of mobile phone , You can also call all of the Bluetooth module API.
2、 Monitor Bluetooth adapter status change events
uni.onBluetoothAdapterStateChange(CALLBACK)
CALLBACK Returns the parameter
| attribute | type | explain |
|---|---|---|
| available | boolean | Whether the Bluetooth adapter is available |
| discovering | boolean | Whether the Bluetooth adapter is in search state |
Sample code
uni.onBluetoothAdapterStateChange((res) => {
console.log('onBluetoothAdapterStateChange', res)
// available: Whether the Bluetooth adapter is available
if (res.available) {
// Cancel monitoring , otherwise stopBluetoothDevicesDiscovery It will continue to trigger onBluetoothAdapterStateChange,
// Cause to call again startBluetoothDevicesDiscovery
uni.onBluetoothAdapterStateChange(() => {
});
// Start searching for Bluetooth peripherals nearby
uni.startBluetoothDevicesDiscovery(OBJECT)
}
})
3、 Start searching for Bluetooth peripherals nearby
uni.startBluetoothDevicesDiscovery(OBJECT)
This operation consumes system resources , Please call after searching and connecting to device uni.stopBluetoothDevicesDiscovery Method to stop searching .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| services | Array | no | To search but Bluetooth device owner service Of uuid list . Some Bluetooth devices broadcast their masters service Of uuid. If this parameter is set , Then only the broadcast packet with corresponding uuid The main service of Bluetooth device . It is recommended to filter out other Bluetooth devices that do not need to be processed around mainly through this parameter . | |
| allowDuplicatesKey | boolean | false | no | Whether it is allowed to report the same equipment repeatedly . If repeated reporting is allowed , be uni.onBlueToothDeviceFound Method will report the same device multiple times , however RSSI Values will vary . |
| interval | number | 0 | no | Report the interval of the equipment .0 It means that new equipment is found and reported immediately , Other values are reported according to the incoming interval . |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
Be careful :
- App The client currently only supports discovery ble Bluetooth devices , More Bluetooth device discovery , have access to Native.js, Reference resources :https://ask.dcloud.net.cn/article/114. It can also be obtained in the plug-in market Native plug-ins
Sample code
// Take the Bluetooth smart light of wechat hardware platform as an example , Main service UUID yes FEE7. Pass in this parameter , Search only the main service UUID by FEE7 The equipment
uni.startBluetoothDevicesDiscovery({
services: ['FEE7'],
success(res) {
console.log(res)
// Listen for events that find new devices
uni.onBluetoothDeviceFound(OBJECT)
}
})
4、 Listen for events that find new devices
uni.onBluetoothDeviceFound(CALLBACK)
CALLBACK Returns the parameter
| attribute | type | explain |
|---|---|---|
| devices | Array | List of newly searched devices |
devices Structure
| attribute | type | explain |
|---|---|---|
| name | string | Bluetooth device name , Some devices may not |
| deviceId | string | Used to distinguish between devices id |
| RSSI | number | Current signal strength of Bluetooth devices |
| advertisData | ArrayBuffer | In the broadcast data segment of the current Bluetooth device ManufacturerData Data segment . |
| advertisServiceUUIDs | Array | In the broadcast data segment of the current Bluetooth device ServiceUUIDs Data segment |
| localName | string | In the broadcast data segment of the current Bluetooth device LocalName Data segment |
| serviceData | Object | In the broadcast data segment of the current Bluetooth device ServiceData Data segment |
Be careful
- If in
uni.onBluetoothDeviceFoundCalled back a device , This device will be added touni.getBluetoothDevicesThe array obtained by the interface .
Sample code
// ArrayBuffer turn 16 Example progress string
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
uni.onBluetoothDeviceFound(function (devices) {
console.log('new device list has founded')
console.dir(devices)
console.log(ab2hex(devices[0].advertisData))
})
5、 Stop searching for nearby Bluetooth peripherals
uni.stopBluetoothDevicesDiscovery(OBJECT)
If you have found the required Bluetooth device and do not need to continue searching , It is recommended to call this interface to stop Bluetooth search .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
Sample code
uni.stopBluetoothDevicesDiscovery({
success(res) {
console.log(res)
}
})
6、 according to uuid Get the connected device
uni.getConnectedBluetoothDevices(OBJECT)
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| services | Array | yes | Bluetooth device owner service Of uuid list | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
success Return parameter description :
| attribute | type | explain |
|---|---|---|
| devices | Array | List of devices searched |
res.devices Structure
| attribute | type | explain |
|---|---|---|
| name | string | Bluetooth device name , Some devices may not |
| deviceId | string | Used to distinguish between devices id |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
Sample code
uni.getConnectedBluetoothDevices({
success(res) {
console.log(res)
}
})
7、 Get all Bluetooth devices discovered during the Bluetooth module takes effect
uni.getBluetoothDevices(OBJECT)
Including devices already connected to the machine .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
success Return parameter description :
| attribute | type | explain |
|---|---|---|
| devices | Array | uuid Corresponding list of connected devices |
res.devices Structure
| attribute | type | explain |
|---|---|---|
| name | string | Bluetooth device name , Some devices may not |
| deviceId | string | Used to distinguish between devices id |
| RSSI | number | Current signal strength of Bluetooth devices |
| advertisData | ArrayBuffer | In the broadcast data segment of the current Bluetooth device ManufacturerData Data segment . |
| advertisServiceUUIDs | Array | In the broadcast data segment of the current Bluetooth device ServiceUUIDs Data segment |
| localName | string | In the broadcast data segment of the current Bluetooth device LocalName Data segment |
| serviceData | Object | In the broadcast data segment of the current Bluetooth device ServiceData Data segment |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
Sample code
// ArrayBuffer turn 16 Example progress string
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
uni.getBluetoothDevices({
success(res) {
console.log(res)
if (res.devices[0]) {
console.log(ab2hex(res.devices[0].advertisData))
}
}
})
Be careful
- The device list obtained by this interface is All Bluetooth devices searched during the validity of Bluetooth module , If the Bluetooth module is not called in time after the use process
uni.closeBluetoothAdapterRelease resources , There will be Bluetooth devices found in the previous Bluetooth usage process when calling this interface , Maybe the device is no longer around the user , Unable to connect . - When the Bluetooth device is searched , The system returned name The fields are generally LocalName Device name in the field , If you establish a connection with a Bluetooth device , The system returned name The field will be changed to that obtained from the Bluetooth device
GattName. If you need to dynamically change the device name and display , It is recommended to uselocalNameField .
8、 Get the status of the native Bluetooth adapter
uni.getBluetoothAdapterState(OBJECT)
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
success Return parameter description :
| attribute | type | explain |
|---|---|---|
| discovering | boolean | Are you searching for devices |
| available | boolean | Whether the Bluetooth adapter is available |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
Sample code
uni.getBluetoothAdapterState({
success(res) {
console.log(res)
}
})
9、 Turn off the Bluetooth module
uni.closeBluetoothAdapter(OBJECT)
Calling this method will disconnect all established connections and release system resources . It is recommended to use Bluetooth process , And uni.openBluetoothAdapter Call in pairs .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
Sample code
uni.closeBluetoothAdapter({
success(res) {
console.log(res)
}
})
Low power Bluetooth :
1、 Set the Bluetooth maximum transmission unit
[uni.setBLEMTU(OBJECT)
Need to be in uni.createBLEConnection After the call succeeds, call ,mtu set range (22,512). Android 5.1 The above is effective .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Used to distinguish between devices id | |
| mtu | number | yes | Maximum transmission unit (22,512) Within the interval , Company bytes | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
2、 Write binary data to the characteristic value of low-power Bluetooth device
uni.writeBLECharacteristicValue(OBJECT)
Be careful : The eigenvalue of the device must support write To successfully call .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Bluetooth devices id | |
| serviceId | string | yes | The Bluetooth eigenvalue corresponds to the service uuid | |
| characteristicId | string | yes | Bluetooth eigenvalue uuid | |
| value | ArrayBuffer | yes | The binary value corresponding to the characteristic value of the Bluetooth device | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
- There is a possibility of write failure when parallel calls are repeated .
- APP There is no limit on the write packet size , However, the system and Bluetooth devices will restrict Bluetooth 4.0 The data size of a single transmission , A write error occurs when the maximum number of bytes is exceeded , It is recommended that no more than... Be written each time 20 byte .
- If the single write data is too long ,iOS There will be no callback on the system ( Including error callback ).
- On the Android platform , Calling
notifyBLECharacteristicValueChangeCall... Immediately after successwriteBLECharacteristicValueInterface , On some models 10008 System error
// Send a 0x00 Of 16 Hexadecimal data
const buffer = new ArrayBuffer(1)
const dataView = new DataView(buffer)
dataView.setUint8(0, 0)
uni.writeBLECharacteristicValue({
// there deviceId Need to be in getBluetoothDevices or onBluetoothDeviceFound Interface
deviceId,
// there serviceId Need to be in getBLEDeviceServices Interface
serviceId,
// there characteristicId Need to be in getBLEDeviceCharacteristics Interface
characteristicId,
// there value yes ArrayBuffer type
value: buffer,
success(res) {
console.log('writeBLECharacteristicValue success', res.errMsg)
}
})
3、 Read the binary data value of the characteristic value of Low Power Bluetooth device
uni.readBLECharacteristicValue(OBJECT)
Be careful : The eigenvalue of the device must support read To successfully call .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Bluetooth devices id | |
| serviceId | string | yes | The Bluetooth eigenvalue corresponds to the service uuid | |
| characteristicId | string | yes | Bluetooth eigenvalue uuid | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
- There is the possibility of reading failure when parallel calls are repeated .
- The information read by the interface needs to be in
onBLECharacteristicValueChangeMethod to get .
// Only the callback here can get
uni.onBLECharacteristicValueChange(function (characteristic) {
console.log('characteristic value comed:', characteristic)
})
uni.readBLECharacteristicValue({
// there deviceId Need to have passed createBLEConnection Establish a link with the corresponding device
deviceId,
// there serviceId Need to be in getBLEDeviceServices Interface
serviceId,
// there characteristicId Need to be in getBLEDeviceCharacteristics Interface
characteristicId,
success(res) {
console.log('readBLECharacteristicValue:', res.errCode)
}
})
4、 Listen for low-power Bluetooth connection status change events
uni.onBLEConnectionStateChange(CALLBACK)
Including developers actively connect or disconnect , Device lost , Abnormal disconnection of connection, etc
CALLBACK Returns the parameter
| attribute | type | explain |
|---|---|---|
| deviceId | string | Bluetooth devices ID |
| connected | boolean | Whether it is connected |
uni.onBLEConnectionStateChange(function (res) {
// This method can be used in the callback to handle exceptions such as accidental disconnection of the connection
console.log(`device ${
res.deviceId} state has changed, connected: ${
res.connected}`)
})
5、 Monitor the eigenvalue change events of low-power Bluetooth devices
uni.onBLECharacteristicValueChange(CALLBACK)
You must first enable notifyBLECharacteristicValueChange The interface can receive the push from the device notification.
CALLBACK Returns the parameter
| attribute | type | explain |
|---|---|---|
| deviceId | string | Bluetooth devices id |
| serviceId | string | The Bluetooth eigenvalue corresponds to the service uuid |
| characteristicId | string | Bluetooth eigenvalue uuid |
| value | ArrayBuffer | The latest value of the characteristic value |
// ArrayBuffer turn 16 Example progress string
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
uni.onBLECharacteristicValueChange(function (res) {
console.log(`characteristic ${
res.characteristicId} has changed, now is ${
res.value}`)
console.log(ab2hex(res.value))
})
6、 Subscription characteristics
uni.notifyBLECharacteristicValueChange(OBJECT)
Enable low power Bluetooth device when the eigenvalue changes notify function , Subscription characteristics . Be careful : The eigenvalue of the device must support notify perhaps indicate To successfully call . in addition , You must first enable notifyBLECharacteristicValueChange To listen to the device characteristicValueChange event
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Bluetooth devices id | |
| serviceId | string | yes | The Bluetooth eigenvalue corresponds to the service uuid | |
| characteristicId | string | yes | Bluetooth eigenvalue uuid | |
| state | boolean | yes | Is it enabled? notify | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
- After the subscription operation is successful, the device needs to actively update the characteristic value value, Will trigger
uni.onBLECharacteristicValueChangeCallback . - On the Android platform , Calling
notifyBLECharacteristicValueChangeCall... Immediately after successwriteBLECharacteristicValueInterface , On some models 10008 System error
uni.notifyBLECharacteristicValueChange({
state: true, // Enable notify function
// there deviceId Need to have passed createBLEConnection Establish a link with the corresponding device
deviceId,
// there serviceId Need to be in getBLEDeviceServices Interface
serviceId,
// there characteristicId Need to be in getBLEDeviceCharacteristics Interface
characteristicId,
success(res) {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
}
})
7、 Get all services from Bluetooth devices (service)
uni.getBLEDeviceServices(OBJECT)
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Bluetooth devices id | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
success Return parameter description :
| attribute | type | explain |
|---|---|---|
| services | Array | Equipment service list |
res.services Structure
| attribute | type | explain |
|---|---|---|
| uuid | string | Bluetooth device service uuid |
| isPrimary | boolean | Whether the service is the main service |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
uni.getBLEDeviceServices({
// there deviceId Need to have passed createBLEConnection Establish a link with the corresponding device
deviceId,
success(res) {
console.log('device services:', res.services)
}
})
8、 Get the signal strength of Bluetooth device
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Bluetooth devices id | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
9、 Get all the eigenvalues in a service of a Bluetooth device (characteristic).
uni.getBLEDeviceCharacteristics(OBJECT)
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Bluetooth devices id | |
| serviceId | string | yes | Bluetooth service uuid, Need to use getBLEDeviceServices obtain | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
success Return parameter description :
| attribute | type | explain |
|---|---|---|
| characteristics | Array | Equipment service list |
res.characteristics Structure
| attribute | type | explain |
|---|---|---|
| uuid | string | Characteristic values of Bluetooth devices uuid |
| properties | Object | The operation types supported by this characteristic value |
properties Structure
| attribute | type | explain |
|---|---|---|
| read | boolean | Whether the characteristic value supports read operation |
| write | boolean | Whether the characteristic value supports write operation |
| notify | boolean | Whether the characteristic value supports notify operation |
| indicate | boolean | Whether the characteristic value supports indicate operation |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
uni.getBLEDeviceCharacteristics({
// there deviceId Need to have passed createBLEConnection Establish a link with the corresponding device
deviceId,
// there serviceId Need to be in getBLEDeviceServices Interface
serviceId,
success(res) {
console.log('device getBLEDeviceCharacteristics:', res.characteristics)
}
})
10、 Connecting low power Bluetooth devices
uni.createBLEConnection(OBJECT)
if APP I have searched a Bluetooth device before , And successfully established the connection , You can directly enter the information obtained by previous search deviceId Try connecting the device directly , No search operation is required .
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Used to distinguish between devices id | |
| timeout | number | no | Timeout time , Company ms, If you don't fill in it, you won't timeout | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
- Please make sure to call in pairs as much as possible
createBLEConnectionandcloseBLEConnectionInterface . If Android calls many timescreateBLEConnectionCreate connection , It may cause the system to hold multiple connected instances of the same device , Results in a call tocloseBLEConnectionYou can't really disconnect from the device . - Bluetooth connection may be disconnected at any time , It is recommended to monitor
uni.onBLEConnectionStateChangeCallback events , When the Bluetooth device is disconnected, perform reconnection on demand - If the interface of data read / write operation is called for an unconnected device or a disconnected device , Returns the 10006 error , Reconnection is recommended .
uni.createBLEConnection({
// there deviceId Need to have passed createBLEConnection Establish a link with the corresponding device
deviceId,
success(res) {
console.log(res)
}
})
11、 Disconnect from the low-power Bluetooth device .
uni.closeBLEConnection(OBJECT)
OBJECT Parameter description
| attribute | type | The default value is | Required | explain |
|---|---|---|---|---|
| deviceId | string | yes | Used to distinguish between devices id | |
| success | function | no | Interface calls the successful callback function | |
| fail | function | no | Interface call failed callback function | |
| complete | function | no | The callback function at the end of the interface call ( Successful call 、 Failure will be carried out ) |
| Error code | error message | explain |
|---|---|---|
| 0 | ok | normal |
| 10000 | not init | Bluetooth adapter not initialized |
| 10001 | not available | The Bluetooth adapter is currently unavailable |
| 10002 | no device | The specified device was not found |
| 10003 | connection fail | The connection fails |
| 10004 | no service | The specified service was not found |
| 10005 | no characteristic | The specified characteristic value... Was not found |
| 10006 | no connection | The current connection has been disconnected |
| 10007 | property not support | The current eigenvalue does not support this operation |
| 10008 | system error | All other exceptions reported by the system |
| 10009 | system not support | Android System specific , The system version is lower than 4.3 I won't support it BLE |
uni.closeBLEConnection({
deviceId,
success(res) {
console.log(res)
}
})
Implementation code :
<script>
const LAST_CONNECTED_DEVICE = 'last_connected_device';
import PrinterJobs from '../../common/printer/printerjobs';
import printerUtil from '../../common/printer/printerutil';
function inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i;
}
}
return -1;
}
// ArrayBuffer turn 16 Example progress string
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
return ('00' + bit.toString(16)).slice(-2);
});
return hexArr.join(',');
}
function str2ab(str) {
// Convert str to ArrayBuff and write to printer
let buffer = new ArrayBuffer(str.length);
let dataView = new DataView(buffer);
for (let i = 0; i < str.length; i++) {
dataView.setUint8(i, str.charAt(i).charCodeAt(0));
}
return buffer;
}
export default {
data() {
return {
devices:[] // Devices searched
}
};
},
onLoad(e) {
this.openBluetoothAdapter() // Initialize Bluetooth module
},
methods: {
// Initialize Bluetooth module
openBluetoothAdapter() {
console.log(' Initialize Bluetooth module openBluetoothAdapter');
if (!uni.openBluetoothAdapter) {
console.log(' Wechat version is too low ');
uni.showModal({
title: this.$t('wechat.w102'), //' Tips ',
content: this.$t('wechat.w226') //' Current wechat version is too low , This feature is not available , Please upgrade to the latest wechat version and try again .'
});
return;
}
uni.openBluetoothAdapter({
success: res => {
console.log(' Successful initialization openBluetoothAdapter success', res);
// Search for Bluetooth nearby
this.startBluetoothDevicesDiscovery();
},
fail: res => {
console.log(' initialization failed openBluetoothAdapter fail', res);
if (res.errCode === 10001) {
uni.showModal({
title: this.$t('wechat.w227'), // error
content: this.$t('wechat.w228'), //' Bluetooth device not found , Please turn on Bluetooth and try again .',
showCancel: false
});
// Monitor Bluetooth adapter status change events
uni.onBluetoothAdapterStateChange(res => {
console.log(' Monitor Bluetooth adapter status onBluetoothAdapterStateChange', res);
// available: Whether the Bluetooth adapter is available
if (res.available) {
// Cancel monitoring , otherwise stopBluetoothDevicesDiscovery It will continue to trigger onBluetoothAdapterStateChange,
// Cause to call again startBluetoothDevicesDiscovery
// uni.onBluetoothAdapterStateChange(() => {});
// Start searching for Bluetooth peripherals nearby
this.startBluetoothDevicesDiscovery();
}
});
}
}
});
},
// Start searching for Bluetooth peripherals nearby
startBluetoothDevicesDiscovery() {
if (this._discoveryStarted) {
return;
}
this._discoveryStarted = true;
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
interval: 0,
success: res => {
console.log(' Search for nearby Bluetooth peripherals startBluetoothDevicesDiscovery success111', res);
// Listen for events that find new devices
this.onBluetoothDeviceFound();
},
fail: res => {
console.log(' Search for nearby Bluetooth peripherals startBluetoothDevicesDiscovery fail', res);
}
});
},
// Listen for events that find new devices
onBluetoothDeviceFound() {
console.log(' Enter the inquiry device ');
uni.onBluetoothDeviceFound(res => {
console.log(' Looking for equipment ', res.devices);
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return;
}
const foundDevices = this.devices;
const idx = inArray(foundDevices, 'deviceId', device.deviceId);
const data = {
};
if (idx === -1) {
this.$set(this.devices, `${
foundDevices.length}`, device);
} else {
this.$set(this.devices, `${
idx}`, device);
}
// console.log(' The search results ',this.devices)
});
});
},
// this.devices Is a list of Bluetooth devices , Render to the page display, click to execute Bluetooth connection
// Click on the link Bluetooth
createBLEConnection(e) {
console.log(' Click Connect Bluetooth ', e);
const deviceId = e.deviceId;
const name = e.name;
this._createBLEConnection(deviceId, name);
},
// Connect Bluetooth devices
_createBLEConnection(deviceId, name) {
this.$myToast(this.$t('wechat.w224'), 'loading'); // In connection device
// Connecting low power Bluetooth devices
uni.createBLEConnection({
deviceId, // Used to distinguish between devices id
success: () => {
console.log(' The call to connect the Bluetooth interface succeeded createBLEConnection success', this.devices);
this.devices.forEach((item, index) => {
this.$set(this.devices[index], 'isShowConnect', false);
if (item.deviceId === deviceId) {
this.$set(this.devices[index], 'isShowConnect', true);
}
});
this.$myToast(this.$t('wechat.w225'), 'success'); // Device connected successfully
this.connected = true;
this.isConnected = false;
this.name = name;
this.deviceId = deviceId;
// Get all services from Bluetooth devices (service)
this.getBLEDeviceServices(deviceId);
// Finally connect the device
uni.setStorage({
key: LAST_CONNECTED_DEVICE,
data: name + ':' + deviceId
});
},
complete() {
uni.hideLoading();
},
fail: res => {
// Call to connect Bluetooth interface failed
console.log(' Call to connect Bluetooth interface failed createBLEConnection fail', res);
uni.showModal({
title: this.$t('wechat.w227'),
content: ' Bluetooth connection failed ',
showCancel: false
});
}
});
// The Bluetooth device you need has been found , Stop searching for nearby Bluetooth peripherals
this.stopBluetoothDevicesDiscovery();
},
// Get all services from Bluetooth devices (service)
getBLEDeviceServices(deviceId) {
uni.getBLEDeviceServices({
deviceId,
success: res => {
console.log(' Get all services from Bluetooth devices getBLEDeviceServices', res);
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].isPrimary) {
this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
return;
}
}
}
});
},
stopBluetoothDevicesDiscovery() {
uni.stopBluetoothDevicesDiscovery({
complete: () => {
// console.log('stopBluetoothDevicesDiscovery')
this._discoveryStarted = false;
}
});
},
/* Get all the eigenvalues in a service of a Bluetooth device (characteristic) characteristic: uuid: Characteristic values of Bluetooth devices uuid properties: The operation types supported by this characteristic value */
getBLEDeviceCharacteristics(deviceId, serviceId) {
uni.getBLEDeviceCharacteristics({
// there deviceId Need to have passed createBLEConnection Establish a link with the corresponding device
deviceId,
// there serviceId( Bluetooth service uuid) Need to be in getBLEDeviceServices Interface
serviceId,
success: res => {
console.log(' Eigenvalue change getBLEDeviceCharacteristics success', res.characteristics);
// There will be characteristic values that support write, The writing is successful but there is no response
// You can only try one by one
// characteristics: Equipment service list
for (let i = 0; i < res.characteristics.length; i++) {
const item = res.characteristics[i];
// if (item.properties.read) {
// uni.readBLECharacteristicValue({
// deviceId,
// serviceId,
// characteristicId: item.uuid
// })
// }
if (item.properties.write) {
this.canWrite = true;
this._deviceId = deviceId;
this._serviceId = serviceId;
this._characteristicId = item.uuid;
}
if (item.properties.notify || item.properties.indicate) {
uni.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: item.uuid,
state: true
});
}
}
},
fail(res) {
console.error(' Eigenvalue change getBLEDeviceCharacteristics', res);
}
});
},
// Click Print after Bluetooth connection is successful , Print data
// Click Print : Write data ( Print the content according to the needs of the project )
writeBLECharacteristicValue() {
this.isLoading = true;
setTimeout(() => {
this.isDisabled = false;
this.isLoading = false;
}, 3000);
let printerJobs = new PrinterJobs();
const {
channels, header, dataList } = this.printInfo;
// console.log(' Channel data ', dataList)
let title = '';
header.forEach(item => {
title = `${
item.name} `;
});
// Header information to print
printerJobs
.setAlign('ct')
.setSize(2, 2)
.print(this.$t('wechat.w221')) //' Record reports '
.setSize(0, 0)
.print()
.setAlign('lt')
.setSize(1, 1)
.print(`${
this.$t('wechat.w51')}:${
this.info.name}`) // Equipment name
.print(`${
this.$t('wechat.w76')}:${
this.info.modelName}`) // Model of equipment
.print(`${
this.$t('wechat.w46')}:${
this.info.deviceSerial}`) // Serial number
.print(`${
this.$t('wechat.w100')}:${
this.userInfo.relName}`) // user name
.print(`${
this.$t('wechat.w101')}:${
this.remark}`); // remarks
if (this.isEn) {
channels.forEach(item => {
printerJobs
.print(`${
item.name}(Max):${
item.max}${
item.unitIcon}`)
.print(`${
this.$t('wechat.w148')}:${
this.$timestampToTimeEn(item.maxDate)}`) // Time
.print(`${
item.name}(Min):${
item.min}${
item.unitIcon}`)
.print(`${
this.$t('wechat.w148')}:${
this.$timestampToTimeEn(item.minDate)}`); // Time
});
} else {
channels.forEach(item => {
printerJobs
.print(`${
item.name}(Max):${
item.max}${
item.unitIcon}`)
.print(`${
this.$t('wechat.w148')}:${
this.$timestampToTime2(item.maxDate)}`) // Time
.print(`${
item.name}(Min):${
item.min}${
item.unitIcon}`)
.print(`${
this.$t('wechat.w148')}:${
this.$timestampToTime2(item.minDate)}`); // Time
});
}
printerJobs.print(printerUtil.fillLine()).setSize(1, 1);
let titleStr = '';
header.forEach((item, index) => {
titleStr = titleStr + `${
index === 0 ? '' : ' '}` + `${
item.name}`;
});
printerJobs.print(printerUtil.inline(this.$t('wechat.w222'), `${
titleStr}`)); // Recording time
// Print '----------------'
printerJobs.print(printerUtil.fillLine());
// What to print :
dataList.forEach(item => {
let str = '';
header.forEach((item2, index2) => {
// no
str = str + `${
index2 === 0 ? '' : ' '}` + `${
item[item2.columnName] ? item[item2.columnName].toFixed(2) : this.$t('wechat.w71empty')}`;
});
if (this.isEn) {
printerJobs.print(printerUtil.inline(`${
this.$timestampToTimeEn2(item.dataTime)}`, `${
str}`));
} else {
printerJobs.print(printerUtil.inline(`${
this.$timestampToTime3(item.dataTime)}`, `${
str}`));
}
// console.log(`${item.dataTime}`, str);
});
// ending
printerJobs
.println()
.print(`${
this.$t('wechat.w223')}:`) //' Signature
.println()
.println();
let buffer = printerJobs.buffer();
// console.log('ArrayBuffer', 'length: ' + buffer.byteLength, ' hex: ' + ab2hex(buffer));
// 1. There is a possibility of write failure when parallel calls are repeated
// 2. It is recommended that no more than... Be written each time 20 byte
// Subcontracting , Delay call
const maxChunk = 20;
const delay = 40;
for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
let subPackage = buffer.slice(i, i + maxChunk <= length ? i + maxChunk : length);
// subPackage: Parameters
setTimeout(this._writeBLECharacteristicValue, j * delay, subPackage);
}
},
// Write binary data to the characteristic value of low-power Bluetooth device . Be careful : The eigenvalue of the device must support write To successfully call .
_writeBLECharacteristicValue(buffer) {
uni.writeBLECharacteristicValue({
deviceId: this._deviceId, // Bluetooth devices id
serviceId: this._serviceId, // The Bluetooth eigenvalue corresponds to the service uuid
characteristicId: this._characteristicId, // Bluetooth eigenvalue uuid
value: buffer, // The binary value corresponding to the characteristic value of the Bluetooth device
success(res) {
console.log('writeBLECharacteristicValue success', res);
},
fail(res) {
console.log('writeBLECharacteristicValue fail', res);
}
});
},
}
Printing effect :
Other documents :
printerutil.js
// Printer paper width 58mm, Width of page 384, The character width is 1, Each row can hold at most 32 Characters
const PAGE_WIDTH = 384;
const MAX_CHAR_COUNT_EACH_LINE = 32;
/** * @param str * @returns {boolean} str Is it all Chinese */
function isChinese(str) {
return /^[\u4e00-\u9fa5]$/.test(str);
}
/** * Return string width (1 Chinese =2 English characters ) * @param str * @returns {number} */
function getStringWidth(str) {
let width = 0;
for (let i = 0, len = str.length; i < len; i++) {
width += isChinese(str.charAt(i)) ? 2 : 1;
}
return width;
}
/** * Output on the same line str1, str2,str1 be at the left side , str2 be at the right * @param {string} str1 Content 1 * @param {string} str2 Content 2 * @param {number} fontWidth Character width 1/2 * @param {string} fillWith str1 str2 Fill characters between * */
function inline(str1, str2, fillWith = ' ', fontWidth = 1) {
const lineWidth = MAX_CHAR_COUNT_EACH_LINE / fontWidth;
// The number of characters to fill
let fillCount = lineWidth - (getStringWidth(str1) + getStringWidth(str2)) % lineWidth;
let fillStr = new Array(fillCount).fill(fillWith.charAt(0)).join('');
return str1 + fillStr + str2;
}
/** * Fill a whole line with characters * @param {string} fillWith Fill character * @param {number} fontWidth Character width 1/2 */
function fillLine(fillWith = '-', fontWidth = 1) {
const lineWidth = MAX_CHAR_COUNT_EACH_LINE / fontWidth;
return new Array(lineWidth).fill(fillWith.charAt(0)).join('');
}
/** * The text content is centered , Fill left and right with characters * @param {string} str Written content * @param {number} fontWidth Character width 1/2 * @param {string} fillWith str1 str2 Fill characters between */
function fillAround(str, fillWith = '-', fontWidth = 1) {
const lineWidth = MAX_CHAR_COUNT_EACH_LINE / fontWidth;
let strWidth = getStringWidth(str);
// The content has exceeded one line , There is no need to fill
if (strWidth >= lineWidth) {
return str;
}
// The number of characters to fill
let fillCount = lineWidth - strWidth;
// The number of characters filled on the left
let leftCount = Math.round(fillCount / 2);
// Padding characters on both sides , It needs to be considered that the left side needs to be filled , The right side does not need to be filled
let fillStr = new Array(leftCount).fill(fillWith.charAt(0)).join('');
return fillStr + str + fillStr.substr(0, fillCount - leftCount);
}
module.exports = {
inline: inline,
fillLine: fillLine,
fillAround: fillAround,
};
printerjobs.js
const commands = require('./commands.js');
const TextEncoder = require('../text-encoding/index').TextEncoder;
const printerJobs = function () {
this._queue = Array.from(commands.HARDWARE.HW_INIT);
this._encoder = new TextEncoder("gb2312", {
NONSTANDARD_allowLegacyEncoding: true});
this._enqueue = function (cmd) {
this._queue.push.apply(this._queue, cmd);
}
};
/** * Add print content * @param {string} content Written content */
printerJobs.prototype.text = function (content) {
if (content) {
let uint8Array = this._encoder.encode(content);
let encoded = Array.from(uint8Array);
this._enqueue(encoded);
}
return this;
};
/** * Print text * @param {string} content Written content */
printerJobs.prototype.print = function (content) {
this.text(content);
this._enqueue(commands.LF);
return this;
};
/** * Print text and wrap * @param {string} content Written content */
printerJobs.prototype.println = function (content = '') {
return this.print(content + commands.EOL);
};
/** * Set alignment * @param {string} align Alignment mode LT/CT/RT */
printerJobs.prototype.setAlign = function (align) {
this._enqueue(commands.TEXT_FORMAT['TXT_ALIGN_' + align.toUpperCase()]);
return this;
};
/** * Set the font * @param {string} family A/B/C */
printerJobs.prototype.setFont = function (family) {
this._enqueue(commands.TEXT_FORMAT['TXT_FONT_' + family.toUpperCase()]);
return this;
};
/** * Set the font size * @param {number} width Font width 1~2 * @param {number} height Font height 1~2 */
printerJobs.prototype.setSize = function (width, height) {
if (2 >= width && 2 >= height) {
this._enqueue(commands.TEXT_FORMAT.TXT_NORMAL);
if (2 === width && 2 === height) {
this._enqueue(commands.TEXT_FORMAT.TXT_4SQUARE);
} else if (1 === width && 2 === height) {
this._enqueue(commands.TEXT_FORMAT.TXT_2HEIGHT);
} else if (2 === width && 1 === height) {
this._enqueue(commands.TEXT_FORMAT.TXT_2WIDTH);
}
}
return this;
};
/** * Set whether the font is bold * @param {boolean} bold */
printerJobs.prototype.setBold = function (bold) {
if (typeof bold !== 'boolean') {
bold = true;
}
this._enqueue(bold ? commands.TEXT_FORMAT.TXT_BOLD_ON : commands.TEXT_FORMAT.TXT_BOLD_OFF);
return this;
};
/** * Set whether underline is turned on * @param {boolean} underline */
printerJobs.prototype.setUnderline = function (underline) {
if (typeof underline !== 'boolean') {
underline = true;
}
this._enqueue(underline ? commands.TEXT_FORMAT.TXT_UNDERL_ON : commands.TEXT_FORMAT.TXT_UNDERL_OFF);
return this;
};
/** * Set the line spacing to n Click line , The default line spacing is 30 spot * @param {number} n 0≤n≤255 */
printerJobs.prototype.setLineSpacing = function (n) {
if (n === undefined || n === null) {
this._enqueue(commands.LINE_SPACING.LS_DEFAULT);
} else {
this._enqueue(commands.LINE_SPACING.LS_SET);
this._enqueue([n]);
}
return this;
};
/** * Print blank lines * @param {number} n */
printerJobs.prototype.lineFeed = function (n = 1) {
return this.print(new Array(n).fill(commands.EOL).join(''));
};
/** * Set font color , Printer support is required * @param {number} color - 0 Default color black 1 Red */
printerJobs.prototype.setColor = function (color) {
this._enqueue(commands.COLOR[color === 1 ? 1 : 0]);
return this;
};
/** * https://support.loyverse.com/hardware/printers/use-the-beeper-in-a-escpos-printers * Beep alarm , Printer support is required * @param {number} n Number of beeps ,1-9 * @param {number} t Buzzer length ,1-9 */
printerJobs.prototype.beep = function (n, t) {
this._enqueue(commands.BEEP);
this._enqueue([n, t]);
return this;
};
/** * Clear task */
printerJobs.prototype.clear = function () {
this._queue = Array.from(commands.HARDWARE.HW_INIT);
return this;
};
/** * return ArrayBuffer */
printerJobs.prototype.buffer = function () {
return new Uint8Array(this._queue).buffer;
};
module.exports = printerJobs;
commands.js
/** * Modified from https://github.com/song940/node-escpos/blob/master/commands.js * ESC/POS _ (Constants) */
var _ = {
LF: [0x0a],
FS: [0x1c],
FF: [0x0c],
GS: [0x1d],
DLE: [0x10],
EOT: [0x04],
NUL: [0x00],
ESC: [0x1b],
EOL: '\n',
};
/** * [FEED_CONTROL_SEQUENCES Feed control sequences] * @type {Object} */
_.FEED_CONTROL_SEQUENCES = {
CTL_LF: [0x0a], // Print and line feed Print line breaks
CTL_GLF: [0x4a, 0x00], // Print and feed paper (without spaces between lines) Printing and paper feeding ( No space between lines )
CTL_FF: [0x0c], // Form feed Change the page
CTL_CR: [0x0d], // Carriage return
CTL_HT: [0x09], // Horizontal tab enter
CTL_VT: [0x0b], // Vertical tab Vertical tabs
};
_.CHARACTER_SPACING = {
CS_DEFAULT: [0x1b, 0x20, 0x00],
CS_SET: [0x1b, 0x20]
};
_.LINE_SPACING = {
LS_DEFAULT: [0x1b, 0x32],
LS_SET: [0x1b, 0x33]
};
/** * [HARDWARE Printer hardware] * @type {Object} */
_.HARDWARE = {
HW_INIT: [0x1b, 0x40], // Clear data in buffer and reset modes
HW_SELECT: [0x1b, 0x3d, 0x01], // Printer select
HW_RESET: [0x1b, 0x3f, 0x0a, 0x00], // Reset printer hardware
};
/** * [CASH_DRAWER Cash Drawer] * @type {Object} */
_.CASH_DRAWER = {
CD_KICK_2: [0x1b, 0x70, 0x00], // Sends a pulse to pin 2 []
CD_KICK_5: [0x1b, 0x70, 0x01], // Sends a pulse to pin 5 []
};
/** * [MARGINS Margins sizes] * @type {Object} */
_.MARGINS = {
BOTTOM: [0x1b, 0x4f], // Fix bottom size
LEFT: [0x1b, 0x6c], // Fix left size
RIGHT: [0x1b, 0x51], // Fix right size
};
/** * [PAPER Paper] * @type {Object} */
_.PAPER = {
PAPER_FULL_CUT: [0x1d, 0x56, 0x00], // Full cut paper
PAPER_PART_CUT: [0x1d, 0x56, 0x01], // Partial cut paper
PAPER_CUT_A: [0x1d, 0x56, 0x41], // Partial cut paper
PAPER_CUT_B: [0x1d, 0x56, 0x42], // Partial cut paper
};
/** * [TEXT_FORMAT Text format] * @type {Object} */
_.TEXT_FORMAT = {
TXT_NORMAL: [0x1b, 0x21, 0x00], // Normal text
TXT_2HEIGHT: [0x1b, 0x21, 0x10], // Double height text Double height text
TXT_2WIDTH: [0x1b, 0x21, 0x20], // Double width text Double width text
TXT_4SQUARE: [0x1b, 0x21, 0x30], // Double width & height text Double width and height text
TXT_UNDERL_OFF: [0x1b, 0x2d, 0x00], // Underline font OFF
TXT_UNDERL_ON: [0x1b, 0x2d, 0x01], // Underline font 1-dot ON
TXT_UNDERL2_ON: [0x1b, 0x2d, 0x02], // Underline font 2-dot ON
TXT_BOLD_OFF: [0x1b, 0x45, 0x00], // Bold font OFF
TXT_BOLD_ON: [0x1b, 0x45, 0x01], // Bold font ON
TXT_ITALIC_OFF: [0x1b, 0x35], // Italic font ON
TXT_ITALIC_ON: [0x1b, 0x34], // Italic font ON
TXT_FONT_A: [0x1b, 0x4d, 0x00], // Font type A
TXT_FONT_B: [0x1b, 0x4d, 0x01], // Font type B
TXT_FONT_C: [0x1b, 0x4d, 0x02], // Font type C
TXT_ALIGN_LT: [0x1b, 0x61, 0x00], // Left justification
TXT_ALIGN_CT: [0x1b, 0x61, 0x01], // Centering
TXT_ALIGN_RT: [0x1b, 0x61, 0x02], // Right justification
};
/** * [BARCODE_FORMAT Barcode format] * @type {Object} */
_.BARCODE_FORMAT = {
BARCODE_TXT_OFF: [0x1d, 0x48, 0x00], // HRI barcode chars OFF
BARCODE_TXT_ABV: [0x1d, 0x48, 0x01], // HRI barcode chars above
BARCODE_TXT_BLW: [0x1d, 0x48, 0x02], // HRI barcode chars below
BARCODE_TXT_BTH: [0x1d, 0x48, 0x03], // HRI barcode chars both above and below
BARCODE_FONT_A: [0x1d, 0x66, 0x00], // Font type A for HRI barcode chars
BARCODE_FONT_B: [0x1d, 0x66, 0x01], // Font type B for HRI barcode chars
BARCODE_HEIGHT: function (height) {
// Barcode Height [1-255]
return [0x1d, 0x68, height];
},
BARCODE_WIDTH: function (width) {
// Barcode Width [2-6]
return [0x1d, 0x77, width];
},
BARCODE_HEIGHT_DEFAULT: [0x1d, 0x68, 0x64], // Barcode height default:100
BARCODE_WIDTH_DEFAULT: [0x1d, 0x77, 0x01], // Barcode width default:1
BARCODE_UPC_A: [0x1d, 0x6b, 0x00], // Barcode type UPC-A
BARCODE_UPC_E: [0x1d, 0x6b, 0x01], // Barcode type UPC-E
BARCODE_EAN13: [0x1d, 0x6b, 0x02], // Barcode type EAN13
BARCODE_EAN8: [0x1d, 0x6b, 0x03], // Barcode type EAN8
BARCODE_CODE39: [0x1d, 0x6b, 0x04], // Barcode type CODE39
BARCODE_ITF: [0x1d, 0x6b, 0x05], // Barcode type ITF
BARCODE_NW7: [0x1d, 0x6b, 0x06], // Barcode type NW7
BARCODE_CODE93: [0x1d, 0x6b, 0x48], // Barcode type CODE93
BARCODE_CODE128: [0x1d, 0x6b, 0x49], // Barcode type CODE128
};
/** * [IMAGE_FORMAT Image format] * @type {Object} */
_.IMAGE_FORMAT = {
S_RASTER_N: [0x1d, 0x76, 0x30, 0x00], // Set raster image normal size
S_RASTER_2W: [0x1d, 0x76, 0x30, 0x01], // Set raster image double width
S_RASTER_2H: [0x1d, 0x76, 0x30, 0x02], // Set raster image double height
S_RASTER_Q: [0x1d, 0x76, 0x30, 0x03], // Set raster image quadruple
};
/** * [BITMAP_FORMAT description] * @type {Object} */
_.BITMAP_FORMAT = {
BITMAP_S8: [0x1b, 0x2a, 0x00],
BITMAP_D8: [0x1b, 0x2a, 0x01],
BITMAP_S24: [0x1b, 0x2a, 0x20],
BITMAP_D24: [0x1b, 0x2a, 0x21]
};
/** * [GSV0_FORMAT description] * @type {Object} */
_.GSV0_FORMAT = {
GSV0_NORMAL: [0x1d, 0x76, 0x30, 0x00],
GSV0_DW: [0x1d, 0x76, 0x30, 0x01],
GSV0_DH: [0x1d, 0x76, 0x30, 0x02],
GSV0_DWDH: [0x1d, 0x76, 0x30, 0x03]
};
/** * [BEEP description] * @type {string} */
_.BEEP = [0x1b, 0x42]; // Printer Buzzer pre hex
/** * [COLOR description] * @type {Object} */
_.COLOR = {
0: [0x1b, 0x72, 0x00], // black
1: [0x1b, 0x72, 0x01] // red
};
/** * [exports description] * @type {[type]} */
module.exports = _;

notes :
1、 The connected Bluetooth must be low-power Bluetooth , Classic Bluetooth cannot be searched ( Because you can't execute uni.onBluetoothDeviceFound)
2、 Some mobile phones need to turn on the location to search for Bluetooth ( Start positioning to execute uni.onBluetoothDeviceFound)
边栏推荐
- Interpretable ml of Li Hongyi's machine learning model
- "Weilai Cup" 2022 Niuke summer multi school training camp 2
- PHP获取本周所有日期或者最近七天所有日期
- Zhou Hongyi talks about Internet thinking: users, not customers
- Untiy controls the playback speed of animation
- SQL注入 Less26(过滤空格和注释符,使用不带空格的报错注入)
- [try to hack] intranet Foundation
- 社区点赞业务缓存设计优化探索
- 2022.07.07 summer training personal qualifying (II)
- Analysys analysis: focus on users, improve the user experience of mobile banking, and help the growth of user value
猜你喜欢

Hcip rip comprehensive experiment

To build agile teams, these methods are indispensable

Configure jupyter remote server

顶级“Redis笔记”,缓存雪崩+击穿+穿透+集群+分布式锁,NB了

Several ways to bind controls --butterknife/viewbinding/databinding

分布式定时器

Developing NES games with C language (cc65) 08. Background collision

Yolov3 complete explanation - from the perspective of data coding

Detailed deployment and configuration of CEPH cluster (II)

"Weilai Cup" 2022 Niuke summer multi school training camp 2
随机推荐
Full resolution of the use of go native plug-ins
新手如何快速完成建站?来免费“试衣间”体验
Developing NES games with C language (cc65) 06. Sprites
IRBuilder
太赞了!京东研发一哥力荐的高可用网站构建技术PDF,备好水,慢慢啃
Hcip day 6 (OSPF related knowledge)
Yolov3 complete explanation - from the perspective of data coding
PHP timestamp subtraction converts to days, hours, minutes and seconds
Top level "redis notes", cache avalanche + breakdown + penetration + cluster + distributed lock, Nb
2022.07.08 summer training personal qualifying (III)
Matlab sets the size of graphics window and image and the position of legend
LyScript 获取上一条与下一条指令
Localization, low latency, green and low carbon: Alibaba cloud officially launched Fuzhou data center
Notes on using objectanimator
用C语言开发NES游戏(CC65)07、控制器
Huawei releases harmonyos 3 and all scene new products, and the smart experience goes further
laravel表单数据验证
【Try to Hack】AT、SC、PS命令提权
Reasons and solutions for moving the first column to the last column in El table
String function (Part 2)