1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<template>
    <view class="page-container">
        <view class="form">
            <view class="form-item">
                <view class="title">物料代码:</view>
                <view class="right">
                    <input name="HMaterCode" v-model="hform.HMaterCode" placeholder="请输入物料代码" />
                </view>
            </view>
            <view class="form-item">
                <view class="title">名称:</view>
                <view class="right">
                    <input name="HMaterName" v-model="hform.HMaterName" placeholder="请输入名称" />
                </view>
            </view>
            <view class="form-item">
                <view class="title">规格型号:</view>
                <view class="right">
                    <input name="HMaterType" v-model="hform.HMaterType" placeholder="请输入物料规格型号" />
                </view>
            </view>
            <view class="form-item">
                <view class="title">数量:</view>
                <view class="right">
                    <input name="HNumber" v-model="hform.HNumber" placeholder="请输入物料数量" />
                </view>
            </view>
            <view class="form-item">
                <view class="title">条形码:</view>
                <view class="right">
                    <input name="HBarCode" v-model="hform.HBarCode" placeholder="请输入条形码" />
                </view>
            </view>
 
            <view class="buttons">
                <button class="btn-c" @click="searchLabelPrinter()">搜索打印机</button>
                <button class="btn-c" @click="labelPrint()">标签打印</button>
            </view>
 
        </view>
        <!-- 打印机选择列表 -->
        <view v-for="(device, index) in discoveredDevices" :key="device.address">
            <uni-card :title="device.name" :extra="connectedDeviceId === device.address?'已连接':'未连接'"
                style="margin: 10px;">
                <view class="operation-zone">
                    <button class="op1" size="mini" plain @click="connectBT(device)">连接设备</button>
                    <button class="op4" size="mini" plain @click="closeBluetooth()">断开连接</button>
                </view>
            </uni-card>
        </view>
 
        <!-- todo: 打印标签预览 -->
    </view>
</template>
 
