最近项目需要连接蓝牙进行打印,一般连接连接蓝牙进行打印的都是通过APP,我们之前的项目也是通过Websoket发送打印数据,APP接收后,进行连接蓝牙打印,但是这样的方式就是不便捷的,对于用户来说,在下载一个APP,在进行打印,是比较麻烦的,所以找到了Webbluetooth,也是参考了很多文章。主要逻辑就是使用
navigator.bluetooth.requestDevice({
filters: [{
namePrefix: 'CS3',
acceptAllDevices: true,
services: ['0000fee7-0000-1000-8000-00805f9b34fb'],
}]
})
.then(device => {
console.log('> Found ' + device.name);
console.log('Connecting to GATT Server...');
return device.gatt.connect();
})
.then(server => server.getPrimaryService("0000fee7-0000-1000-8000-00805f9b34fb"))
.then(service => service.getCharacteristic("0000fec7-0000-1000-8000-00805f9b34fb"))
.then(characteristic => {
// Cache the characteristic
printCharacteristic = characteristic;
// console.log(printCharacteristic);
sendPrinterData();
上面的services就是打印服务的UUID,如何查找呢?主要通过:在浏览器中:输入chrome://bluetooth-internals/#adapter
就可以扫描到:
这里就是services:
demo:https://www.ylesb.com/demos/bluetooth-printer/index.html
就是打印服务的UUID,替换上面,然后打印数据函数自己定义好就可以了。最后附上一些参考学习的文章以及项目。
参考:
https://googlechrome.github.io/samples/web-bluetooth/index.html
https://www.jianshu.com/p/d991f0fdec63
https://webbluetoothcg.github.io/demos/bluetooth-printer/
https://webbluetoothcg.github.io/demos/
https://github.com/WebBluetoothCG/demos
https://github.com/Sun-Target/print
https://www.cnblogs.com/jam-liu/p/14654548.html