<script>
    import bluetoothTool from '@/plugins/BluetoothTool.js'
    import permission from '@/plugins/permission.js'
    import {
        InputImage
    } from '@psdk/frame-imageb';
    import {
        ConnectedDevice,
        Lifecycle,
        Raw,
        FakeConnectedDevice,
        WriteOptions,
    } from '@psdk/frame-father';
    import {
        CBar,
        CBox,
        CForm,
        CImage,
        CLine,
        CCodeRotation,
        CCodeType,
        CPage,
        CText,
        CFont,
        CBold,
        CRotation,
        CInverse,
        CMag,
        CQRCode,
        CCorrectLevel,
        CSN,
        CStatus,
    } from "@psdk/cpcl";
    import {
        EImage
    } from "@psdk/esc";
    export default {
        data() {
            return {
                hform: {
                    HMaterCode: "",
                    HMaterName: "",
                    HMaterType: "",
                    HNumber: "",
                    HBarCode: "",
                },
                discoveredDevices: [], // 查询到的设备
                connectedDeviceId: ""
            }
        },
        async onLoad() {
            //#ifdef APP-PLUS
            // 蓝牙
            bluetoothTool.init({
                listenBTStatusCallback: (state) => {
                    if (state == 'STATE_ON') {
                        console.log(state);
                    }
                },
                discoveryDeviceCallback: this.onDevice,
                discoveryFinishedCallback: function() {
                    console.log("搜索完成");
                },
                readDataCallback: function(dataByteArr) {
                    /* if(that.receiveDataArr.length >= 200) {
                        that.receiveDataArr = [];
                    }
                    that.receiveDataArr.push.apply(that.receiveDataArr, dataByteArr); */
                    console.log("读取完成" + dataByteArr);
                },
                connExceptionCallback: function(e) {
                    console.log(e);
                }
            });
            //#endif
        },
        methods: {
            async checkPermission() { // 授权
                try {
                    let checkResult = await permission.androidPermissionCheck("bluetooth");
                    console.log("检测信息:", checkResult);
                    if (checkResult.code == 1) {
                        let result = checkResult.data;
                        if (result == 1) {
                            console.log("授权成功!");
                        }
                        if (result == 0) {
                            console.log("授权已拒绝!");
                        }
                        if (result == -1) {
                            console.log("您已永久拒绝权限,请在应用设置中手动打开!");
                        }
                    }
                } catch (err) {
                    console.log("授权失败:", err);
                }
            },
            async searchLabelPrinter() {
                // 查找打印机
                var that = this
                // 使用openBluetoothAdapter 接口,免去主动申请权限的麻烦
                uni.openBluetoothAdapter({
                    success: async (res) => {
                        await this.checkPermission();
                        console.log('start discovery devices');
                        this.discoveredDevices = [];
                        console.log(res)
                        bluetoothTool.discoveryNewDevice();
                    },
                    fail: async (e) => {
                        console.error(e)
                        switch (e.code) {
                            case "10009":
                                this.showToast("此设备不支持设备搜索功能!");
                                break;
                            default:
                                console.error(e);
                        }
                    }
                })
 
            },
            onDevice(device) {
                console.log("监听寻找到新设备的事件---------------")
                console.log(device)
                if (typeof device === 'undefined') return;
                if (typeof device.name === 'undefined') return;
                console.log(device.name);
                if (device.name === '') return;
                if (device.name === null) return;
                if (device.name.toUpperCase().endsWith('_BLE') ||
                    device.name.toUpperCase().endsWith('-LE') ||
                    device.name.toUpperCase().endsWith('-BLE')) return;
                const isDuplicate = this.discoveredDevices.find(item => item.address === device.address);
                if (isDuplicate) return;
                this.discoveredDevices.push(device);
            },
            connectBT(device) {
                const vm = this;
                uni.showLoading({
                    title: '连接中'
                });
                bluetoothTool.connDevice(device.address, (result) => {
                    console.log(result)
                    uni.hideLoading()
                    if (result) {
                        //     // console.log(result);
                        bluetoothTool.cancelDiscovery();
                        // console.log(vm.$printer)
                        vm.$printer.init(new FakeConnectedDevice());
                        vm.connectedDeviceId = device.address;
                        uni.showToast({
                            icon: 'none',
                            title: '连接成功'
                        })
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: '连接失败'
                        })
                    }
                });
            },
            stopSearchBT() {
                console.log("停止搜寻附近的蓝牙外围设备---------------")
                bluetoothTool.cancelDiscovery();
            },
            closeBluetooth() {
                console.log("停止蓝牙连接")
                const vm = this;
                if (vm.connectedDeviceId != '') {
                    bluetoothTool.closeBtSocket();
                    vm.connectedDeviceId = "";
                }
            },
            labelPrint() {
                // 打印
                // 检查蓝牙连接
                let btStatus = bluetoothTool.getBluetoothStatus()
                if(btStatus != true) {
                    this.showToast("蓝牙连接异常!")
                    return
                }
                
                // 检查是否连接设备
                let pairedDevices = bluetoothTool.getPairedDevices()
                if(pairedDevices.length < 1) {
                    this.showToast("无设备连接!")
                    return
                }
                
                // 检查表单项是否有空值
                for (var key in this.hform) {
                    if (this.hform[key] == "") {
                        // todo 提示表单项不能为空
                        this.showToast("表单不能有空值!")
                        return
                    }
                }
                this.printWrite()
                
                
            },
            showToast(msg, status = "none") {
                uni.showToast({
                    title: msg,
                    icon: status,
                    duration: 2000
                });
            },
            ///转成安卓有符号的
            uint8ArrayToSignedArray(uint8Array) {
                let signedArray = new Array(uint8Array.length);
                for (let i = 0; i < uint8Array.length; i++) {
                    if (uint8Array[i] >= 128) {
                        signedArray[i] = uint8Array[i] - 256;
                    } else {
                        signedArray[i] = uint8Array[i];
                    }
                }
                return signedArray;
            },
            async printWrite(type = "cpcl") {
                const vm = this;
                console.log("开始打印------------------")
                switch (type) {
                    case "cpcl":
                        await vm.writeCpclModel();
                        break;
                }
            },
            async writeCpclModel() {
                const vm = this;
                try {
                    const cpcl = await vm.$printer.cpcl().clear()
                        .page(new CPage({
                            width: 608,
                            height: 260
                        }))
                        .text(new CText({
                            x: 54,
                            y: 40,
                            content: "物料代码: " + vm.hform.HMaterCode,
                            font: CFont.TSS24
                        }))
                        .text(new CText({
                            x: 54,
                            y: 80,
                            content: "名    称: " + vm.hform.HMaterName,
                            font: CFont.TSS24
                        }))
                        .text(new CText({
                            x: 54,
                            y: 120,
                            content: "规格型号: " + vm.hform.HMaterType,
                            font: CFont.TSS24
                        }))
                        .text(new CText({
                            x: 54,
                            y: 160,
                            content: "数    量: " + vm.hform.HNumber,
                            font: CFont.TSS24
                        }))
                        .bar(new CBar({
                            x: 120,
                            y: 200,
                            lineWidth: 1,
                            height: 80,
                            content: vm.hform.HBarCode,
                            codeRotation: CCodeRotation.ROTATION_0,
                            codeType: CCodeType.CODE128
                        }))
                        .form(new CForm()) //标签纸需要加定位指令
                        .print();
                    console.log(cpcl.command().string());
                    var binary = cpcl.command().binary();
                    await this.sendMessage(Array.from(this.uint8ArrayToSignedArray(binary)));
                } catch (e) {
                    console.error(e);
                    uni.showToast({
                        title: '失败',
                    });
                }
            },
            async sendMessage(cmd) {
                console.log(cmd);
                const result = bluetoothTool.sendByteData(cmd);
                uni.showToast({
                    icon: 'none',
                    title: result ? '发送成功!' : '发送失败...'
                })
            },
        }
    }
</script>
 
<style lang="scss">
    .page-container {
        padding: 20rpx
    }
 
    .form {
        width: 668rpx;
        margin: 20rpx auto;
        // padding-bottom: 240rpx;
    }
 
    .form-item {
        display: flex;
        align-items: center;
        font-size: 30rpx;
        padding: 6rpx 0;
 
        .title {
            width: 208rpx;
 
            text {
                color: red;
                font-weight: bold;
            }
        }
 
        .right {
            width: 450rpx;
            border-radius: 22rpx;
            border: 1px solid #acacac;
 
            input {
                width: 100%;
                padding: 8rpx 20rpx;
                font-size: 30rpx;
            }
        }
    }
 
    .buttons {
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 20rpx;
 
        button {
            border-radius: 50rpx;
            width: 220rpx;
            height: 66rpx;
            line-height: 66rpx;
            font-size: 28rpx;
        }
 
        .btn-a {
            background-color: #acacac;
            color: #fff;
        }
 
        .btn-b {
            background-color: #41a863;
            color: #fff;
        }
 
        .btn-c {
            background-color: #3a78ff;
            color: #fff;
        }
    }
 
    .operation-zone {
        display: flex;
        justify-content: space-around;
        margin-top: 10rpx;
 
        .op1 {
            border: 1px solid #41a863;
            color: #41a863;
        }
 
        .op4 {
            border: 1px solid #da0000;
            color: #da0000;
        }
 
    }
</style>