Browse Source

initial commit

master
munir ishak 4 years ago
commit
08a7ebefa5
100 changed files with 9975 additions and 0 deletions
  1. 1
    0
      .gitattributes
  2. 3
    0
      .npmignore
  3. 21
    0
      LICENSE
  4. 485
    0
      README.md
  5. 60
    0
      android/build.gradle
  6. 13
    0
      android/build/generated/source/buildConfig/debug/cn/jystudio/bluetooth/BuildConfig.java
  7. 16
    0
      android/build/intermediates/aapt_friendly_merged_manifests/debug/aapt/AndroidManifest.xml
  8. 1
    0
      android/build/intermediates/aapt_friendly_merged_manifests/debug/aapt/output.json
  9. 1
    0
      android/build/intermediates/annotation_processor_list/debug/annotationProcessors.json
  10. 0
    0
      android/build/intermediates/annotations_typedef_file/debug/extractDebugAnnotations/typedefs.txt
  11. BIN
      android/build/intermediates/compile_library_classes/debug/classes.jar
  12. BIN
      android/build/intermediates/compile_only_not_namespaced_r_class_jar/debug/generateDebugRFile/R.jar
  13. BIN
      android/build/intermediates/incremental/debug-mergeJavaRes/merge-state
  14. BIN
      android/build/intermediates/incremental/debug-mergeJniLibs/merge-state
  15. 2
    0
      android/build/intermediates/incremental/mergeDebugJniLibFolders/merger.xml
  16. 2
    0
      android/build/intermediates/incremental/mergeDebugShaders/merger.xml
  17. 2
    0
      android/build/intermediates/incremental/packageDebugAssets/merger.xml
  18. 1
    0
      android/build/intermediates/incremental/packageDebugResources/compile-file-map.properties
  19. 2
    0
      android/build/intermediates/incremental/packageDebugResources/merger.xml
  20. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BluetoothService$ConnectedThread.class
  21. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BluetoothService.class
  22. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BluetoothServiceStateObserver.class
  23. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BuildConfig.class
  24. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/RNBluetoothEscposPrinterPackage.class
  25. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/RNBluetoothManagerModule$1.class
  26. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/RNBluetoothManagerModule.class
  27. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/RNBluetoothEscposPrinterModule$ColumnSplitedString.class
  28. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/RNBluetoothEscposPrinterModule.class
  29. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/command/sdk/Command.class
  30. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/command/sdk/PrintPicture.class
  31. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/command/sdk/PrinterCommand.class
  32. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/RNBluetoothTscPrinterModule.class
  33. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$BARCODETYPE.class
  34. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$BITMAP_MODE.class
  35. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$CODEPAGE.class
  36. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$DENSITY.class
  37. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$DIRECTION.class
  38. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$EEC.class
  39. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$ENABLE.class
  40. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$FONTMUL.class
  41. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$FONTTYPE.class
  42. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$FOOT.class
  43. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$READABLE.class
  44. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$ROTATION.class
  45. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$SPEED.class
  46. BIN
      android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand.class
  47. BIN
      android/build/intermediates/library_java_res/debug/res.jar
  48. 16
    0
      android/build/intermediates/library_manifest/debug/AndroidManifest.xml
  49. 1
    0
      android/build/intermediates/merged_manifests/debug/output.json
  50. BIN
      android/build/intermediates/packaged-classes/debug/classes.jar
  51. 1338
    0
      android/build/intermediates/res/symbol-table-with-package/debug/package-aware-r.txt
  52. BIN
      android/build/intermediates/runtime_library_classes/debug/classes.jar
  53. 1812
    0
      android/build/intermediates/symbols/debug/R.txt
  54. BIN
      android/build/intermediates/transforms/mergeJavaRes/debug/0.jar
  55. 1
    0
      android/build/intermediates/transforms/mergeJavaRes/debug/__content__.json
  56. 1
    0
      android/build/intermediates/transforms/mergeJniLibs/debug/__content__.json
  57. BIN
      android/build/outputs/aar/react-native-bluetooth-escpos-printer-debug.aar
  58. 53
    0
      android/build/outputs/logs/manifest-merger-debug-report.txt
  59. 170
    0
      android/react-native-bluetooth-escpos-printer.iml
  60. 10
    0
      android/src/main/AndroidManifest.xml
  61. 8
    0
      android/src/main/gen/cn/jystudio/bluetooth/BuildConfig.java
  62. 7
    0
      android/src/main/gen/cn/jystudio/bluetooth/Manifest.java
  63. 7
    0
      android/src/main/gen/cn/jystudio/bluetooth/R.java
  64. 345
    0
      android/src/main/java/cn/jystudio/bluetooth/BluetoothService.java
  65. 11
    0
      android/src/main/java/cn/jystudio/bluetooth/BluetoothServiceStateObserver.java
  66. 34
    0
      android/src/main/java/cn/jystudio/bluetooth/RNBluetoothEscposPrinterPackage.java
  67. 442
    0
      android/src/main/java/cn/jystudio/bluetooth/RNBluetoothManagerModule.java
  68. 492
    0
      android/src/main/java/cn/jystudio/bluetooth/escpos/RNBluetoothEscposPrinterModule.java
  69. 154
    0
      android/src/main/java/cn/jystudio/bluetooth/escpos/command/sdk/Command.java
  70. 281
    0
      android/src/main/java/cn/jystudio/bluetooth/escpos/command/sdk/PrintPicture.java
  71. 500
    0
      android/src/main/java/cn/jystudio/bluetooth/escpos/command/sdk/PrinterCommand.java
  72. 305
    0
      android/src/main/java/cn/jystudio/bluetooth/tsc/RNBluetoothTscPrinterModule.java
  73. 525
    0
      android/src/main/java/cn/jystudio/bluetooth/tsc/TscCommand.java
  74. 17
    0
      android/src/main/main1.iml
  75. BIN
      docs/ble_service_ids.png
  76. 146
    0
      index.js
  77. 11
    0
      ios/ColumnSplitedString.h
  78. 13
    0
      ios/ColumnSplitedString.m
  79. 19
    0
      ios/ImageUtils.h
  80. 277
    0
      ios/ImageUtils.m
  81. 25
    0
      ios/PrintColumnBleWriteDelegate.h
  82. 53
    0
      ios/PrintColumnBleWriteDelegate.m
  83. 19
    0
      ios/PrintImageBleWriteDelegate.h
  84. 61
    0
      ios/PrintImageBleWriteDelegate.m
  85. 16
    0
      ios/RNBluetoothEscposPrinter.h
  86. 626
    0
      ios/RNBluetoothEscposPrinter.m
  87. 444
    0
      ios/RNBluetoothEscposPrinter.xcodeproj/project.pbxproj
  88. 7
    0
      ios/RNBluetoothEscposPrinter.xcodeproj/project.xcworkspace/contents.xcworkspacedata
  89. 8
    0
      ios/RNBluetoothEscposPrinter.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
  90. BIN
      ios/RNBluetoothEscposPrinter.xcodeproj/project.xcworkspace/xcuserdata/januslo.xcuserdatad/UserInterfaceState.xcuserstate
  91. 14
    0
      ios/RNBluetoothEscposPrinter.xcodeproj/xcuserdata/januslo.xcuserdatad/xcschemes/xcschememanagement.plist
  92. 9
    0
      ios/RNBluetoothEscposPrinter.xcworkspace/contents.xcworkspacedata
  93. 29
    0
      ios/RNBluetoothManager.h
  94. 571
    0
      ios/RNBluetoothManager.m
  95. 13
    0
      ios/RNBluetoothTscPrinter.h
  96. 168
    0
      ios/RNBluetoothTscPrinter.m
  97. 72
    0
      ios/RNTscCommand.h
  98. 233
    0
      ios/RNTscCommand.m
  99. 1
    0
      ios/ZXingObjC-3.2.2/.gitattributes
  100. 0
    0
      ios/ZXingObjC-3.2.2/.npmignore

+ 1
- 0
.gitattributes View File

@@ -0,0 +1 @@
1
+*.pbxproj -text

+ 3
- 0
.npmignore View File

@@ -0,0 +1,3 @@
1
+# Created by .ignore support plugin (hsz.mobi)
2
+examples
3
+.idea

+ 21
- 0
LICENSE View File

@@ -0,0 +1,21 @@
1
+MIT License
2
+
3
+Copyright (c) 2018 januslo6211@icloud.com
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+SOFTWARE.

+ 485
- 0
README.md View File

@@ -0,0 +1,485 @@
1
+# react-native-bluetooch-escpos-printer
2
+
3
+React-Native plugin for the bluetooth ESC/POS & TSC printers.
4
+
5
+Any questions or bug please raise a issue.
6
+
7
+##Still under developement
8
+
9
+#May support Android /IOS
10
+
11
+[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/januslo/react-native-bluetooth-escpos-printer/master/LICENSE) [![npm version](https://badge.fury.io/js/react-native-bluetooth-escpos-printer.svg)](https://www.npmjs.com/package/react-native-bluetooth-escpos-printer)
12
+
13
+## Installation
14
+### Step 1 ###
15
+Install via NPM [Check In NPM](https://www.npmjs.com/package/react-native-bluetooth-escpos-printer)
16
+```bash
17
+npm install react-native-bluetooth-escpos-printer --save
18
+```
19
+
20
+Or install via github
21
+```bash
22
+npm install https://github.com/januslo/react-native-bluetooth-escpos-printer.git --save
23
+```
24
+
25
+### Step2 ###
26
+Link the plugin to your RN project
27
+```bash
28
+react-native link react-native-bluetooth-escpos-printer
29
+```
30
+
31
+Or you may need to link manually.
32
+//TODO: manually link guilds.
33
+
34
+### Step3 ###
35
+Refers to your JS files
36
+```javascript
37
+    import {BluetoothManager,BluetoothEscposPrinter,BluetoothTscPrinter} from 'react-native-bluetooth-escpos-printer';
38
+```
39
+
40
+## Usage and APIs ##
41
+
42
+### BluetoothManager ###
43
+BluetoothManager is the module that for Bluetooth service management, supports Bluetooth status check, enable/disable Bluetooth service,scan devices,connect/unpaire devices.
44
+
45
+* isBluetoothEnabled ==>
46
+async function, check whether Bluetooth service is enabled.
47
+//TODO: consider to return the the devices information already bound and paired here..
48
+
49
+```javascript
50
+     BluetoothManager.isBluetoothEnabled().then((enabled)=> {
51
+                alert(enabled) // enabled ==> true /false
52
+            }, (err)=> {
53
+                alert(err)
54
+            });
55
+```
56
+
57
+* enableBluetooth ==> ``` diff + ANDROID ONLY ```
58
+async function, enable the bluetooth service, returns the devices information already bound and paired.  ``` diff - IOS would just resovle with nil ```
59
+
60
+```javascript
61
+BluetoothManager.enableBluetooth().then((r)=>{
62
+                var paired = [];
63
+                if(r && r.length>0){
64
+                    for(var i=0;i<r.length;i++){
65
+                        try{
66
+                            paired.push(JSON.parse(r[i])); // NEED TO PARSE THE DEVICE INFORMATION
67
+                        }catch(e){
68
+                            //ignore
69
+                        }
70
+                    }
71
+                }
72
+                console.log(JSON.stringify(paired))
73
+            },(err)=>{
74
+               alert(err)
75
+           });
76
+```
77
+
78
+* disableBluetooth ==>  ``` diff + ANDROID ONLY ```
79
+async function ,disable the bluetooth service. ``` diff - IOS would just resovle with nil ```
80
+
81
+```javascript
82
+BluetoothManager.disableBluetooth().then(()=>{
83
+            // do something.
84
+          },(err)=>{alert(err)});
85
+```
86
+
87
+* scanDevices ==>
88
+async function , scans the bluetooth devices, returns devices found and pared after scan finish. Event [BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED] would be emitted with devices bound; event [BluetoothManager.EVENT_DEVICE_FOUND] would be emitted (many time) as long as new devices found.
89
+
90
+samples with events:
91
+```javascript
92
+ DeviceEventEmitter.addListener(
93
+            BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED, (rsp)=> {
94
+                this._deviceAlreadPaired(rsp) // rsp.devices would returns the paired devices array in JSON string.
95
+            });
96
+        DeviceEventEmitter.addListener(
97
+            BluetoothManager.EVENT_DEVICE_FOUND, (rsp)=> {
98
+                this._deviceFoundEvent(rsp) // rsp.devices would returns the found device object in JSON string
99
+            });
100
+```
101
+
102
+samples with scanDevices function
103
+```javascript
104
+BluetoothManager.scanDevices()
105
+            .then((s)=> {
106
+                var ss = JSON.parse(s);//JSON string
107
+                this.setState({
108
+                    pairedDs: this.state.pairedDs.cloneWithRows(ss.paired || []),
109
+                    foundDs: this.state.foundDs.cloneWithRows(ss.found || []),
110
+                    loading: false
111
+                }, ()=> {
112
+                    this.paired = ss.paired || [];
113
+                    this.found = ss.found || [];
114
+                });
115
+            }, (er)=> {
116
+                this.setState({
117
+                    loading: false
118
+                })
119
+                alert('error' + JSON.stringify(er));
120
+            });
121
+```
122
+
123
+* connect ==>
124
+async function, connect the specified devices, if not bound, bound dailog promps.
125
+
126
+```javascript
127
+
128
+    BluetoothManager.connect(rowData.address) // the device address scanned.
129
+     .then((s)=>{
130
+       this.setState({
131
+        loading:false,
132
+        boundAddress:rowData.address
133
+    })
134
+    },(e)=>{
135
+       this.setState({
136
+         loading:false
137
+     })
138
+       alert(e);
139
+    })
140
+
141
+```
142
+
143
+* unpaire ==>
144
+async function, disconnect and unpaire the specified devices
145
+
146
+```javascript
147
+     BluetoothManager.connect(rowData.address)
148
+     .then((s)=>{
149
+        //success here
150
+     },
151
+     (err)=>{
152
+        //error here
153
+     })
154
+```
155
+
156
+* Events of BluetoothManager module
157
+
158
+| Name/KEY | DESCRIPTION |
159
+|---|---|
160
+| EVENT_DEVICE_ALREADY_PAIRED | Emits the devices array already paired |
161
+| EVENT_DEVICE_DISCOVER_DONE | Emits when the scan done |
162
+| EVENT_DEVICE_FOUND | Emits when device found during scan |
163
+| EVENT_CONNECTION_LOST | Emits when device connection lost |
164
+| EVENT_UNABLE_CONNECT | Emits when error occurs while trying to connect device |
165
+| EVENT_CONNECTED | Emits when device connected |
166
+| EVENT_BLUETOOTH_NOT_SUPPORT | Emits when device not support bluetooth(android only) |
167
+
168
+### BluetoothTscPrinter ###
169
+The printer for label printing.
170
+
171
+* printLabel ==>
172
+async function the perform label print action.
173
+
174
+```javascript
175
+BluetoothTscPrinter.printLable(options)
176
+.then(()=>{
177
+    //success
178
+},
179
+(err)=>{
180
+    //error
181
+})
182
+
183
+```
184
+
185
+#### Options of printLabel( ) function: (JSON object) ####
186
+
187
+##### width #####
188
+    label with , the real size of the label, matured by mm usualy.
189
+##### height #####
190
+    label height, the real size of the label, matured by mm usualy.
191
+##### direction #####
192
+    the printing direction, constants of BluetoothTscPrinter.DIRECTION, values BluetoothTscPrinter.DIRECTION.FORWARD/BluetoothTscPrinter.DIRECTION.BACKWARD (0/1)
193
+##### gap #####
194
+    the gap between 2 labels, matured by mm usualy.
195
+##### reference #####
196
+    the "zero" position of the label, values [x,y], default [0,0]
197
+##### tear #####
198
+    switch of the paper cut, constants of BluetoothTscPrinter.TEAR, values ON/OFF (string 'ON','OFF')
199
+##### sound #####
200
+    switch of the bee sound, values 0/1
201
+##### text #####
202
+    the collection of texts to print, contains following fields as the configuration:
203
+        * text
204
+            the text string,
205
+        * x
206
+            the text print start position-x
207
+        * y
208
+            the text print start position-y
209
+        * fonttype
210
+            the font type of the text, constanst of BluetoothTscPrinter.FONTTYPE,refereces as table:
211
+                | CONSTANTS | VALUE   |
212
+                |---|---|
213
+                |FONT_1| "1"|
214
+                |FONT_2| "2"|
215
+                |FONT_3| "3"|
216
+                |FONT_4| "4"|
217
+                |FONT_5| "5"|
218
+                |FONT_6| "6"|
219
+                |FONT_7| "7"|
220
+                |FONT_8|"8"|
221
+                |SIMPLIFIED_CHINESE| "TSS24.BF2"|
222
+                |TRADITIONAL_CHINESE| "TST24.BF2"|
223
+                |KOREAN| "K"|
224
+        * rotation
225
+            the rotation of the text, constants of the BluetoothTscPrinter.ROTATION, referces as table:
226
+                   | CONSTANTS | VALUE   |
227
+                   |---|---|
228
+                   |ROTATION_0| 0|
229
+                   |ROTATION_90| 90|
230
+                   |ROTATION_180| 180|
231
+                   |ROTATION_270| 270|
232
+        * xscal
233
+            the scal in x,
234
+        * yscal
235
+            the scal in y, xscal/yscal is the constants of the BluetoothTscPrinter.FONTMUL, referces as table:
236
+             | CONSTANTS | VALUE   |
237
+             |---|---|
238
+             |MUL_1| 1|
239
+             |MUL_2| 2|
240
+             |MUL_3| 3|
241
+             |MUL_4| 4|
242
+             |MUL_5| 5|
243
+             |MUL_6| 6|
244
+             |MUL_7| 7|
245
+             |MUL_8| 8|
246
+             |MUL_9| 9|
247
+             |MUL_10: 10|
248
+
249
+##### qrcode #####
250
+    the collection of qrcodes to print, contains following fields as the configuration:
251
+        * code
252
+            the qrcode content string.
253
+        * x
254
+            the print start position at x
255
+        * y
256
+            the print start position at y
257
+        * level
258
+            the error correction level, constants of BluetoothTscPrinter.EEC, referces as tables:
259
+            | CONSTANTS | VALUE   |
260
+            |---|---|
261
+            |LEVEL_L|"L"|
262
+            |LEVEL_M| "M"|
263
+            |LEVEL_Q| "Q"|
264
+            |LEVEL_H| "H"|
265
+        * width
266
+            the qrcode size (width X width),since the qrcode are squre normally, so we just config the width.
267
+
268
+        * rotation
269
+            rationtion. the same as text object.
270
+
271
+##### barcode #####
272
+    the collection of barcode to print, contains foloowing fields as configuration
273
+      * x
274
+        the print start position of x,
275
+      * y
276
+        the print start position of y,
277
+      * type
278
+        the barcode type, constants of BluetoothTscPrinter, definition as table:
279
+        | CONSTRANTS | VALUE |
280
+        |---|---|
281
+        | CODE128 | "128" |
282
+        | CODE128M | "128M" |
283
+        | EAN128 | "EAN128" |
284
+        | ITF25 | "25" |
285
+        | ITF25C | "25C" |
286
+        | CODE39 | "39" |
287
+        | CODE39C | "39C" |
288
+        | CODE39S | "39S" |
289
+        | CODE93 | "93" |
290
+        | EAN13 | "EAN13" |
291
+        | EAN13_2 | "EAN13+2" |
292
+        | EAN13_5 | "EAN13+5" |
293
+        | EAN8 | "EAN8" |
294
+        | EAN8_2 | "EAN8+2" |
295
+        | EAN8_5 | "EAN8+5" |
296
+        | CODABAR | "CODA" |
297
+        | POST | "POST" |
298
+        | UPCA | "EAN13" |
299
+        | UPCA_2 | "EAN13+2" |
300
+        | UPCA_5 | "EAN13+5" |
301
+        | UPCE | "EAN13" |
302
+        | UPCE_2 | "EAN13+2" |
303
+        | UPCE_5 | "EAN13+5" |
304
+        | CPOST | "CPOST" |
305
+        | MSI | "MSI" |
306
+        | MSIC | "MSIC" |
307
+        | PLESSEY | "PLESSEY" |
308
+        | ITF14 | "ITF14" |
309
+        | EAN14 | "EAN14" |
310
+
311
+     * height
312
+      the height of the barcode.
313
+     * readable
314
+      the hunman readable factor, 0-not readable, 1-readable.
315
+     * rotation
316
+      rotation, the same as text.
317
+     * code
318
+      the code to generate and print, should follow the restriction of the code type using.
319
+     * wide
320
+     the wide bar lines width (dot)
321
+     * narrow
322
+     the narrow bar line widht (dot)
323
+
324
+##### image #####
325
+    the collection of the image to print.
326
+     * x
327
+     the print start position x.
328
+     * y
329
+     the print start position y.
330
+     * mode
331
+     the bitmap mode of print, constants of BluetoothTscPrinter.BITMAP_MODE, valuse OVERWRITE(0),OR(1),XOR(2).
332
+     * width
333
+     the width of the image to print. (height will be calculated by image ratio)
334
+     * image
335
+     the base64 encoded image data(without schema)
336
+
337
+#### demo of printLabel() options ####
338
+```javascript
339
+let options = {
340
+   width: 40,
341
+   height: 30,
342
+   gap: 20,
343
+   direction: BluetoothTscPrinter.DIRECTION.FORWARD,
344
+   reference: [0, 0],
345
+   tear: BluetoothTscPrinter.TEAR.ON,
346
+   sound: 0,
347
+   text: [{
348
+       text: 'I am a testing txt',
349
+       x: 20,
350
+       y: 0,
351
+       fonttype: BluetoothTscPrinter.FONTTYPE.SIMPLIFIED_CHINESE,
352
+       rotation: BluetoothTscPrinter.ROTATION.ROTATION_0,
353
+       xscal:BluetoothTscPrinter.FONTMUL.MUL_1,
354
+       yscal: BluetoothTscPrinter.FONTMUL.MUL_1
355
+   },{
356
+       text: '你在说什么呢?',
357
+       x: 20,
358
+       y: 50,
359
+       fonttype: BluetoothTscPrinter.FONTTYPE.SIMPLIFIED_CHINESE,
360
+       rotation: BluetoothTscPrinter.ROTATION.ROTATION_0,
361
+       xscal:BluetoothTscPrinter.FONTMUL.MUL_1,
362
+       yscal: BluetoothTscPrinter.FONTMUL.MUL_1
363
+   }],
364
+   qrcode: [{x: 20, y: 96, level: BluetoothTscPrinter.EEC.LEVEL_L, width: 3, rotation: BluetoothTscPrinter.ROTATION.ROTATION_0, code: 'show me the money'}],
365
+   barcode: [{x: 120, y:96, type: BluetoothTscPrinter.BARCODETYPE.CODE128, height: 40, readable: 1, rotation: BluetoothTscPrinter.ROTATION.ROTATION_0, code: '1234567890'}],
366
+   image: [{x: 160, y: 160, mode: BluetoothTscPrinter.BITMAP_MODE.OVERWRITE,width: 60,image: base64Image}]
367
+}
368
+```
369
+### BluetoothEscposPrinter ###
370
+  the printer for receipt printing, following ESC/POS command.
371
+
372
+#### printerInit() ####
373
+  init the printer.
374
+
375
+#### printAndFeed(int feed) ####
376
+  printer the buffer data and feed (feed lines).
377
+
378
+#### printerLeftSpace(int sp) ####
379
+  set the printer left spaces.
380
+
381
+#### printerLineSpace(int sp) ####
382
+  set the spaces between lines.
383
+
384
+#### printerUnderLine(int line) ####
385
+  set the under line of the text, @param line --  0-off,1-on,2-deeper
386
+
387
+#### printerAlign(int align) ####
388
+  set the printer alignment, constansts: BluetoothEscposPrinter.ALIGN.LEFT/BluetoothEscposPrinter.ALIGN.CENTER/BluetoothEscposPrinter.ALIGN.RIGHT.
389
+  Not works ant printPic() method.
390
+
391
+#### printText(String text, ReadableMap options) ####
392
+  print text, options as following:
393
+  * encoding => text encoding,default GBK.
394
+  * codepage => codepage using, default 0.
395
+  * widthtimes => text font mul times in width, default 0.
396
+  * heigthTimes => text font mul times in height, default 0.
397
+  * fonttype => text font type, default 0.
398
+
399
+#### printColumn(ReadableArray columnWidths,ReadableArray columnAligns,ReadableArray columnTexts,ReadableMap options) ####
400
+  print texts in column, Parameters as following:
401
+  * columnWidths => int arrays, configs the width of each column, calculate by english character length. ex:the width of "abcdef" is 5 ,the width of "中文" is 4.
402
+  * columnAligns => arrays, alignment of each column, values is the same of printerAlign().
403
+  * columnTexts => arrays, the texts of each colunm to print.
404
+  * options => text print config options, the same of printText() options.
405
+
406
+#### setWidth(int width) ####
407
+  sets the widht of the printer.
408
+
409
+#### printPic(String base64encodeStr,ReadableMap options) ####
410
+  prints the image which encoded by base64, without schema.
411
+  * options: contains the params that may use in printing pic: "with":the pic with,basic on devices width(dots,58mm-384); "left":the left padding of the pic,for the printing position adjustment.
412
+
413
+#### setfTest() ####
414
+  prints the selft test.
415
+
416
+#### rotate() ####
417
+  set the rotate of the line.
418
+
419
+#### setBlob(int weight) ####
420
+  set blob of the line.
421
+
422
+#### printQRCode(String content, int size, int correctionLevel) ####
423
+  prints the qrcode.
424
+
425
+#### printBarCode(String str,int nType, int nWidthX, int nHeight, int nHriFontType, int nHriFontPosition) ####
426
+  prints the barcode.
427
+
428
+### Demos of printing a receipt ###
429
+```javascript
430
+await BluetoothEscposPrinter.printerAlign(BluetoothEscposPrinter.ALIGN.CENTER);
431
+await BluetoothEscposPrinter.setBlob(0);
432
+await  BluetoothEscposPrinter.printText("广州俊烨\n\r",{
433
+  encoding:'GBK',
434
+  codepage:0,
435
+  widthtimes:3,
436
+  heigthtimes:3,
437
+  fonttype:1
438
+});
439
+await BluetoothEscposPrinter.setBlob(0);
440
+await  BluetoothEscposPrinter.printText("销售单\n\r",{
441
+  encoding:'GBK',
442
+  codepage:0,
443
+  widthtimes:0,
444
+  heigthtimes:0,
445
+  fonttype:1
446
+});
447
+await BluetoothEscposPrinter.printerAlign(BluetoothEscposPrinter.ALIGN.LEFT);
448
+await  BluetoothEscposPrinter.printText("客户:零售客户\n\r",{});
449
+await  BluetoothEscposPrinter.printText("单号:xsd201909210000001\n\r",{});
450
+await  BluetoothEscposPrinter.printText("日期:"+(dateFormat(new Date(), "yyyy-mm-dd h:MM:ss"))+"\n\r",{});
451
+await  BluetoothEscposPrinter.printText("销售员:18664896621\n\r",{});
452
+await  BluetoothEscposPrinter.printText("--------------------------------\n\r",{});
453
+let columnWidths = [12,6,6,8];
454
+await BluetoothEscposPrinter.printColumn(columnWidths,
455
+  [BluetoothEscposPrinter.ALIGN.LEFT,BluetoothEscposPrinter.ALIGN.CENTER,BluetoothEscposPrinter.ALIGN.CENTER,BluetoothEscposPrinter.ALIGN.RIGHT],
456
+  ["商品",'数量','单价','金额'],{});
457
+await BluetoothEscposPrinter.printColumn(columnWidths,
458
+  [BluetoothEscposPrinter.ALIGN.LEFT,BluetoothEscposPrinter.ALIGN.LEFT,BluetoothEscposPrinter.ALIGN.CENTER,BluetoothEscposPrinter.ALIGN.RIGHT],
459
+  ["React-Native定制开发我是比较长的位置你稍微看看是不是这样?",'1','32000','32000'],{});
460
+    await  BluetoothEscposPrinter.printText("\n\r",{});
461
+  await BluetoothEscposPrinter.printColumn(columnWidths,
462
+  [BluetoothEscposPrinter.ALIGN.LEFT,BluetoothEscposPrinter.ALIGN.LEFT,BluetoothEscposPrinter.ALIGN.CENTER,BluetoothEscposPrinter.ALIGN.RIGHT],
463
+  ["React-Native定制开发我是比较长的位置你稍微看看是不是这样?",'1','32000','32000'],{});
464
+await  BluetoothEscposPrinter.printText("\n\r",{});
465
+await  BluetoothEscposPrinter.printText("--------------------------------\n\r",{});
466
+await BluetoothEscposPrinter.printColumn([12,8,12],
467
+  [BluetoothEscposPrinter.ALIGN.LEFT,BluetoothEscposPrinter.ALIGN.LEFT,BluetoothEscposPrinter.ALIGN.RIGHT],
468
+  ["合计",'2','64000'],{});
469
+await  BluetoothEscposPrinter.printText("\n\r",{});
470
+await  BluetoothEscposPrinter.printText("折扣率:100%\n\r",{});
471
+await  BluetoothEscposPrinter.printText("折扣后应收:64000.00\n\r",{});
472
+await  BluetoothEscposPrinter.printText("会员卡支付:0.00\n\r",{});
473
+await  BluetoothEscposPrinter.printText("积分抵扣:0.00\n\r",{});
474
+await  BluetoothEscposPrinter.printText("支付金额:64000.00\n\r",{});
475
+await  BluetoothEscposPrinter.printText("结算账户:现金账户\n\r",{});
476
+await  BluetoothEscposPrinter.printText("备注:无\n\r",{});
477
+await  BluetoothEscposPrinter.printText("快递单号:无\n\r",{});
478
+await  BluetoothEscposPrinter.printText("打印时间:"+(dateFormat(new Date(), "yyyy-mm-dd h:MM:ss"))+"\n\r",{});
479
+await  BluetoothEscposPrinter.printText("--------------------------------\n\r",{});
480
+await  BluetoothEscposPrinter.printText("电话:\n\r",{});
481
+await  BluetoothEscposPrinter.printText("地址:\n\r\n\r",{});
482
+await BluetoothEscposPrinter.printerAlign(BluetoothEscposPrinter.ALIGN.CENTER);
483
+await  BluetoothEscposPrinter.printText("欢迎下次光临\n\r\n\r\n\r",{});
484
+await BluetoothEscposPrinter.printerAlign(BluetoothEscposPrinter.ALIGN.LEFT);
485
+```

+ 60
- 0
android/build.gradle View File

@@ -0,0 +1,60 @@
1
+buildscript {
2
+    repositories {
3
+        jcenter { url "http://jcenter.bintray.com/" }
4
+        maven {url "http://repo.spring.io/plugins-release/"}
5
+        mavenCentral()
6
+        maven {
7
+            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
8
+            url "$rootDir/../node_modules/react-native/android"
9
+        }
10
+        maven {
11
+            url 'https://maven.google.com'
12
+        }
13
+    }
14
+
15
+    dependencies {
16
+        classpath 'com.android.tools.build:gradle:3.1.4'
17
+    }
18
+}
19
+
20
+apply plugin: 'com.android.library'
21
+
22
+android {
23
+    compileSdkVersion 27
24
+    buildToolsVersion "27.0.3"
25
+
26
+    defaultConfig {
27
+        minSdkVersion 16
28
+        targetSdkVersion 24
29
+        versionCode 1
30
+        versionName "1.0"
31
+    }
32
+    lintOptions {
33
+        abortOnError false
34
+    }
35
+    sourceSets {
36
+        main {
37
+            aidl.srcDirs = ['src/main/java']
38
+        }
39
+    }
40
+}
41
+
42
+repositories {
43
+    jcenter { url "http://jcenter.bintray.com/" }
44
+    maven {url "http://repo.spring.io/plugins-release/"}
45
+    mavenCentral()
46
+    maven {
47
+        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
48
+        url "$rootDir/../node_modules/react-native/android"
49
+    }
50
+    maven {
51
+        url 'https://maven.google.com'
52
+    }
53
+}
54
+
55
+dependencies {
56
+    compile fileTree(dir: 'libs', include: ['*.jar'])
57
+    implementation 'com.facebook.react:react-native:+'  // From node_modules
58
+    implementation group: 'com.android.support', name: 'support-v4', version: '27.0.0'
59
+    implementation "com.google.zxing:core:3.3.0"
60
+}

+ 13
- 0
android/build/generated/source/buildConfig/debug/cn/jystudio/bluetooth/BuildConfig.java View File

@@ -0,0 +1,13 @@
1
+/**
2
+ * Automatically generated file. DO NOT MODIFY
3
+ */
4
+package cn.jystudio.bluetooth;
5
+
6
+public final class BuildConfig {
7
+  public static final boolean DEBUG = Boolean.parseBoolean("true");
8
+  public static final String APPLICATION_ID = "cn.jystudio.bluetooth";
9
+  public static final String BUILD_TYPE = "debug";
10
+  public static final String FLAVOR = "";
11
+  public static final int VERSION_CODE = 1;
12
+  public static final String VERSION_NAME = "1.0";
13
+}

+ 16
- 0
android/build/intermediates/aapt_friendly_merged_manifests/debug/aapt/AndroidManifest.xml View File

@@ -0,0 +1,16 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+    package="cn.jystudio.bluetooth"
4
+    android:versionCode="1"
5
+    android:versionName="1.0" >
6
+
7
+    <uses-sdk
8
+        android:minSdkVersion="16"
9
+        android:targetSdkVersion="24" />
10
+
11
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
12
+    <uses-permission android:name="android.permission.BLUETOOTH" />
13
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
14
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
15
+
16
+</manifest>

+ 1
- 0
android/build/intermediates/aapt_friendly_merged_manifests/debug/aapt/output.json View File

@@ -0,0 +1 @@
1
+[{"outputType":{"type":"AAPT_FRIENDLY_MERGED_MANIFESTS"},"apkData":{"type":"MAIN","splits":[],"versionCode":1,"versionName":"1.0","enabled":true,"outputFile":"react-native-bluetooth-escpos-printer-debug.aar","fullName":"debug","baseName":"debug"},"path":"AndroidManifest.xml","properties":{"packageId":"cn.jystudio.bluetooth","split":""}}]

+ 1
- 0
android/build/intermediates/annotation_processor_list/debug/annotationProcessors.json View File

@@ -0,0 +1 @@
1
+{}

+ 0
- 0
android/build/intermediates/annotations_typedef_file/debug/extractDebugAnnotations/typedefs.txt View File


BIN
android/build/intermediates/compile_library_classes/debug/classes.jar View File


BIN
android/build/intermediates/compile_only_not_namespaced_r_class_jar/debug/generateDebugRFile/R.jar View File


BIN
android/build/intermediates/incremental/debug-mergeJavaRes/merge-state View File


BIN
android/build/intermediates/incremental/debug-mergeJniLibs/merge-state View File


+ 2
- 0
android/build/intermediates/incremental/mergeDebugJniLibFolders/merger.xml View File

@@ -0,0 +1,2 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<merger version="3"><dataSet config="main" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/jniLibs"/></dataSet><dataSet config="debug" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/debug/jniLibs"/></dataSet></merger>

+ 2
- 0
android/build/intermediates/incremental/mergeDebugShaders/merger.xml View File

@@ -0,0 +1,2 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<merger version="3"><dataSet config="main" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/shaders"/></dataSet><dataSet config="debug" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/debug/shaders"/></dataSet></merger>

+ 2
- 0
android/build/intermediates/incremental/packageDebugAssets/merger.xml View File

@@ -0,0 +1,2 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<merger version="3"><dataSet config="main" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/assets"/><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/build/intermediates/shader_assets/debug/compileDebugShaders/out"/></dataSet><dataSet config="debug" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/debug/assets"/></dataSet></merger>

+ 1
- 0
android/build/intermediates/incremental/packageDebugResources/compile-file-map.properties View File

@@ -0,0 +1 @@
1
+#Wed Jan 29 16:49:37 MYT 2020

+ 2
- 0
android/build/intermediates/incremental/packageDebugResources/merger.xml View File

@@ -0,0 +1,2 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<merger version="3"><dataSet aapt-namespace="http://schemas.android.com/apk/res-auto" config="main$Generated" generated="true" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/res"/><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/build/generated/res/rs/debug"/><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/build/generated/res/resValues/debug"/></dataSet><dataSet aapt-namespace="http://schemas.android.com/apk/res-auto" config="main" generated-set="main$Generated" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/res"/><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/build/generated/res/rs/debug"/><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/build/generated/res/resValues/debug"/></dataSet><dataSet aapt-namespace="http://schemas.android.com/apk/res-auto" config="debug$Generated" generated="true" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/debug/res"/></dataSet><dataSet aapt-namespace="http://schemas.android.com/apk/res-auto" config="debug" generated-set="debug$Generated" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="/Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/debug/res"/></dataSet><mergedItems/></merger>

BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BluetoothService$ConnectedThread.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BluetoothService.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BluetoothServiceStateObserver.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/BuildConfig.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/RNBluetoothEscposPrinterPackage.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/RNBluetoothManagerModule$1.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/RNBluetoothManagerModule.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/RNBluetoothEscposPrinterModule$ColumnSplitedString.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/RNBluetoothEscposPrinterModule.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/command/sdk/Command.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/command/sdk/PrintPicture.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/escpos/command/sdk/PrinterCommand.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/RNBluetoothTscPrinterModule.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$BARCODETYPE.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$BITMAP_MODE.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$CODEPAGE.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$DENSITY.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$DIRECTION.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$EEC.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$ENABLE.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$FONTMUL.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$FONTTYPE.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$FOOT.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$READABLE.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$ROTATION.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand$SPEED.class View File


BIN
android/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/cn/jystudio/bluetooth/tsc/TscCommand.class View File


BIN
android/build/intermediates/library_java_res/debug/res.jar View File


+ 16
- 0
android/build/intermediates/library_manifest/debug/AndroidManifest.xml View File

@@ -0,0 +1,16 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+    package="cn.jystudio.bluetooth"
4
+    android:versionCode="1"
5
+    android:versionName="1.0" >
6
+
7
+    <uses-sdk
8
+        android:minSdkVersion="16"
9
+        android:targetSdkVersion="24" />
10
+
11
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
12
+    <uses-permission android:name="android.permission.BLUETOOTH" />
13
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
14
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
15
+
16
+</manifest>

+ 1
- 0
android/build/intermediates/merged_manifests/debug/output.json View File

@@ -0,0 +1 @@
1
+[{"outputType":{"type":"MERGED_MANIFESTS"},"apkData":{"type":"MAIN","splits":[],"versionCode":1,"versionName":"1.0","enabled":true,"outputFile":"react-native-bluetooth-escpos-printer-debug.aar","fullName":"debug","baseName":"debug"},"path":"../../library_manifest/debug/AndroidManifest.xml","properties":{"packageId":"cn.jystudio.bluetooth","split":""}}]

BIN
android/build/intermediates/packaged-classes/debug/classes.jar View File


+ 1338
- 0
android/build/intermediates/res/symbol-table-with-package/debug/package-aware-r.txt
File diff suppressed because it is too large
View File


BIN
android/build/intermediates/runtime_library_classes/debug/classes.jar View File


+ 1812
- 0
android/build/intermediates/symbols/debug/R.txt
File diff suppressed because it is too large
View File


BIN
android/build/intermediates/transforms/mergeJavaRes/debug/0.jar View File


+ 1
- 0
android/build/intermediates/transforms/mergeJavaRes/debug/__content__.json View File

@@ -0,0 +1 @@
1
+[{"name":"resources","index":0,"scopes":["PROJECT"],"types":["RESOURCES"],"format":"JAR","present":true}]

+ 1
- 0
android/build/intermediates/transforms/mergeJniLibs/debug/__content__.json View File

@@ -0,0 +1 @@
1
+[{"name":"resources","index":0,"scopes":["PROJECT"],"types":["NATIVE_LIBS"],"format":"DIRECTORY","present":false}]

BIN
android/build/outputs/aar/react-native-bluetooth-escpos-printer-debug.aar View File


+ 53
- 0
android/build/outputs/logs/manifest-merger-debug-report.txt View File

@@ -0,0 +1,53 @@
1
+-- Merging decision tree log ---
2
+manifest
3
+ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
4
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
5
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
6
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
7
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
8
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
9
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
10
+	package
11
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:3:11-42
12
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
13
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
14
+	android:versionName
15
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
16
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
17
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
18
+	android:versionCode
19
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
20
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:1-9:12
21
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
22
+	xmlns:android
23
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:2:11-69
24
+uses-permission#android.permission.BLUETOOTH_ADMIN
25
+ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:4:5-74
26
+	android:name
27
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:4:22-71
28
+uses-permission#android.permission.BLUETOOTH
29
+ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:5:5-68
30
+	android:name
31
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:5:22-65
32
+uses-permission#android.permission.ACCESS_COARSE_LOCATION
33
+ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:6:5-80
34
+	android:name
35
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:6:22-78
36
+uses-permission#android.permission.ACCESS_FINE_LOCATION
37
+ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:7:5-78
38
+	android:name
39
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml:7:22-76
40
+uses-sdk
41
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml reason: use-sdk injection requested
42
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
43
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
44
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
45
+INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
46
+	android:targetSdkVersion
47
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
48
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
49
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
50
+	android:minSdkVersion
51
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
52
+		ADDED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml
53
+		INJECTED from /Users/munirishak/Documents/gitea/pahang-fa/pahang-fe/node_modules/react-native-bluetooth-escpos-printer/android/src/main/AndroidManifest.xml

+ 170
- 0
android/react-native-bluetooth-escpos-printer.iml View File

@@ -0,0 +1,170 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<module external.linked.project.id=":react-native-bluetooth-escpos-printer" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/../../../android" external.system.id="GRADLE" type="JAVA_MODULE" version="4">
3
+  <component name="FacetManager">
4
+    <facet type="android-gradle" name="Android-Gradle">
5
+      <configuration>
6
+        <option name="GRADLE_PROJECT_PATH" value=":react-native-bluetooth-escpos-printer" />
7
+      </configuration>
8
+    </facet>
9
+    <facet type="android" name="Android">
10
+      <configuration>
11
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />
12
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
13
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
14
+        <afterSyncTasks>
15
+          <task>generateDebugSources</task>
16
+        </afterSyncTasks>
17
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />
18
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
19
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
20
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/build/generated/res/resValues/debug" />
21
+        <option name="TEST_RES_FOLDERS_RELATIVE_PATH" value="" />
22
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
23
+        <option name="PROJECT_TYPE" value="1" />
24
+      </configuration>
25
+    </facet>
26
+  </component>
27
+  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7">
28
+    <output url="file://$MODULE_DIR$/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes" />
29
+    <output-test url="file://$MODULE_DIR$/build/intermediates/javac/debugUnitTest/compileDebugUnitTestJavaWithJavac/classes" />
30
+    <exclude-output />
31
+    <content url="file://$MODULE_DIR$">
32
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/debug" isTestSource="false" generated="true" />
33
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debug/compileDebugAidl/out" isTestSource="false" generated="true" />
34
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
35
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debug/compileDebugRenderscript/out" isTestSource="false" generated="true" />
36
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
37
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
38
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/androidTest/debug" isTestSource="true" generated="true" />
39
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debugAndroidTest/compileDebugAndroidTestAidl/out" isTestSource="true" generated="true" />
40
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
41
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debugAndroidTest/compileDebugAndroidTestRenderscript/out" isTestSource="true" generated="true" />
42
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
43
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
44
+      <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/test/debug" isTestSource="true" generated="true" />
45
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
46
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
47
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
48
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
49
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
50
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
51
+      <sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" />
52
+      <sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
53
+      <sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
54
+      <sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
55
+      <sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
56
+      <sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
57
+      <sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
58
+      <sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" />
59
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/res" type="java-test-resource" />
60
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/resources" type="java-test-resource" />
61
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/assets" type="java-test-resource" />
62
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/aidl" isTestSource="true" />
63
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/java" isTestSource="true" />
64
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/rs" isTestSource="true" />
65
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/shaders" isTestSource="true" />
66
+      <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
67
+      <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
68
+      <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
69
+      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
70
+      <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
71
+      <sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
72
+      <sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
73
+      <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
74
+      <sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
75
+      <sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
76
+      <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
77
+      <sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
78
+      <sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
79
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
80
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
81
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
82
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
83
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
84
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
85
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
86
+      <excludeFolder url="file://$MODULE_DIR$/build/generated/not_namespaced_r_class_sources" />
87
+      <excludeFolder url="file://$MODULE_DIR$/build/generated/source/r" />
88
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/aapt_friendly_merged_manifests" />
89
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/annotation_processor_list" />
90
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/annotations_typedef_file" />
91
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/annotations_zip" />
92
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/check_manifest_result" />
93
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/compile_library_classes" />
94
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/compile_only_not_namespaced_r_class_jar" />
95
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/consumer_proguard_file" />
96
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
97
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/intermediate-jars" />
98
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javac" />
99
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/library_and_local_jars_jni" />
100
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/library_assets" />
101
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/library_java_res" />
102
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/library_manifest" />
103
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint_publish_jar" />
104
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/merged_jni_libs" />
105
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/merged_manifests" />
106
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/merged_shaders" />
107
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/packaged-classes" />
108
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/packaged_res" />
109
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/public_res" />
110
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
111
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/runtime_library_classes" />
112
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/shader_assets" />
113
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
114
+      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" />
115
+      <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
116
+      <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
117
+    </content>
118
+    <orderEntry type="jdk" jdkName="Android API 27 Platform" jdkType="Android SDK" />
119
+    <orderEntry type="sourceFolder" forTests="false" />
120
+    <orderEntry type="library" name="Gradle: com.squareup.okhttp3:okhttp-urlconnection:3.12.1@jar" level="project" />
121
+    <orderEntry type="library" name="Gradle: com.facebook.react:react-native:0.61.5@aar" level="project" />
122
+    <orderEntry type="library" name="Gradle: androidx.drawerlayout:drawerlayout:1.0.0@aar" level="project" />
123
+    <orderEntry type="library" name="Gradle: androidx.documentfile:documentfile:1.0.0@aar" level="project" />
124
+    <orderEntry type="library" name="Gradle: androidx.localbroadcastmanager:localbroadcastmanager:1.0.0@aar" level="project" />
125
+    <orderEntry type="library" name="Gradle: com.squareup.okhttp3:okhttp:3.12.1@jar" level="project" />
126
+    <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-runtime:2.0.0@aar" level="project" />
127
+    <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata-core:2.0.0@aar" level="project" />
128
+    <orderEntry type="library" name="Gradle: com.google.zxing:core:3.3.0@jar" level="project" />
129
+    <orderEntry type="library" name="Gradle: androidx.cursoradapter:cursoradapter:1.0.0@aar" level="project" />
130
+    <orderEntry type="library" name="Gradle: androidx.customview:customview:1.0.0@aar" level="project" />
131
+    <orderEntry type="library" name="Gradle: androidx.asynclayoutinflater:asynclayoutinflater:1.0.0@aar" level="project" />
132
+    <orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable:1.0.1@aar" level="project" />
133
+    <orderEntry type="library" name="Gradle: androidx.interpolator:interpolator:1.0.0@aar" level="project" />
134
+    <orderEntry type="library" name="Gradle: androidx.fragment:fragment:1.0.0@aar" level="project" />
135
+    <orderEntry type="library" name="Gradle: javax.inject:javax.inject:1@jar" level="project" />
136
+    <orderEntry type="library" name="Gradle: androidx.slidingpanelayout:slidingpanelayout:1.0.0@aar" level="project" />
137
+    <orderEntry type="library" name="Gradle: androidx.media:media:1.0.0@aar" level="project" />
138
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:nativeimagefilters:2.0.0@aar" level="project" />
139
+    <orderEntry type="library" name="Gradle: com.facebook.soloader:soloader:0.6.0@aar" level="project" />
140
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:fresco:2.0.0@aar" level="project" />
141
+    <orderEntry type="library" name="Gradle: androidx.coordinatorlayout:coordinatorlayout:1.0.0@aar" level="project" />
142
+    <orderEntry type="library" name="Gradle: com.google.code.findbugs:jsr305:3.0.2@jar" level="project" />
143
+    <orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-v4:1.0.0@aar" level="project" />
144
+    <orderEntry type="library" name="Gradle: androidx.arch.core:core-runtime:2.0.0@aar" level="project" />
145
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:imagepipeline-base:2.0.0@aar" level="project" />
146
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:imagepipeline:2.0.0@aar" level="project" />
147
+    <orderEntry type="library" name="Gradle: androidx.swiperefreshlayout:swiperefreshlayout:1.0.0@aar" level="project" />
148
+    <orderEntry type="library" name="Gradle: androidx.viewpager:viewpager:1.0.0@aar" level="project" />
149
+    <orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-ui:1.0.0@aar" level="project" />
150
+    <orderEntry type="library" name="Gradle: androidx.loader:loader:1.0.0@aar" level="project" />
151
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:imagepipeline-okhttp3:2.0.0@aar" level="project" />
152
+    <orderEntry type="library" name="Gradle: androidx.appcompat:appcompat:1.0.2@aar" level="project" />
153
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:drawee:2.0.0@aar" level="project" />
154
+    <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata:2.0.0@aar" level="project" />
155
+    <orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable-animated:1.0.0@aar" level="project" />
156
+    <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-common:2.0.0@jar" level="project" />
157
+    <orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-utils:1.0.0@aar" level="project" />
158
+    <orderEntry type="library" name="Gradle: androidx.print:print:1.0.0@aar" level="project" />
159
+    <orderEntry type="library" name="Gradle: androidx.versionedparcelable:versionedparcelable:1.0.0@aar" level="project" />
160
+    <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-viewmodel:2.0.0@aar" level="project" />
161
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:fbcore:2.0.0@aar" level="project" />
162
+    <orderEntry type="library" name="Gradle: androidx.arch.core:core-common:2.0.0@jar" level="project" />
163
+    <orderEntry type="library" name="Gradle: androidx.annotation:annotation:1.0.0@jar" level="project" />
164
+    <orderEntry type="library" name="Gradle: com.facebook.infer.annotation:infer-annotation:0.11.2@jar" level="project" />
165
+    <orderEntry type="library" name="Gradle: androidx.core:core:1.0.1@aar" level="project" />
166
+    <orderEntry type="library" name="Gradle: com.squareup.okio:okio:1.15.0@jar" level="project" />
167
+    <orderEntry type="library" name="Gradle: com.facebook.fresco:nativeimagetranscoder:2.0.0@aar" level="project" />
168
+    <orderEntry type="library" name="Gradle: androidx.collection:collection:1.0.0@jar" level="project" />
169
+  </component>
170
+</module>

+ 10
- 0
android/src/main/AndroidManifest.xml View File

@@ -0,0 +1,10 @@
1
+
2
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3
+          package="cn.jystudio.bluetooth">
4
+    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
5
+    <uses-permission android:name="android.permission.BLUETOOTH" />
6
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
7
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
8
+
9
+</manifest>
10
+  

+ 8
- 0
android/src/main/gen/cn/jystudio/bluetooth/BuildConfig.java View File

@@ -0,0 +1,8 @@
1
+/*___Generated_by_IDEA___*/
2
+
3
+package cn.jystudio.bluetooth;
4
+
5
+/* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */
6
+public final class BuildConfig {
7
+  public final static boolean DEBUG = Boolean.parseBoolean(null);
8
+}

+ 7
- 0
android/src/main/gen/cn/jystudio/bluetooth/Manifest.java View File

@@ -0,0 +1,7 @@
1
+/*___Generated_by_IDEA___*/
2
+
3
+package cn.jystudio.bluetooth;
4
+
5
+/* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */
6
+public final class Manifest {
7
+}

+ 7
- 0
android/src/main/gen/cn/jystudio/bluetooth/R.java View File

@@ -0,0 +1,7 @@
1
+/*___Generated_by_IDEA___*/
2
+
3
+package cn.jystudio.bluetooth;
4
+
5
+/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */
6
+public final class R {
7
+}

+ 345
- 0
android/src/main/java/cn/jystudio/bluetooth/BluetoothService.java View File

@@ -0,0 +1,345 @@
1
+
2
+package cn.jystudio.bluetooth;
3
+
4
+import android.bluetooth.BluetoothAdapter;
5
+import android.bluetooth.BluetoothDevice;
6
+import android.bluetooth.BluetoothServerSocket;
7
+import android.bluetooth.BluetoothSocket;
8
+import android.content.Context;
9
+import android.util.Log;
10
+
11
+import java.io.IOException;
12
+import java.io.InputStream;
13
+import java.io.OutputStream;
14
+import java.util.*;
15
+import java.lang.reflect.Method;
16
+
17
+/**
18
+ * This class does all the work for setting up and managing Bluetooth
19
+ * connections with other devices.
20
+ */
21
+public class BluetoothService {
22
+    // Debugging
23
+    private static final String TAG = "BluetoothService";
24
+    private static final boolean DEBUG = true;
25
+
26
+
27
+    // Name for the SDP record when creating server socket
28
+    private static final String NAME = "BTPrinter";
29
+    //UUID must be this
30
+    // Unique UUID for this application
31
+    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
32
+
33
+    // Member fields
34
+    private BluetoothAdapter mAdapter;
35
+
36
+    private ConnectedThread mConnectedThread;
37
+    private int mState;
38
+
39
+    // Constants that indicate the current connection state
40
+    public static final int STATE_NONE = 0;       // we're doing nothing
41
+   // public static final int STATE_LISTEN = 1;     // now listening for incoming connections //feathure removed.
42
+    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
43
+    public static final int STATE_CONNECTED = 3;  // now connected to a remote device
44
+
45
+
46
+    public static final int MESSAGE_STATE_CHANGE = 4;
47
+    public static final int MESSAGE_READ = 5;
48
+    public static final int MESSAGE_WRITE = 6;
49
+    public static final int MESSAGE_DEVICE_NAME = 7;
50
+    public static final int MESSAGE_CONNECTION_LOST = 8;
51
+    public static final int MESSAGE_UNABLE_CONNECT = 9;
52
+
53
+    // Key names received from the BluetoothService Handler
54
+    public static final String DEVICE_NAME = "device_name";
55
+    public static final String DEVICE_ADDRESS = "device_address";
56
+    public static final String TOAST = "toast";
57
+
58
+    public static String ErrorMessage = "No_Error_Message";
59
+
60
+    private static List<BluetoothServiceStateObserver> observers = new ArrayList<BluetoothServiceStateObserver>();
61
+
62
+    /**
63
+     * Constructor. Prepares a new BTPrinter session.
64
+     *
65
+     * @param context The UI Activity Context
66
+     */
67
+    public BluetoothService(Context context) {
68
+        mAdapter = BluetoothAdapter.getDefaultAdapter();
69
+        mState = STATE_NONE;
70
+
71
+    }
72
+
73
+    public void addStateObserver(BluetoothServiceStateObserver observer) {
74
+        observers.add(observer);
75
+    }
76
+
77
+    public void removeStateObserver(BluetoothServiceStateObserver observer) {
78
+        observers.remove(observer);
79
+    }
80
+
81
+    /**
82
+     * Set the current state of the connection
83
+     *
84
+     * @param state An integer defining the current connection state
85
+     */
86
+    private synchronized void setState(int state, Map<String, Object> bundle) {
87
+        if (DEBUG) Log.d(TAG, "setState() " + getStateName(mState) + " -> " + getStateName(state));
88
+        mState = state;
89
+        infoObervers(state, bundle);
90
+    }
91
+    private String getStateName(int state){
92
+        String name="UNKNOW:" + state;
93
+        if(STATE_NONE == state){
94
+            name="STATE_NONE";
95
+        }else if(STATE_CONNECTED == state){
96
+            name="STATE_CONNECTED";
97
+        }else if(STATE_CONNECTING ==  state){
98
+            name="STATE_CONNECTING";
99
+        }
100
+        return name;
101
+    }
102
+
103
+    private synchronized void infoObervers(int code, Map<String, Object> bundle) {
104
+        for (BluetoothServiceStateObserver ob : observers) {
105
+            ob.onBluetoothServiceStateChanged(code, bundle);
106
+        }
107
+    }
108
+
109
+    /**
110
+     * Return the current connection state.
111
+     */
112
+    public synchronized int getState() {
113
+        return mState;
114
+    }
115
+
116
+
117
+    /**
118
+     * Start the ConnectThread to initiate a connection to a remote device.
119
+     *
120
+     * @param device The BluetoothDevice to connect
121
+     */
122
+    public synchronized void connect(BluetoothDevice device) {
123
+        if (DEBUG) Log.d(TAG, "connect to: " + device);
124
+        BluetoothDevice connectedDevice = null;
125
+        if(mConnectedThread!=null){
126
+            connectedDevice = mConnectedThread.bluetoothDevice();
127
+        }
128
+        if( mState==STATE_CONNECTED && connectedDevice!=null && connectedDevice.getAddress().equals(device.getAddress())){
129
+            // connected already
130
+            Map<String, Object> bundle = new HashMap<String, Object>();
131
+            bundle.put(DEVICE_NAME, device.getName());
132
+            bundle.put(DEVICE_ADDRESS,device.getAddress());
133
+            setState(STATE_CONNECTED, bundle);
134
+        }else {
135
+            // Cancel any thread currently running a connection
136
+            this.stop();
137
+            // Start the thread to manage the connection and perform transmissions
138
+            mConnectedThread = new ConnectedThread(device);
139
+            mConnectedThread.start();
140
+            setState(STATE_CONNECTING, null);
141
+        }
142
+    }
143
+
144
+    /**
145
+     * Stop all threads
146
+     */
147
+    public synchronized void stop() {
148
+        if (mConnectedThread != null) {
149
+            mConnectedThread.cancel();
150
+            mConnectedThread = null;
151
+        }
152
+    }
153
+
154
+    /**
155
+     * Write to the ConnectedThread in an unsynchronized manner
156
+     *
157
+     * @param out The bytes to write
158
+     * @see ConnectedThread#write(byte[])
159
+     */
160
+    public void write(byte[] out) {
161
+        // Create temporary object
162
+        ConnectedThread r;
163
+        // Synchronize a copy of the ConnectedThread
164
+        synchronized (this) {
165
+            if (mState != STATE_CONNECTED) return;
166
+            r = mConnectedThread;
167
+        }
168
+        r.write(out);
169
+    }
170
+
171
+    /**
172
+     * Indicate that the connection attempt failed.
173
+     */
174
+    private void connectionFailed() {
175
+        setState(STATE_NONE, null);
176
+        infoObervers(MESSAGE_UNABLE_CONNECT, null);
177
+    }
178
+
179
+    /**
180
+     * Indicate that the connection was lost and notify the UI Activity.
181
+     */
182
+    private void connectionLost() {
183
+        setState(STATE_NONE, null);
184
+        infoObervers(MESSAGE_CONNECTION_LOST, null);
185
+    }
186
+
187
+    /**
188
+     * This thread runs during a connection with a remote device.
189
+     * It handles all incoming and outgoing transmissions.
190
+     */
191
+    private class ConnectedThread extends Thread {
192
+        private final BluetoothDevice mmDevice;
193
+        private  BluetoothSocket mmSocket;
194
+        private  InputStream mmInStream;
195
+        private  OutputStream mmOutStream;
196
+
197
+        public ConnectedThread(BluetoothDevice device) {
198
+            mmDevice = device;
199
+        }
200
+
201
+        @Override
202
+        public void run() {
203
+            Log.i(TAG, "BEGIN mConnectThread");
204
+            setName("ConnectThread");
205
+            Map<String, Object> bundle = new HashMap<String, Object>();
206
+
207
+            // Always cancel discovery because it will slow down a connection
208
+            mAdapter.cancelDiscovery();
209
+
210
+            BluetoothSocket tmp = null;
211
+
212
+            // try to connect with socket inner method firstly.
213
+            for(int i=1;i<=3;i++) {
214
+                try {
215
+                    tmp = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", int.class).invoke(mmDevice, i);
216
+                } catch (Exception e) {
217
+                }
218
+                if(tmp!=null){
219
+                    mmSocket = tmp;
220
+                    break;
221
+                }
222
+            }
223
+
224
+            // try with given uuid
225
+            if(mmSocket == null) {
226
+                try {
227
+                    tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
228
+                } catch (IOException e) {
229
+                    e.printStackTrace();
230
+                    Log.e(TAG, "create() failed", e);
231
+                }
232
+                if (tmp == null) {
233
+                    Log.e(TAG, "create() failed: Socket NULL.");
234
+                    connectionFailed();
235
+                    return;
236
+                }
237
+            }
238
+            mmSocket = tmp;
239
+
240
+            // Make a connection to the BluetoothSocket
241
+            try {
242
+                // This is a blocking call and will only return on a
243
+                // successful connection or an exception
244
+                mmSocket.connect();
245
+            } catch (Exception e) {
246
+                e.printStackTrace();
247
+                connectionFailed();
248
+                // Close the socket
249
+                try {
250
+                    mmSocket.close();
251
+                } catch (Exception e2) {
252
+                    Log.e(TAG, "unable to close() socket during connection failure", e2);
253
+                }
254
+                return;
255
+            }
256
+
257
+
258
+            Log.d(TAG, "create ConnectedThread");
259
+            InputStream tmpIn = null;
260
+            OutputStream tmpOut = null;
261
+
262
+            // Get the BluetoothSocket input and output streams
263
+            try {
264
+                tmpIn = mmSocket.getInputStream();
265
+                tmpOut = mmSocket.getOutputStream();
266
+            } catch (IOException e) {
267
+                Log.e(TAG, "temp sockets not created", e);
268
+            }
269
+
270
+            mmInStream = tmpIn;
271
+            mmOutStream = tmpOut;
272
+
273
+            bundle.put(DEVICE_NAME, mmDevice.getName());
274
+            bundle.put(DEVICE_ADDRESS,mmDevice.getAddress());
275
+            setState(STATE_CONNECTED, bundle);
276
+
277
+            Log.i(TAG, "Connected");
278
+            int bytes;
279
+
280
+            // Keep listening to the InputStream while connected
281
+            while (true) {
282
+                try {
283
+                    byte[] buffer = new byte[256];
284
+                    // Read from the InputStream
285
+                    bytes = mmInStream.read(buffer);
286
+                    if (bytes > 0) {
287
+                        // Send the obtained bytes to the UI Activity
288
+                        bundle = new HashMap<String, Object>();
289
+                        bundle.put("bytes", bytes);
290
+                        infoObervers(MESSAGE_READ, bundle);
291
+                    } else {
292
+                        Log.e(TAG, "disconnected");
293
+                        connectionLost();
294
+                        break;
295
+                    }
296
+                } catch (IOException e) {
297
+                    Log.e(TAG, "disconnected", e);
298
+                    connectionLost();
299
+                    break;
300
+                }
301
+            }
302
+            Log.i(TAG, "ConnectedThread End");
303
+        }
304
+
305
+        /**
306
+         * Write to the connected OutStream.
307
+         *
308
+         * @param buffer The bytes to write
309
+         */
310
+        public void write(byte[] buffer) {
311
+            try {
312
+                mmOutStream.write(buffer);
313
+                mmOutStream.flush();//清空缓存
314
+               /* if (buffer.length > 3000) //
315
+                {
316
+                  byte[] readata = new byte[1];
317
+                  SPPReadTimeout(readata, 1, 5000);
318
+                }*/
319
+                Log.i("BTPWRITE", new String(buffer, "GBK"));
320
+                Map<String, Object> bundle = new HashMap<String, Object>();
321
+                bundle.put("bytes", buffer);
322
+                infoObervers(MESSAGE_WRITE, bundle);
323
+            } catch (IOException e) {
324
+                Log.e(TAG, "Exception during write", e);
325
+            }
326
+        }
327
+
328
+        public BluetoothDevice bluetoothDevice(){
329
+            if(mmSocket!=null && mmSocket.isConnected()){
330
+                return mmSocket.getRemoteDevice();
331
+            }else{
332
+                return null;
333
+            }
334
+        }
335
+
336
+        public void cancel() {
337
+            try {
338
+                mmSocket.close();
339
+                connectionLost();
340
+            } catch (IOException e) {
341
+                Log.e(TAG, "close() of connect socket failed", e);
342
+            }
343
+        }
344
+    }
345
+}

+ 11
- 0
android/src/main/java/cn/jystudio/bluetooth/BluetoothServiceStateObserver.java View File

@@ -0,0 +1,11 @@
1
+package cn.jystudio.bluetooth;
2
+
3
+import java.util.Map;
4
+
5
+
6
+/**
7
+ * Created by januslo on 2018/9/22.
8
+ */
9
+public interface BluetoothServiceStateObserver {
10
+    void onBluetoothServiceStateChanged(int state, Map<String,Object> boundle);
11
+}

+ 34
- 0
android/src/main/java/cn/jystudio/bluetooth/RNBluetoothEscposPrinterPackage.java View File

@@ -0,0 +1,34 @@
1
+
2
+package cn.jystudio.bluetooth;
3
+
4
+import java.util.Arrays;
5
+import java.util.Collections;
6
+import java.util.List;
7
+
8
+import cn.jystudio.bluetooth.escpos.RNBluetoothEscposPrinterModule;
9
+import cn.jystudio.bluetooth.tsc.RNBluetoothTscPrinterModule;
10
+import com.facebook.react.ReactPackage;
11
+import com.facebook.react.bridge.NativeModule;
12
+import com.facebook.react.bridge.ReactApplicationContext;
13
+import com.facebook.react.uimanager.ViewManager;
14
+import com.facebook.react.bridge.JavaScriptModule;
15
+
16
+public class RNBluetoothEscposPrinterPackage implements ReactPackage {
17
+    @Override
18
+    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
19
+        BluetoothService service = new BluetoothService(reactContext);
20
+        return Arrays.<NativeModule>asList(new RNBluetoothManagerModule(reactContext, service),
21
+                new RNBluetoothEscposPrinterModule(reactContext, service),
22
+                new RNBluetoothTscPrinterModule(reactContext, service));
23
+    }
24
+
25
+    // Deprecated from RN 0.47
26
+    public List<Class<? extends JavaScriptModule>> createJSModules() {
27
+        return Collections.emptyList();
28
+    }
29
+
30
+    @Override
31
+    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
32
+        return Collections.emptyList();
33
+    }
34
+}

+ 442
- 0
android/src/main/java/cn/jystudio/bluetooth/RNBluetoothManagerModule.java View File

@@ -0,0 +1,442 @@
1
+package cn.jystudio.bluetooth;
2
+
3
+
4
+import android.app.Activity;
5
+import android.bluetooth.BluetoothAdapter;
6
+import android.bluetooth.BluetoothDevice;
7
+import android.content.BroadcastReceiver;
8
+import android.content.Context;
9
+import android.content.Intent;
10
+import android.content.IntentFilter;
11
+import android.content.pm.PackageManager;
12
+import android.os.Bundle;
13
+import androidx.core.app.ActivityCompat;
14
+import androidx.core.content.ContextCompat;
15
+import android.util.Log;
16
+import android.widget.Toast;
17
+import com.facebook.react.bridge.*;
18
+import com.facebook.react.modules.core.DeviceEventManagerModule;
19
+import org.json.JSONArray;
20
+import org.json.JSONObject;
21
+
22
+import javax.annotation.Nullable;
23
+import java.lang.reflect.Method;
24
+import java.util.Collections;
25
+import java.util.HashMap;
26
+import java.util.Map;
27
+import java.util.Set;
28
+
29
+/**
30
+ * Created by januslo on 2018/9/22.
31
+ */
32
+public class RNBluetoothManagerModule extends ReactContextBaseJavaModule
33
+        implements ActivityEventListener, BluetoothServiceStateObserver {
34
+
35
+    private static final String TAG = "BluetoothManager";
36
+    private final ReactApplicationContext reactContext;
37
+    public static final String EVENT_DEVICE_ALREADY_PAIRED = "EVENT_DEVICE_ALREADY_PAIRED";
38
+    public static final String EVENT_DEVICE_FOUND = "EVENT_DEVICE_FOUND";
39
+    public static final String EVENT_DEVICE_DISCOVER_DONE = "EVENT_DEVICE_DISCOVER_DONE";
40
+    public static final String EVENT_CONNECTION_LOST = "EVENT_CONNECTION_LOST";
41
+    public static final String EVENT_UNABLE_CONNECT = "EVENT_UNABLE_CONNECT";
42
+    public static final String EVENT_CONNECTED = "EVENT_CONNECTED";
43
+    public static final String EVENT_BLUETOOTH_NOT_SUPPORT = "EVENT_BLUETOOTH_NOT_SUPPORT";
44
+
45
+
46
+    // Intent request codes
47
+    private static final int REQUEST_CONNECT_DEVICE = 1;
48
+    private static final int REQUEST_ENABLE_BT = 2;
49
+
50
+    public static final int MESSAGE_STATE_CHANGE = BluetoothService.MESSAGE_STATE_CHANGE;
51
+    public static final int MESSAGE_READ = BluetoothService.MESSAGE_READ;
52
+    public static final int MESSAGE_WRITE = BluetoothService.MESSAGE_WRITE;
53
+    public static final int MESSAGE_DEVICE_NAME = BluetoothService.MESSAGE_DEVICE_NAME;
54
+
55
+    public static final int MESSAGE_CONNECTION_LOST = BluetoothService.MESSAGE_CONNECTION_LOST;
56
+    public static final int MESSAGE_UNABLE_CONNECT = BluetoothService.MESSAGE_UNABLE_CONNECT;
57
+    public static final String DEVICE_NAME = BluetoothService.DEVICE_NAME;
58
+    public static final String TOAST = BluetoothService.TOAST;
59
+
60
+    // Return Intent extra
61
+    public static String EXTRA_DEVICE_ADDRESS = "device_address";
62
+
63
+    private static final Map<String, Promise> promiseMap = Collections.synchronizedMap(new HashMap<String, Promise>());
64
+    private static final String PROMISE_ENABLE_BT = "ENABLE_BT";
65
+    private static final String PROMISE_SCAN = "SCAN";
66
+    private static final String PROMISE_CONNECT = "CONNECT";
67
+
68
+    private JSONArray pairedDeivce = new JSONArray();
69
+    private JSONArray foundDevice = new JSONArray();
70
+    // Name of the connected device
71
+    private String mConnectedDeviceName = null;
72
+    // Local Bluetooth adapter
73
+    private BluetoothAdapter mBluetoothAdapter = null;
74
+    // Member object for the services
75
+    private BluetoothService mService = null;
76
+
77
+    public RNBluetoothManagerModule(ReactApplicationContext reactContext, BluetoothService bluetoothService) {
78
+        super(reactContext);
79
+        this.reactContext = reactContext;
80
+        this.reactContext.addActivityEventListener(this);
81
+        this.mService = bluetoothService;
82
+        this.mService.addStateObserver(this);
83
+        // Register for broadcasts when a device is discovered
84
+        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
85
+        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
86
+        this.reactContext.registerReceiver(discoverReceiver, filter);
87
+    }
88
+
89
+    @Override
90
+    public
91
+    @Nullable
92
+    Map<String, Object> getConstants() {
93
+        Map<String, Object> constants = new HashMap<>();
94
+        constants.put(EVENT_DEVICE_ALREADY_PAIRED, EVENT_DEVICE_ALREADY_PAIRED);
95
+        constants.put(EVENT_DEVICE_DISCOVER_DONE, EVENT_DEVICE_DISCOVER_DONE);
96
+        constants.put(EVENT_DEVICE_FOUND, EVENT_DEVICE_FOUND);
97
+        constants.put(EVENT_CONNECTION_LOST, EVENT_CONNECTION_LOST);
98
+        constants.put(EVENT_UNABLE_CONNECT, EVENT_UNABLE_CONNECT);
99
+        constants.put(EVENT_CONNECTED, EVENT_CONNECTED);
100
+        constants.put(EVENT_BLUETOOTH_NOT_SUPPORT, EVENT_BLUETOOTH_NOT_SUPPORT);
101
+        constants.put(DEVICE_NAME, DEVICE_NAME);
102
+        constants.put(EVENT_BLUETOOTH_NOT_SUPPORT, EVENT_BLUETOOTH_NOT_SUPPORT);
103
+        return constants;
104
+    }
105
+
106
+    private BluetoothAdapter getBluetoothAdapter(){
107
+        if(mBluetoothAdapter == null){
108
+            // Get local Bluetooth adapter
109
+            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
110
+        }
111
+        // If the adapter is null, then Bluetooth is not supported
112
+        if (mBluetoothAdapter == null) {
113
+            emitRNEvent(EVENT_BLUETOOTH_NOT_SUPPORT,  Arguments.createMap());
114
+        }
115
+
116
+        return mBluetoothAdapter;
117
+    }
118
+
119
+
120
+    @ReactMethod
121
+    public void enableBluetooth(final Promise promise) {
122
+        BluetoothAdapter adapter = this.getBluetoothAdapter();
123
+        if(adapter == null){
124
+            promise.reject(EVENT_BLUETOOTH_NOT_SUPPORT);
125
+        }else if (!adapter.isEnabled()) {
126
+            // If Bluetooth is not on, request that it be enabled.
127
+            // setupChat() will then be called during onActivityResult
128
+            Intent enableIntent = new Intent(
129
+                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
130
+            promiseMap.put(PROMISE_ENABLE_BT, promise);
131
+            this.reactContext.startActivityForResult(enableIntent, REQUEST_ENABLE_BT, Bundle.EMPTY);
132
+        } else {
133
+            WritableArray pairedDeivce =Arguments.createArray();
134
+            Set<BluetoothDevice> boundDevices = adapter.getBondedDevices();
135
+            for (BluetoothDevice d : boundDevices) {
136
+                try {
137
+                    JSONObject obj = new JSONObject();
138
+                    obj.put("name", d.getName());
139
+                    obj.put("address", d.getAddress());
140
+                    pairedDeivce.pushString(obj.toString());
141
+                } catch (Exception e) {
142
+                    //ignore.
143
+                }
144
+            }Log.d(TAG,"ble Enabled");
145
+            promise.resolve(pairedDeivce);
146
+        }
147
+    }
148
+
149
+    @ReactMethod
150
+    public void disableBluetooth(final Promise promise) {
151
+        BluetoothAdapter adapter = this.getBluetoothAdapter();
152
+        if(adapter == null){
153
+            promise.resolve(true);
154
+        }else {
155
+            if (mService != null && mService.getState() != BluetoothService.STATE_NONE) {
156
+                mService.stop();
157
+            }
158
+            promise.resolve(!adapter.isEnabled() || adapter.disable());
159
+        }
160
+    }
161
+
162
+    @ReactMethod
163
+    public void isBluetoothEnabled(final Promise promise) {
164
+        BluetoothAdapter adapter = this.getBluetoothAdapter();
165
+        promise.resolve(adapter!=null && adapter.isEnabled());
166
+    }
167
+
168
+    @ReactMethod
169
+    public void scanDevices(final Promise promise) {
170
+        BluetoothAdapter adapter = this.getBluetoothAdapter();
171
+        if(adapter == null){
172
+            promise.reject(EVENT_BLUETOOTH_NOT_SUPPORT);
173
+        }else {
174
+            cancelDisCovery();
175
+            int permissionChecked = ContextCompat.checkSelfPermission(reactContext, android.Manifest.permission.ACCESS_COARSE_LOCATION);
176
+            if (permissionChecked == PackageManager.PERMISSION_DENIED) {
177
+                // // TODO: 2018/9/21
178
+                ActivityCompat.requestPermissions(reactContext.getCurrentActivity(),
179
+                        new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
180
+                        1);
181
+            }
182
+
183
+
184
+            pairedDeivce = new JSONArray();
185
+            foundDevice = new JSONArray();
186
+            Set<BluetoothDevice> boundDevices = adapter.getBondedDevices();
187
+            for (BluetoothDevice d : boundDevices) {
188
+                try {
189
+                    JSONObject obj = new JSONObject();
190
+                    obj.put("name", d.getName());
191
+                    obj.put("address", d.getAddress());
192
+                    pairedDeivce.put(obj);
193
+                } catch (Exception e) {
194
+                    //ignore.
195
+                }
196
+            }
197
+
198
+            WritableMap params = Arguments.createMap();
199
+            params.putString("devices", pairedDeivce.toString());
200
+            emitRNEvent(EVENT_DEVICE_ALREADY_PAIRED, params);
201
+            if (!adapter.startDiscovery()) {
202
+                promise.reject("DISCOVER", "NOT_STARTED");
203
+                cancelDisCovery();
204
+            } else {
205
+                promiseMap.put(PROMISE_SCAN, promise);
206
+            }
207
+        }
208
+    }
209
+
210
+    @ReactMethod
211
+    public void connect(String address, final Promise promise) {
212
+        BluetoothAdapter adapter = this.getBluetoothAdapter();
213
+        if (adapter!=null && adapter.isEnabled()) {
214
+            BluetoothDevice device = adapter.getRemoteDevice(address);
215
+            promiseMap.put(PROMISE_CONNECT, promise);
216
+            mService.connect(device);
217
+        } else {
218
+            promise.reject("BT NOT ENABLED");
219
+        }
220
+
221
+    }
222
+
223
+    @ReactMethod
224
+    public void unpaire(String address,final Promise promise){
225
+        BluetoothAdapter adapter = this.getBluetoothAdapter();
226
+        if (adapter!=null && adapter.isEnabled()) {
227
+            BluetoothDevice device = adapter.getRemoteDevice(address);
228
+            this.unpairDevice(device);
229
+            promise.resolve(address);
230
+        } else {
231
+            promise.reject("BT NOT ENABLED");
232
+        }
233
+
234
+    }
235
+
236
+    private void unpairDevice(BluetoothDevice device) {
237
+        try {
238
+            Method m = device.getClass()
239
+                    .getMethod("removeBond", (Class[]) null);
240
+            m.invoke(device, (Object[]) null);
241
+        } catch (Exception e) {
242
+            Log.e(TAG, e.getMessage());
243
+        }
244
+    }
245
+
246
+    private void cancelDisCovery() {
247
+        try {
248
+            BluetoothAdapter adapter = this.getBluetoothAdapter();
249
+            if (adapter!=null && adapter.isDiscovering()) {
250
+                adapter.cancelDiscovery();
251
+            }
252
+            Log.d(TAG, "Discover canceled");
253
+        } catch (Exception e) {
254
+            //ignore
255
+        }
256
+    }
257
+
258
+
259
+    @Override
260
+    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
261
+        BluetoothAdapter adapter = this.getBluetoothAdapter();
262
+        Log.d(TAG, "onActivityResult " + resultCode);
263
+        switch (requestCode) {
264
+            case REQUEST_CONNECT_DEVICE: {
265
+                // When DeviceListActivity returns with a device to connect
266
+                if (resultCode == Activity.RESULT_OK) {
267
+                    // Get the device MAC address
268
+                    String address = data.getExtras().getString(
269
+                            EXTRA_DEVICE_ADDRESS);
270
+                    // Get the BLuetoothDevice object
271
+                    if (adapter!=null && BluetoothAdapter.checkBluetoothAddress(address)) {
272
+                        BluetoothDevice device = adapter
273
+                                .getRemoteDevice(address);
274
+                        // Attempt to connect to the device
275
+                        mService.connect(device);
276
+                    }
277
+                }
278
+                break;
279
+            }
280
+            case REQUEST_ENABLE_BT: {
281
+                Promise promise = promiseMap.remove(PROMISE_ENABLE_BT);
282
+                // When the request to enable Bluetooth returns
283
+                if (resultCode == Activity.RESULT_OK && promise != null) {
284
+                    // Bluetooth is now enabled, so set up a session
285
+                    if(adapter!=null){
286
+                        WritableArray pairedDeivce =Arguments.createArray();
287
+                        Set<BluetoothDevice> boundDevices = adapter.getBondedDevices();
288
+                        for (BluetoothDevice d : boundDevices) {
289
+                            try {
290
+                                JSONObject obj = new JSONObject();
291
+                                obj.put("name", d.getName());
292
+                                obj.put("address", d.getAddress());
293
+                                pairedDeivce.pushString(obj.toString());
294
+                            } catch (Exception e) {
295
+                                //ignore.
296
+                            }
297
+                        }
298
+                        promise.resolve(pairedDeivce);
299
+                    }else{
300
+                        promise.resolve(null);
301
+                    }
302
+
303
+                } else {
304
+                    // User did not enable Bluetooth or an error occured
305
+                    Log.d(TAG, "BT not enabled");
306
+                    if (promise != null) {
307
+                        promise.reject("ERR", new Exception("BT NOT ENABLED"));
308
+                    }
309
+                }
310
+                break;
311
+            }
312
+        }
313
+    }
314
+
315
+    @Override
316
+    public void onNewIntent(Intent intent) {
317
+
318
+    }
319
+
320
+    @Override
321
+    public String getName() {
322
+        return "BluetoothManager";
323
+    }
324
+
325
+
326
+    private boolean objectFound(JSONObject obj) {
327
+        boolean found = false;
328
+        if (foundDevice.length() > 0) {
329
+            for (int i = 0; i < foundDevice.length(); i++) {
330
+                try {
331
+                    String objAddress = obj.optString("address", "objAddress");
332
+                    String dsAddress = ((JSONObject) foundDevice.get(i)).optString("address", "dsAddress");
333
+                    if (objAddress.equalsIgnoreCase(dsAddress)) {
334
+                        found = true;
335
+                        break;
336
+                    }
337
+                } catch (Exception e) {
338
+                }
339
+            }
340
+        }
341
+        return found;
342
+    }
343
+
344
+    // The BroadcastReceiver that listens for discovered devices and
345
+    // changes the title when discovery is finished
346
+    private final BroadcastReceiver discoverReceiver = new BroadcastReceiver() {
347
+        @Override
348
+        public void onReceive(Context context, Intent intent) {
349
+            String action = intent.getAction();
350
+            Log.d(TAG, "on receive:" + action);
351
+            // When discovery finds a device
352
+            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
353
+                // Get the BluetoothDevice object from the Intent
354
+                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
355
+                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
356
+                    JSONObject deviceFound = new JSONObject();
357
+                    try {
358
+                        deviceFound.put("name", device.getName());
359
+                        deviceFound.put("address", device.getAddress());
360
+                    } catch (Exception e) {
361
+                        //ignore
362
+                    }
363
+                    if (!objectFound(deviceFound)) {
364
+                        foundDevice.put(deviceFound);
365
+                        WritableMap params = Arguments.createMap();
366
+                        params.putString("device", deviceFound.toString());
367
+                        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
368
+                                .emit(EVENT_DEVICE_FOUND, params);
369
+                    }
370
+
371
+                }
372
+            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
373
+                Promise promise = promiseMap.remove(PROMISE_SCAN);
374
+                if (promise != null) {
375
+
376
+                    JSONObject result = null;
377
+                    try {
378
+                        result = new JSONObject();
379
+                        result.put("paired", pairedDeivce);
380
+                        result.put("found", foundDevice);
381
+                        promise.resolve(result.toString());
382
+                    } catch (Exception e) {
383
+                        //ignore
384
+                    }
385
+                    WritableMap params = Arguments.createMap();
386
+                    params.putString("paired", pairedDeivce.toString());
387
+                    params.putString("found", foundDevice.toString());
388
+                    emitRNEvent(EVENT_DEVICE_DISCOVER_DONE, params);
389
+                }
390
+            }
391
+        }
392
+    };
393
+
394
+    private void emitRNEvent(String event, @Nullable WritableMap params) {
395
+        getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
396
+                .emit(event, params);
397
+    }
398
+
399
+    @Override
400
+    public void onBluetoothServiceStateChanged(int state, Map<String, Object> bundle) {
401
+        Log.d(TAG,"on bluetoothServiceStatChange:"+state);
402
+        switch (state) {
403
+            case BluetoothService.STATE_CONNECTED:
404
+            case MESSAGE_DEVICE_NAME: {
405
+                // save the connected device's name
406
+                mConnectedDeviceName = (String) bundle.get(DEVICE_NAME);
407
+                Promise p = promiseMap.remove(PROMISE_CONNECT);
408
+                if (p == null) {   Log.d(TAG,"No Promise found.");
409
+                    WritableMap params = Arguments.createMap();
410
+                    params.putString(DEVICE_NAME, mConnectedDeviceName);
411
+                    emitRNEvent(EVENT_CONNECTED, params);
412
+                } else { Log.d(TAG,"Promise Resolve.");
413
+                    p.resolve(mConnectedDeviceName);
414
+                }
415
+
416
+                break;
417
+            }
418
+            case MESSAGE_CONNECTION_LOST: {
419
+                //Connection lost should not be the connect result.
420
+               // Promise p = promiseMap.remove(PROMISE_CONNECT);
421
+               // if (p == null) {
422
+                    emitRNEvent(EVENT_CONNECTION_LOST, null);
423
+               // } else {
424
+                 //   p.reject("Device connection was lost");
425
+                //}
426
+                break;
427
+            }
428
+            case MESSAGE_UNABLE_CONNECT: {     //无法连接设备
429
+                Promise p = promiseMap.remove(PROMISE_CONNECT);
430
+                if (p == null) {
431
+                    emitRNEvent(EVENT_UNABLE_CONNECT, null);
432
+                } else {
433
+                    p.reject("Unable to connect device");
434
+                }
435
+
436
+                break;
437
+            }
438
+            default:
439
+                break;
440
+        }
441
+    }
442
+}

+ 492
- 0
android/src/main/java/cn/jystudio/bluetooth/escpos/RNBluetoothEscposPrinterModule.java View File

@@ -0,0 +1,492 @@
1
+
2
+package cn.jystudio.bluetooth.escpos;
3
+
4
+import android.graphics.Bitmap;
5
+import android.graphics.BitmapFactory;
6
+import android.util.Base64;
7
+import android.util.Log;
8
+import cn.jystudio.bluetooth.BluetoothService;
9
+import cn.jystudio.bluetooth.BluetoothServiceStateObserver;
10
+import cn.jystudio.bluetooth.escpos.command.sdk.Command;
11
+import cn.jystudio.bluetooth.escpos.command.sdk.PrintPicture;
12
+import cn.jystudio.bluetooth.escpos.command.sdk.PrinterCommand;
13
+import com.facebook.react.bridge.*;
14
+import com.google.zxing.BarcodeFormat;
15
+import com.google.zxing.EncodeHintType;
16
+import com.google.zxing.common.BitMatrix;
17
+import com.google.zxing.qrcode.QRCodeWriter;
18
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
19
+
20
+import javax.annotation.Nullable;
21
+import java.nio.charset.Charset;
22
+import java.util.*;
23
+
24
+public class RNBluetoothEscposPrinterModule extends ReactContextBaseJavaModule
25
+        implements BluetoothServiceStateObserver {
26
+    private static final String TAG = "BluetoothEscposPrinter";
27
+
28
+    public static final int WIDTH_58 = 384;
29
+    public static final int WIDTH_80 = 576;
30
+    private final ReactApplicationContext reactContext;
31
+    /******************************************************************************************************/
32
+
33
+    private int deviceWidth = WIDTH_58;
34
+    private BluetoothService mService;
35
+
36
+
37
+    public RNBluetoothEscposPrinterModule(ReactApplicationContext reactContext,
38
+                                          BluetoothService bluetoothService) {
39
+        super(reactContext);
40
+        this.reactContext = reactContext;
41
+        this.mService = bluetoothService;
42
+        this.mService.addStateObserver(this);
43
+    }
44
+
45
+    @Override
46
+    public String getName() {
47
+        return "BluetoothEscposPrinter";
48
+    }
49
+
50
+
51
+    @Override
52
+    public
53
+    @Nullable
54
+    Map<String, Object> getConstants() {
55
+        Map<String, Object> constants = new HashMap<>();
56
+        constants.put("width58", WIDTH_58);
57
+        constants.put("width80", WIDTH_80);
58
+        return constants;
59
+    }
60
+
61
+    @ReactMethod
62
+    public void printerInit(final Promise promise){
63
+        if(sendDataByte(PrinterCommand.POS_Set_PrtInit())){
64
+            promise.resolve(null);
65
+        }else{
66
+            promise.reject("COMMAND_NOT_SEND");
67
+        }
68
+    }
69
+
70
+    @ReactMethod
71
+    public void printAndFeed(int feed,final Promise promise){
72
+        if(sendDataByte(PrinterCommand.POS_Set_PrtAndFeedPaper(feed))){
73
+            promise.resolve(null);
74
+        }else{
75
+            promise.reject("COMMAND_NOT_SEND");
76
+        }
77
+    }
78
+
79
+    @ReactMethod
80
+    public void printerLeftSpace(int sp,final Promise promise){
81
+        if(sendDataByte(PrinterCommand.POS_Set_LeftSP(sp))){
82
+            promise.resolve(null);
83
+        }else{
84
+            promise.reject("COMMAND_NOT_SEND");
85
+        }
86
+    }
87
+
88
+    @ReactMethod
89
+    public void printerLineSpace(int sp,final Promise promise){
90
+        byte[] command = PrinterCommand.POS_Set_DefLineSpace();
91
+        if(sp>0){
92
+            command = PrinterCommand.POS_Set_LineSpace(sp);
93
+        }
94
+        if(command==null || !sendDataByte(command)){
95
+            promise.reject("COMMAND_NOT_SEND");
96
+        }else{
97
+            promise.resolve(null);
98
+        }
99
+    }
100
+
101
+    /**
102
+     * Under line switch, 0-off,1-on,2-deeper
103
+     * @param line 0-off,1-on,2-deeper
104
+     */
105
+    @ReactMethod
106
+    public void printerUnderLine(int line,final Promise promise){
107
+        if(sendDataByte(PrinterCommand.POS_Set_UnderLine(line))){
108
+            promise.resolve(null);
109
+        }else{
110
+            promise.reject("COMMAND_NOT_SEND");
111
+        }
112
+    }
113
+
114
+    /**
115
+     * When n=0 or 48, left justification is enabled
116
+     * When n=1 or 49, center justification is enabled
117
+     * When n=2 or 50, right justification is enabled
118
+     * @param align
119
+     * @param promise
120
+     */
121
+    @ReactMethod
122
+    public void printerAlign(int align,final Promise promise){
123
+        Log.d(TAG,"Align:"+align);
124
+        if(sendDataByte(PrinterCommand.POS_S_Align(align))){
125
+            promise.resolve(null);
126
+        }else{
127
+            promise.reject("COMMAND_NOT_SEND");
128
+        }
129
+    }
130
+
131
+
132
+    @ReactMethod
133
+    public void printText(String text, @Nullable  ReadableMap options, final Promise promise) {
134
+        try {
135
+            String encoding = "GBK";
136
+            int codepage = 0;
137
+            int widthTimes = 0;
138
+            int heigthTimes=0;
139
+            int fonttype=0;
140
+            if(options!=null) {
141
+                encoding = options.hasKey("encoding") ? options.getString("encoding") : "GBK";
142
+                codepage = options.hasKey("codepage") ? options.getInt("codepage") : 0;
143
+                widthTimes = options.hasKey("widthtimes") ? options.getInt("widthtimes") : 0;
144
+                heigthTimes = options.hasKey("heigthtimes") ? options.getInt("heigthtimes") : 0;
145
+                fonttype = options.hasKey("fonttype") ? options.getInt("fonttype") : 0;
146
+            }
147
+            String toPrint = text;
148
+//            if ("UTF-8".equalsIgnoreCase(encoding)) {
149
+//                byte[] b = text.getBytes("UTF-8");
150
+//                toPrint = new String(b, Charset.forName(encoding));
151
+//            }
152
+
153
+            byte[] bytes = PrinterCommand.POS_Print_Text(toPrint, encoding, codepage, widthTimes, heigthTimes, fonttype);
154
+            if (sendDataByte(bytes)) {
155
+                promise.resolve(null);
156
+            } else {
157
+                promise.reject("COMMAND_NOT_SEND");
158
+            }
159
+        }catch (Exception e){
160
+            promise.reject(e.getMessage(),e);
161
+        }
162
+    }
163
+
164
+    @ReactMethod
165
+    public void printColumn(ReadableArray columnWidths,ReadableArray columnAligns,ReadableArray columnTexts,
166
+                            @Nullable ReadableMap options,final Promise promise){
167
+        if(columnWidths.size()!=columnTexts.size() || columnWidths.size()!=columnAligns.size()){
168
+            promise.reject("COLUMN_WIDTHS_ALIGNS_AND_TEXTS_NOT_MATCH");
169
+            return;
170
+        }
171
+            int totalLen = 0;
172
+            for(int i=0;i<columnWidths.size();i++){
173
+                totalLen+=columnWidths.getInt(i);
174
+            }
175
+            int maxLen = deviceWidth/8;
176
+            if(totalLen>maxLen){
177
+                promise.reject("COLUNM_WIDTHS_TOO_LARGE");
178
+                return;
179
+            }
180
+
181
+        String encoding = "GBK";
182
+        int codepage = 0;
183
+        int widthTimes = 0;
184
+        int heigthTimes = 0;
185
+        int fonttype = 0;
186
+        if (options != null) {
187
+            encoding = options.hasKey("encoding") ? options.getString("encoding") : "GBK";
188
+            codepage = options.hasKey("codepage") ? options.getInt("codepage") : 0;
189
+            widthTimes = options.hasKey("widthtimes") ? options.getInt("widthtimes") : 0;
190
+            heigthTimes = options.hasKey("heigthtimes") ? options.getInt("heigthtimes") : 0;
191
+            fonttype = options.hasKey("fonttype") ? options.getInt("fonttype") : 0;
192
+        }
193
+        Log.d(TAG,"encoding: "+encoding);
194
+
195
+        /**
196
+         * [column1-1,
197
+         * column1-2,
198
+         * column1-3 ... column1-n]
199
+         * ,
200
+         *  [column2-1,
201
+         * column2-2,
202
+         * column2-3 ... column2-n]
203
+         *
204
+         * ...
205
+         *
206
+         */
207
+        List<List<String>> table = new ArrayList<List<String>>();
208
+
209
+        /**splits the column text to few rows and applies the alignment **/
210
+        int padding = 1;
211
+        for(int i=0;i<columnWidths.size();i++){
212
+            int width =columnWidths.getInt(i)-padding;//1 char padding
213
+            String text = String.copyValueOf(columnTexts.getString(i).toCharArray());
214
+            List<ColumnSplitedString> splited = new ArrayList<ColumnSplitedString>();
215
+            int shorter = 0;
216
+            int counter = 0;
217
+            String temp = "";
218
+            for(int c=0;c<text.length();c++){
219
+                char ch = text.charAt(c);
220
+                int l = isChinese(ch)?2:1;
221
+                if (l==2){
222
+                    shorter++;
223
+                }
224
+                temp=temp+ch;
225
+
226
+                if(counter+l<width){
227
+                   counter = counter+l;
228
+                }else{
229
+                    splited.add(new ColumnSplitedString(shorter,temp));
230
+                    temp = "";
231
+                    counter=0;
232
+                    shorter=0;
233
+                }
234
+            }
235
+            if(temp.length()>0) {
236
+                splited.add(new ColumnSplitedString(shorter,temp));
237
+            }
238
+            int align = columnAligns.getInt(i);
239
+
240
+            List<String> formated = new ArrayList<String>();
241
+            for(ColumnSplitedString s: splited){
242
+                StringBuilder empty = new StringBuilder();
243
+                for(int w=0;w<(width+padding-s.getShorter());w++){
244
+                    empty.append(" ");
245
+                }
246
+                int startIdx = 0;
247
+                String ss = s.getStr();
248
+                if(align == 1 && ss.length()<(width-s.getShorter())){
249
+                    startIdx = (width-s.getShorter()-ss.length())/2;
250
+                    if(startIdx+ss.length()>width-s.getShorter()){
251
+                        startIdx--;
252
+                    }
253
+                    if(startIdx<0){
254
+                        startIdx=0;
255
+                    }
256
+                }else if(align==2 && ss.length()<(width-s.getShorter())){
257
+                    startIdx =width - s.getShorter()-ss.length();
258
+                }
259
+                Log.d(TAG,"empty.replace("+startIdx+","+(startIdx+ss.length())+","+ss+")");
260
+                empty.replace(startIdx,startIdx+ss.length(),ss);
261
+                formated.add(empty.toString());
262
+            }
263
+            table.add(formated);
264
+
265
+        }
266
+
267
+        /**  try to find the max row count of the table **/
268
+        int maxRowCount = 0;
269
+        for(int i=0;i<table.size()/*column count*/;i++){
270
+            List<String> rows = table.get(i); // row data in current column
271
+            if(rows.size()>maxRowCount){maxRowCount = rows.size();}// try to find the max row count;
272
+        }
273
+
274
+        /** loop table again to fill the rows **/
275
+        StringBuilder[] rowsToPrint = new StringBuilder[maxRowCount];
276
+        for(int column=0;column<table.size()/*column count*/;column++){
277
+            List<String> rows = table.get(column); // row data in current column
278
+            for(int row=0;row<maxRowCount;row++){
279
+                if(rowsToPrint[row]==null){
280
+                    rowsToPrint[row] = new StringBuilder();
281
+                }
282
+                if(row<rows.size()){
283
+                    //got the row of this column
284
+                    rowsToPrint[row].append(rows.get(row));
285
+                }else{
286
+                    int w =columnWidths.getInt(column);
287
+                    StringBuilder empty = new StringBuilder();
288
+                   for(int i=0;i<w;i++){
289
+                       empty.append(" ");
290
+                   }
291
+                    rowsToPrint[row].append(empty.toString());//Append spaces to ensure the format
292
+                }
293
+            }
294
+        }
295
+
296
+        /** loops the rows and print **/
297
+        for(int i=0;i<rowsToPrint.length;i++){
298
+            rowsToPrint[i].append("\n\r");//wrap line..
299
+            try {
300
+//                byte[] toPrint = rowsToPrint[i].toString().getBytes("UTF-8");
301
+//                String text = new String(toPrint, Charset.forName(encoding));
302
+                if (!sendDataByte(PrinterCommand.POS_Print_Text(rowsToPrint[i].toString(), encoding, codepage, widthTimes, heigthTimes, fonttype))) {
303
+                    promise.reject("COMMAND_NOT_SEND");
304
+                    return;
305
+                }
306
+            }catch (Exception e){
307
+                e.printStackTrace();
308
+            }
309
+        }
310
+        promise.resolve(null);
311
+    }
312
+
313
+    @ReactMethod
314
+    public void setWidth(int width) {
315
+        deviceWidth = width;
316
+    }
317
+
318
+    @ReactMethod
319
+    public void printPic(String base64encodeStr, @Nullable  ReadableMap options) {
320
+        int width = 0;
321
+        int leftPadding = 0;
322
+        if(options!=null){
323
+            width = options.hasKey("width") ? options.getInt("width") : 0;
324
+            leftPadding = options.hasKey("left")?options.getInt("left") : 0;
325
+        }
326
+
327
+        //cannot larger then devicesWith;
328
+        if(width > deviceWidth || width == 0){
329
+            width = deviceWidth;
330
+        }
331
+
332
+        byte[] bytes = Base64.decode(base64encodeStr, Base64.DEFAULT);
333
+        Bitmap mBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
334
+        int nMode = 0;
335
+        if (mBitmap != null) {
336
+            /**
337
+             * Parameters:
338
+             * mBitmap  要打印的图片
339
+             * nWidth   打印宽度(58和80)
340
+             * nMode    打印模式
341
+             * Returns: byte[]
342
+             */
343
+            byte[] data = PrintPicture.POS_PrintBMP(mBitmap, width, nMode, leftPadding);
344
+            //	SendDataByte(buffer);
345
+            sendDataByte(Command.ESC_Init);
346
+            sendDataByte(Command.LF);
347
+            sendDataByte(data);
348
+            // sendDataByte(PrinterCommand.POS_Set_PrtAndFeedPaper(30));
349
+            // sendDataByte(PrinterCommand.POS_Set_Cut(1));
350
+            sendDataByte(PrinterCommand.POS_Set_PrtInit());
351
+        }
352
+    }
353
+
354
+    @ReactMethod
355
+    public void cutPaper() {
356
+        sendDataByte(Command.ESC_Init);
357
+        sendDataByte(Command.LF);
358
+        sendDataByte(PrinterCommand.POS_Set_Cut(1));
359
+    }
360
+
361
+
362
+    @ReactMethod
363
+    public void selfTest(@Nullable Callback cb) {
364
+        boolean result = sendDataByte(PrinterCommand.POS_Set_PrtSelfTest());
365
+        if (cb != null) {
366
+            cb.invoke(result);
367
+        }
368
+    }
369
+
370
+    /**
371
+     * Rotate 90 degree, 0-no rotate, 1-rotate
372
+     * @param rotate  0-no rotate, 1-rotate
373
+     */
374
+    @ReactMethod
375
+    public void rotate(int rotate,final Promise promise) {
376
+        if(sendDataByte(PrinterCommand.POS_Set_Rotate(rotate))){
377
+            promise.resolve(null);
378
+        }else{
379
+            promise.reject("COMMAND_NOT_SEND");
380
+        }
381
+    }
382
+
383
+    @ReactMethod
384
+    public void setBlob(int weight,final Promise promise) {
385
+        if(sendDataByte(PrinterCommand.POS_Set_Bold(weight))){
386
+            promise.resolve(null);
387
+        }else{
388
+            promise.reject("COMMAND_NOT_SEND");
389
+        }
390
+    }
391
+
392
+    @ReactMethod
393
+    public void printQRCode(String content, int size, int correctionLevel, final Promise promise) {
394
+        try {
395
+            Log.i(TAG, "生成的文本:" + content);
396
+            // 把输入的文本转为二维码
397
+            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
398
+            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
399
+            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.forBits(correctionLevel));
400
+            BitMatrix bitMatrix = new QRCodeWriter().encode(content,
401
+                    BarcodeFormat.QR_CODE, size, size, hints);
402
+
403
+            int width = bitMatrix.getWidth();
404
+            int height = bitMatrix.getHeight();
405
+
406
+            System.out.println("w:" + width + "h:"
407
+                    + height);
408
+
409
+            int[] pixels = new int[width * height];
410
+            for (int y = 0; y < height; y++) {
411
+                for (int x = 0; x < width; x++) {
412
+                    if (bitMatrix.get(x, y)) {
413
+                        pixels[y * width + x] = 0xff000000;
414
+                    } else {
415
+                        pixels[y * width + x] = 0xffffffff;
416
+                    }
417
+                }
418
+            }
419
+
420
+            Bitmap bitmap = Bitmap.createBitmap(width, height,
421
+                    Bitmap.Config.ARGB_8888);
422
+
423
+            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
424
+
425
+            //TODO: may need a left padding to align center.
426
+            byte[] data = PrintPicture.POS_PrintBMP(bitmap, size, 0, 0);
427
+            if (sendDataByte(data)) {
428
+                promise.resolve(null);
429
+            } else {
430
+                promise.reject("COMMAND_NOT_SEND");
431
+            }
432
+        } catch (Exception e) {
433
+            promise.reject(e.getMessage(), e);
434
+        }
435
+    }
436
+
437
+    @ReactMethod
438
+    public void printBarCode(String str, int nType, int nWidthX, int nHeight,
439
+                             int nHriFontType, int nHriFontPosition) {
440
+        byte[] command = PrinterCommand.getBarCodeCommand(str, nType, nWidthX, nHeight, nHriFontType, nHriFontPosition);
441
+        sendDataByte(command);
442
+    }
443
+
444
+    private boolean sendDataByte(byte[] data) {
445
+        if (data==null || mService.getState() != BluetoothService.STATE_CONNECTED) {
446
+            return false;
447
+        }
448
+        mService.write(data);
449
+        return true;
450
+    }
451
+
452
+    // 根据Unicode编码完美的判断中文汉字和符号
453
+    private static boolean isChinese(char c) {
454
+        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
455
+        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
456
+                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
457
+                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
458
+                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
459
+                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
460
+                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
461
+                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
462
+            return true;
463
+        }
464
+        return false;
465
+    }
466
+
467
+    @Override
468
+    public void onBluetoothServiceStateChanged(int state, Map<String, Object> boundle) {
469
+
470
+    }
471
+
472
+    /****************************************************************************************************/
473
+
474
+    private static class ColumnSplitedString{
475
+        private int shorter;
476
+        private String str;
477
+
478
+        public ColumnSplitedString(int shorter, String str) {
479
+            this.shorter = shorter;
480
+            this.str = str;
481
+        }
482
+
483
+        public int getShorter() {
484
+            return shorter;
485
+        }
486
+
487
+        public String getStr() {
488
+            return str;
489
+        }
490
+    }
491
+
492
+}

+ 154
- 0
android/src/main/java/cn/jystudio/bluetooth/escpos/command/sdk/Command.java View File

@@ -0,0 +1,154 @@
1
+package cn.jystudio.bluetooth.escpos.command.sdk;
2
+
3
+public class Command {
4
+
5
+	private static final byte ESC = 0x1B;
6
+	private static final byte FS = 0x1C;
7
+	private static final byte GS = 0x1D;
8
+	private static final byte US = 0x1F;
9
+	private static final byte DLE = 0x10;
10
+	private static final byte DC4 = 0x14;
11
+	private static final byte DC1 = 0x11;
12
+	private static final byte SP = 0x20;
13
+	private static final byte NL = 0x0A;
14
+	private static final byte FF = 0x0C;
15
+	public static final byte PIECE = (byte) 0xFF;
16
+	public static final byte NUL = (byte) 0x00;
17
+	
18
+	//打印机初始化
19
+	public static byte[] ESC_Init = new byte[] {ESC, '@' };
20
+	
21
+	/**
22
+	 * 打印命令
23
+	 */
24
+	//打印并换行
25
+	public static byte[] LF = new byte[] {NL};
26
+	
27
+	//打印并走纸
28
+	public static byte[] ESC_J = new byte[] {ESC, 'J', 0x00 };
29
+	public static byte[] ESC_d = new byte[] {ESC, 'd', 0x00 };
30
+	
31
+	//打印自检页
32
+	public static byte[] US_vt_eot = new byte[] {US, DC1, 0x04 };
33
+	
34
+	 //蜂鸣指令
35
+    public static byte[] ESC_B_m_n = new byte[] {ESC, 'B', 0x00, 0x00 };
36
+	
37
+    //切刀指令
38
+    public static byte[] GS_V_n = new byte[] {GS, 'V', 0x00 };
39
+    public static byte[] GS_V_m_n = new byte[] {GS, 'V', 'B', 0x00 };
40
+    public static byte[] GS_i = new byte[] {ESC, 'i' };
41
+    public static byte[] GS_m = new byte[] {ESC, 'm' };
42
+	
43
+	/**
44
+	 * 字符设置命令
45
+	 */
46
+	//设置字符右间距
47
+	public static byte[] ESC_SP = new byte[] {ESC, SP, 0x00 };
48
+	
49
+	//设置字符打印字体格式
50
+	public static byte[] ESC_ExclamationMark = new byte[] {ESC, '!', 0x00 };
51
+	
52
+	//设置字体倍高倍宽
53
+	public static byte[] GS_ExclamationMark = new byte[] {GS, '!', 0x00 };
54
+	
55
+	//设置反显打印
56
+	public static byte[] GS_B = new byte[] {GS, 'B', 0x00 };
57
+	
58
+	//取消/选择90度旋转打印
59
+	public static byte[] ESC_V = new byte[] {ESC, 'V', 0x00 };
60
+	
61
+	//选择字体字型(主要是ASCII码)
62
+	public static byte[] ESC_M = new byte[] {ESC, 'M', 0x00 };
63
+	
64
+	//选择/取消加粗指令
65
+	public static byte[] ESC_G = new byte[] {ESC, 'G', 0x00 };
66
+	public static byte[] ESC_E = new byte[] {ESC, 'E', 0x00 };
67
+	
68
+	//选择/取消倒置打印模式
69
+	public static byte[] ESC_LeftBrace = new byte[] {ESC, '{', 0x00 };
70
+	
71
+	//设置下划线点高度(字符)
72
+	public static byte[] ESC_Minus = new byte[] {ESC, 45, 0x00 };
73
+	
74
+	//字符模式
75
+	public static byte[] FS_dot = new byte[] {FS, 46 };
76
+	
77
+	//汉字模式
78
+	public static byte[] FS_and = new byte[] {FS, '&' };
79
+	
80
+	//设置汉字打印模式
81
+	public static byte[] FS_ExclamationMark = new byte[] {FS, '!', 0x00 };
82
+	
83
+	//设置下划线点高度(汉字)
84
+	public static byte[] FS_Minus = new byte[] {FS, 45, 0x00 };
85
+	
86
+	//设置汉字左右间距
87
+	public static byte[] FS_S = new byte[] {FS, 'S', 0x00, 0x00 };
88
+	
89
+	//选择字符代码页
90
+	public static byte[] ESC_t = new byte[] {ESC, 't', 0x00 };
91
+	
92
+	/**
93
+	 * 格式设置指令
94
+	 */
95
+	//设置默认行间距
96
+	public static byte[] ESC_Two = new byte[] {ESC, 50}; 
97
+	
98
+	//设置行间距
99
+	public static byte[] ESC_Three = new byte[] {ESC, 51, 0x00 };
100
+	
101
+	//设置对齐模式
102
+	public static byte[] ESC_Align = new byte[] {ESC, 'a', 0x00 };
103
+	
104
+	//设置左边距
105
+	public static byte[] GS_LeftSp = new byte[] {GS, 'L', 0x00 , 0x00 };
106
+	
107
+	//设置绝对打印位置
108
+	//将当前位置设置到距离行首(nL + nH x 256)处。
109
+	//如果设置位置在指定打印区域外,该命令被忽略
110
+	public static byte[] ESC_Absolute  = new byte[] {ESC, '$', 0x00, 0x00 };
111
+	
112
+	//设置相对打印位置
113
+	public static byte[] ESC_Relative = new byte[] {ESC, 92, 0x00, 0x00 };
114
+	
115
+	//设置打印区域宽度
116
+	public static byte[] GS_W = new byte[] {GS, 'W', 0x00, 0x00 };
117
+
118
+	/**
119
+	 * 状态指令
120
+	 */
121
+	//实时状态传送指令
122
+	public static byte[] DLE_eot = new byte[] {DLE, 0x04, 0x00 };
123
+	
124
+	//实时弹钱箱指令
125
+	public static byte[] DLE_DC4 = new byte[] {DLE, DC4, 0x00, 0x00, 0x00 };
126
+	
127
+	//标准弹钱箱指令
128
+	public static byte[] ESC_p = new byte[] {ESC, 'F', 0x00, 0x00, 0x00 };
129
+	
130
+	/**
131
+	 * 条码设置指令
132
+	 */
133
+	//选择HRI打印方式
134
+	public static byte[] GS_H = new byte[] {GS, 'H', 0x00 };
135
+	
136
+	//设置条码高度
137
+	public static byte[] GS_h = new byte[] {GS, 'h', (byte) 0xa2 };
138
+	
139
+	//设置条码宽度
140
+	public static byte[] GS_w = new byte[] {GS, 'w', 0x00 };
141
+	
142
+	//设置HRI字符字体字型
143
+	public static byte[] GS_f = new byte[] {GS, 'f', 0x00 };
144
+	
145
+	//条码左偏移指令
146
+	public static byte[] GS_x = new byte[] {GS, 'x', 0x00 };
147
+	
148
+	//打印条码指令
149
+	public static byte[] GS_k = new byte[] {GS, 'k', 'A', FF };
150
+
151
+	//二维码相关指令		
152
+    public static byte[] GS_k_m_v_r_nL_nH = new byte[] { ESC, 'Z', 0x03, 0x03, 0x08, 0x00, 0x00 };
153
+	
154
+}

+ 281
- 0
android/src/main/java/cn/jystudio/bluetooth/escpos/command/sdk/PrintPicture.java View File

@@ -0,0 +1,281 @@
1
+package cn.jystudio.bluetooth.escpos.command.sdk;
2
+
3
+import android.graphics.*;
4
+
5
+import java.io.UnsupportedEncodingException;
6
+
7
+public class PrintPicture {
8
+    private static int[] p0 = new int[]{0, 128};
9
+    private static int[] p1 = new int[]{0, 64};
10
+    private static int[] p2 = new int[]{0, 32};
11
+    private static int[] p3 = new int[]{0, 16};
12
+    private static int[] p4 = new int[]{0, 8};
13
+    private static int[] p5 = new int[]{0, 4};
14
+    private static int[] p6 = new int[]{0, 2};
15
+    private static int[][] Floyd16x16 = new int[][]{{0, 128, 32, 160, 8, 136, 40, 168, 2, 130, 34, 162, 10, 138, 42, 170}, {192, 64, 224, 96, 200, 72, 232, 104, 194, 66, 226, 98, 202, 74, 234, 106}, {48, 176, 16, 144, 56, 184, 24, 152, 50, 178, 18, 146, 58, 186, 26, 154}, {240, 112, 208, 80, 248, 120, 216, 88, 242, 114, 210, 82, 250, 122, 218, 90}, {12, 140, 44, 172, 4, 132, 36, 164, 14, 142, 46, 174, 6, 134, 38, 166}, {204, 76, 236, 108, 196, 68, 228, 100, 206, 78, 238, 110, 198, 70, 230, 102}, {60, 188, 28, 156, 52, 180, 20, 148, 62, 190, 30, 158, 54, 182, 22, 150}, {252, 124, 220, 92, 244, 116, 212, 84, 254, 126, 222, 94, 246, 118, 214, 86}, {3, 131, 35, 163, 11, 139, 43, 171, 1, 129, 33, 161, 9, 137, 41, 169}, {195, 67, 227, 99, 203, 75, 235, 107, 193, 65, 225, 97, 201, 73, 233, 105}, {51, 179, 19, 147, 59, 187, 27, 155, 49, 177, 17, 145, 57, 185, 25, 153}, {243, 115, 211, 83, 251, 123, 219, 91, 241, 113, 209, 81, 249, 121, 217, 89}, {15, 143, 47, 175, 7, 135, 39, 167, 13, 141, 45, 173, 5, 133, 37, 165}, {207, 79, 239, 111, 199, 71, 231, 103, 205, 77, 237, 109, 197, 69, 229, 101}, {63, 191, 31, 159, 55, 183, 23, 151, 61, 189, 29, 157, 53, 181, 21, 149}, {254, 127, 223, 95, 247, 119, 215, 87, 253, 125, 221, 93, 245, 117, 213, 85}};
16
+
17
+
18
+    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
19
+        int width = bitmap.getWidth();
20
+        int height = bitmap.getHeight();
21
+        float scaleWidth = (float) w / (float) width;
22
+        float scaleHeight = (float) h / (float) height;
23
+        Matrix matrix = new Matrix();
24
+        matrix.postScale(scaleWidth, scaleHeight);
25
+        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
26
+        return resizedBitmap;
27
+    }
28
+
29
+    public static Bitmap pad(Bitmap Src, int padding_x, int padding_y) {
30
+        Bitmap outputimage = Bitmap.createBitmap(Src.getWidth() + padding_x,Src.getHeight() + padding_y, Bitmap.Config.ARGB_8888);
31
+        Canvas can = new Canvas(outputimage);
32
+        can.drawARGB(255,255,255,255); //This represents White color
33
+        can.drawBitmap(Src, padding_x, padding_y, null);
34
+        return outputimage;
35
+    }
36
+
37
+
38
+    /**
39
+     * 打印位图函数
40
+     * 此函数是将一行作为一个图片打印,这样处理不容易出错
41
+     *
42
+     * @param mBitmap
43
+     * @param nWidth
44
+     * @param nMode
45
+     * @return
46
+     */
47
+    public static byte[] POS_PrintBMP(Bitmap mBitmap, int nWidth, int nMode, int leftPadding) {
48
+        // 先转黑白,再调用函数缩放位图
49
+        int width = ((nWidth + 7) / 8) * 8;
50
+        int height = mBitmap.getHeight() * width / mBitmap.getWidth();
51
+        height = ((height + 7) / 8) * 8;
52
+        int left = leftPadding == 0 ? 0 : ((leftPadding+7) / 8) * 8;
53
+
54
+        Bitmap rszBitmap = mBitmap;
55
+        if (mBitmap.getWidth() != width) {
56
+            rszBitmap = Bitmap.createScaledBitmap(mBitmap, width, height, true);
57
+        }
58
+
59
+        Bitmap grayBitmap = toGrayscale(rszBitmap);
60
+        if(left>0){
61
+            grayBitmap = pad(grayBitmap,left,0);
62
+        }
63
+
64
+        byte[] dithered = thresholdToBWPic(grayBitmap);
65
+
66
+        byte[] data = eachLinePixToCmd(dithered, width+left, nMode);
67
+
68
+        return data;
69
+    }
70
+
71
+    /**
72
+     * 使用下传位图打印图片
73
+     * 先收完再打印
74
+     *
75
+     * @param bmp
76
+     * @return
77
+     */
78
+    public static byte[] Print_1D2A(Bitmap bmp) {
79
+
80
+			/*
81
+			 * 使用下传位图打印图片
82
+			 * 先收完再打印
83
+			 */
84
+        int width = bmp.getWidth();
85
+        int height = bmp.getHeight();
86
+        byte data[] = new byte[1024 * 10];
87
+        data[0] = 0x1D;
88
+        data[1] = 0x2A;
89
+        data[2] = (byte) ((width - 1) / 8 + 1);
90
+        data[3] = (byte) ((height - 1) / 8 + 1);
91
+        byte k = 0;
92
+        int position = 4;
93
+        int i;
94
+        int j;
95
+        byte temp = 0;
96
+        for (i = 0; i < width; i++) {
97
+            for (j = 0; j < height; j++) {
98
+                if (bmp.getPixel(i, j) != -1) {
99
+                    temp |= (0x80 >> k);
100
+                } // end if
101
+                k++;
102
+                if (k == 8) {
103
+                    data[position++] = temp;
104
+                    temp = 0;
105
+                    k = 0;
106
+                } // end if k
107
+            }// end for j
108
+            if (k % 8 != 0) {
109
+                data[position++] = temp;
110
+                temp = 0;
111
+                k = 0;
112
+            }
113
+
114
+        }
115
+
116
+        if (width % 8 != 0) {
117
+            i = height / 8;
118
+            if (height % 8 != 0) i++;
119
+            j = 8 - (width % 8);
120
+            for (k = 0; k < i * j; k++) {
121
+                data[position++] = 0;
122
+            }
123
+        }
124
+        return data;
125
+    }
126
+
127
+    public static Bitmap toGrayscale(Bitmap bmpOriginal) {
128
+        int width, height;
129
+        height = bmpOriginal.getHeight();
130
+        width = bmpOriginal.getWidth();
131
+
132
+        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
133
+        Canvas c = new Canvas(bmpGrayscale);
134
+        Paint paint = new Paint();
135
+        ColorMatrix cm = new ColorMatrix();
136
+        cm.setSaturation(0);
137
+        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
138
+        paint.setColorFilter(f);
139
+        c.drawBitmap(bmpOriginal, 0, 0, paint);
140
+        return bmpGrayscale;
141
+    }
142
+
143
+    public static byte[] thresholdToBWPic(Bitmap mBitmap) {
144
+        int[] pixels = new int[mBitmap.getWidth() * mBitmap.getHeight()];
145
+        byte[] data = new byte[mBitmap.getWidth() * mBitmap.getHeight()];
146
+        mBitmap.getPixels(pixels, 0, mBitmap.getWidth(), 0, 0, mBitmap.getWidth(), mBitmap.getHeight());
147
+        format_K_threshold(pixels, mBitmap.getWidth(), mBitmap.getHeight(), data);
148
+        return data;
149
+    }
150
+
151
+    private static void format_K_threshold(int[] orgpixels, int xsize, int ysize, byte[] despixels) {
152
+        int graytotal = 0;
153
+        boolean grayave = true;
154
+        int k = 0;
155
+
156
+        int i;
157
+        int j;
158
+        int gray;
159
+        for (i = 0; i < ysize; ++i) {
160
+            for (j = 0; j < xsize; ++j) {
161
+                gray = orgpixels[k] & 255;
162
+                graytotal += gray;
163
+                ++k;
164
+            }
165
+        }
166
+
167
+        int var10 = graytotal / ysize / xsize;
168
+        k = 0;
169
+
170
+        for (i = 0; i < ysize; ++i) {
171
+            for (j = 0; j < xsize; ++j) {
172
+                gray = orgpixels[k] & 255;
173
+                if (gray > var10) {
174
+                    despixels[k] = 0;
175
+                } else {
176
+                    despixels[k] = 1;
177
+                }
178
+
179
+                ++k;
180
+            }
181
+        }
182
+
183
+    }
184
+
185
+    public static byte[] eachLinePixToCmd(byte[] src, int nWidth, int nMode) {
186
+        int nHeight = src.length / nWidth;
187
+        int nBytesPerLine = nWidth / 8;
188
+        byte[] data = new byte[nHeight * (8 + nBytesPerLine)];
189
+        boolean offset = false;
190
+        int k = 0;
191
+
192
+        for (int i = 0; i < nHeight; ++i) {
193
+            int var10 = i * (8 + nBytesPerLine);
194
+            //GS v 0 m xL xH yL yH d1....dk 打印光栅位图
195
+            data[var10 + 0] = 29;//GS
196
+            data[var10 + 1] = 118;//v
197
+            data[var10 + 2] = 48;//0
198
+            data[var10 + 3] = (byte) (nMode & 1);
199
+            data[var10 + 4] = (byte) (nBytesPerLine % 256);//xL
200
+            data[var10 + 5] = (byte) (nBytesPerLine / 256);//xH
201
+            data[var10 + 6] = 1;//yL
202
+            data[var10 + 7] = 0;//yH
203
+
204
+            for (int j = 0; j < nBytesPerLine; ++j) {
205
+                data[var10 + 8 + j] = (byte) (p0[src[k]] + p1[src[k + 1]] + p2[src[k + 2]] + p3[src[k + 3]] + p4[src[k + 4]] + p5[src[k + 5]] + p6[src[k + 6]] + src[k + 7]);
206
+                k += 8;
207
+            }
208
+        }
209
+
210
+        return data;
211
+    }
212
+
213
+    public static byte[] pixToTscCmd(byte[] src) {
214
+        byte[] data = new byte[src.length / 8];
215
+        int k = 0;
216
+
217
+        for (int j = 0; k < data.length; ++k) {
218
+            byte temp = (byte) (p0[src[j]] + p1[src[j + 1]] + p2[src[j + 2]] + p3[src[j + 3]] + p4[src[j + 4]] + p5[src[j + 5]] + p6[src[j + 6]] + src[j + 7]);
219
+            data[k] = (byte) (~temp);
220
+            j += 8;
221
+        }
222
+
223
+        return data;
224
+    }
225
+    public static byte[] pixToEscRastBitImageCmd(byte[] src) {
226
+        byte[] data = new byte[src.length / 8];
227
+        int i = 0;
228
+
229
+        for (int k = 0; i < data.length; ++i) {
230
+            data[i] = (byte) (p0[src[k]] + p1[src[k + 1]] + p2[src[k + 2]] + p3[src[k + 3]] + p4[src[k + 4]] + p5[src[k + 5]] + p6[src[k + 6]] + src[k + 7]);
231
+            k += 8;
232
+        }
233
+
234
+        return data;
235
+    }
236
+    public static byte[] pixToEscNvBitImageCmd(byte[] src, int width, int height) {
237
+        byte[] data = new byte[src.length / 8 + 4];
238
+        data[0] = (byte) (width / 8 % 256);
239
+        data[1] = (byte) (width / 8 / 256);
240
+        data[2] = (byte) (height / 8 % 256);
241
+        data[3] = (byte) (height / 8 / 256);
242
+        boolean k = false;
243
+
244
+        for (int i = 0; i < width; ++i) {
245
+            int var7 = 0;
246
+
247
+            for (int j = 0; j < height / 8; ++j) {
248
+                data[4 + j + i * height / 8] = (byte) (p0[src[i + var7]] + p1[src[i + var7 + 1 * width]] + p2[src[i + var7 + 2 * width]] + p3[src[i + var7 + 3 * width]] + p4[src[i + var7 + 4 * width]] + p5[src[i + var7 + 5 * width]] + p6[src[i + var7 + 6 * width]] + src[i + var7 + 7 * width]);
249
+                var7 += 8 * width;
250
+            }
251
+        }
252
+
253
+        return data;
254
+    }
255
+    public static byte[] bitmapToBWPix(Bitmap mBitmap) {
256
+        int[] pixels = new int[mBitmap.getWidth() * mBitmap.getHeight()];
257
+        byte[] data = new byte[mBitmap.getWidth() * mBitmap.getHeight()];
258
+        Bitmap grayBitmap = toGrayscale(mBitmap);
259
+        grayBitmap.getPixels(pixels, 0, mBitmap.getWidth(), 0, 0, mBitmap.getWidth(), mBitmap.getHeight());
260
+        format_K_dither16x16(pixels, grayBitmap.getWidth(), grayBitmap.getHeight(), data);
261
+        return data;
262
+    }
263
+
264
+    private static void format_K_dither16x16(int[] orgpixels, int xsize, int ysize, byte[] despixels) {
265
+        int k = 0;
266
+
267
+        for (int y = 0; y < ysize; ++y) {
268
+            for (int x = 0; x < xsize; ++x) {
269
+                if ((orgpixels[k] & 255) > Floyd16x16[x & 15][y & 15]) {
270
+                    despixels[k] = 0;
271
+                } else {
272
+                    despixels[k] = 1;
273
+                }
274
+
275
+                ++k;
276
+            }
277
+        }
278
+
279
+    }
280
+
281
+}

+ 500
- 0
android/src/main/java/cn/jystudio/bluetooth/escpos/command/sdk/PrinterCommand.java View File

@@ -0,0 +1,500 @@
1
+package cn.jystudio.bluetooth.escpos.command.sdk;
2
+
3
+import java.io.UnsupportedEncodingException;
4
+import java.util.Arrays;
5
+
6
+public class PrinterCommand {
7
+
8
+    /**
9
+     * 打印机初始化
10
+     *
11
+     * @return
12
+     */
13
+    public static byte[] POS_Set_PrtInit() {
14
+        return Command.ESC_Init;
15
+    }
16
+
17
+    /**
18
+     * 打印并换行
19
+     *
20
+     * @return
21
+     */
22
+    public static byte[] POS_Set_LF() {
23
+        return Command.LF;
24
+    }
25
+
26
+    /**
27
+     * 打印并走纸 (0~255)
28
+     *
29
+     * @param feed
30
+     * @return
31
+     */
32
+    public static byte[] POS_Set_PrtAndFeedPaper(int feed) {
33
+        if (feed > 255 | feed < 0) return null;
34
+
35
+        byte[] data = Arrays.copyOf(Command.ESC_J, Command.ESC_J.length);
36
+        data[2] = (byte) feed;
37
+        return data;
38
+    }
39
+
40
+    /**
41
+     * 打印自检页
42
+     *
43
+     * @return
44
+     */
45
+    public static byte[] POS_Set_PrtSelfTest() {
46
+        return Command.US_vt_eot;
47
+    }
48
+
49
+    /**
50
+     * 蜂鸣指令
51
+     *
52
+     * @param m 蜂鸣次数
53
+     * @param t 每次蜂鸣的时间
54
+     * @return
55
+     */
56
+    public static byte[] POS_Set_Beep(int m, int t) {
57
+
58
+        if ((m < 1 || m > 9) | (t < 1 || t > 9)) return null;
59
+
60
+        byte[] data = Arrays.copyOf(Command.ESC_B_m_n, Command.ESC_B_m_n.length);
61
+        data[2] = (byte) m;
62
+        data[3] = (byte) t;
63
+        return data;
64
+    }
65
+
66
+    /**
67
+     * 切刀指令(走纸到切刀位置并切纸)
68
+     *
69
+     * @param cut 0~255
70
+     * @return
71
+     */
72
+    public static byte[] POS_Set_Cut(int cut) {
73
+        if (cut > 255 | cut < 0) return null;
74
+
75
+        byte[] data = Arrays.copyOf(Command.GS_V_m_n, Command.GS_V_m_n.length);
76
+        data[3] = (byte) cut;
77
+        return data;
78
+    }
79
+
80
+    /**
81
+     * 钱箱指令
82
+     *
83
+     * @param nMode
84
+     * @param nTime1
85
+     * @param nTime2
86
+     * @return
87
+     */
88
+    public static byte[] POS_Set_Cashbox(int nMode, int nTime1, int nTime2) {
89
+
90
+        if ((nMode < 0 || nMode > 1) | nTime1 < 0 | nTime1 > 255 | nTime2 < 0 | nTime2 > 255) return null;
91
+
92
+        byte[] data = Arrays.copyOf(Command.ESC_p, Command.ESC_p.length);
93
+        data[2] = (byte) nMode;
94
+        data[3] = (byte) nTime1;
95
+        data[4] = (byte) nTime2;
96
+        return data;
97
+    }
98
+
99
+    /**
100
+     * 设置绝对打印位置
101
+     *
102
+     * @param absolute
103
+     * @return
104
+     */
105
+    public static byte[] POS_Set_Absolute(int absolute) {
106
+        if (absolute > 65535 | absolute < 0) return null;
107
+
108
+        byte[] data = Arrays.copyOf(Command.ESC_Absolute, Command.ESC_Absolute.length);
109
+        data[2] = (byte) (absolute % 0x100);
110
+        data[3] = (byte) (absolute / 0x100);
111
+        return data;
112
+    }
113
+
114
+    /**
115
+     * 设置相对打印位置
116
+     *
117
+     * @param relative
118
+     * @return
119
+     */
120
+    public static byte[] POS_Set_Relative(int relative) {
121
+        if (relative < 0 | relative > 65535) return null;
122
+
123
+        byte[] data = Arrays.copyOf(Command.ESC_Relative, Command.ESC_Relative.length);
124
+        data[2] = (byte) (relative % 0x100);
125
+        data[3] = (byte) (relative / 0x100);
126
+        return data;
127
+    }
128
+
129
+    /**
130
+     * 设置左边距
131
+     *
132
+     * @param left
133
+     * @return
134
+     */
135
+    public static byte[] POS_Set_LeftSP(int left) {
136
+        if (left > 255 | left < 0) return null;
137
+
138
+        byte[] data = Arrays.copyOf(Command.GS_LeftSp, Command.GS_LeftSp.length);
139
+        data[2] = (byte) (left % 0x100);
140
+        data[3] = (byte) (left / 0x100);
141
+        return data;
142
+    }
143
+
144
+    /**
145
+     * 设置对齐模式
146
+     *
147
+     * @param align
148
+     * @return
149
+     */
150
+    public static byte[] POS_S_Align(int align) {
151
+        if ((align < 0 || align > 2) && (align < 48 || align > 50)) return null;
152
+
153
+        byte[] data = Arrays.copyOf(Command.ESC_Align, Command.ESC_Align.length);
154
+        data[2] = (byte) align;
155
+        return data;
156
+    }
157
+
158
+    /**
159
+     * 设置打印区域宽度
160
+     *
161
+     * @param width
162
+     * @return
163
+     */
164
+    public static byte[] POS_Set_PrintWidth(int width) {
165
+        if (width < 0 | width > 255) return null;
166
+
167
+        byte[] data = Arrays.copyOf(Command.GS_W, Command.GS_W.length);
168
+        data[2] = (byte) (width % 0x100);
169
+        data[3] = (byte) (width / 0x100);
170
+        return data;
171
+    }
172
+
173
+    /**
174
+     * 设置默认行间距
175
+     *
176
+     * @return
177
+     */
178
+    public static byte[] POS_Set_DefLineSpace() {
179
+        return Command.ESC_Two;
180
+    }
181
+
182
+    /**
183
+     * 设置行间距
184
+     *
185
+     * @param space
186
+     * @return
187
+     */
188
+    public static byte[] POS_Set_LineSpace(int space) {
189
+        if (space < 0 | space > 255) return null;
190
+
191
+        byte[] data = Arrays.copyOf(Command.ESC_Three, Command.ESC_Three.length);
192
+        data[2] = (byte) space;
193
+        return data;
194
+    }
195
+
196
+    /**
197
+     * 选择字符代码页
198
+     *
199
+     * @param page
200
+     * @return
201
+     */
202
+    public static byte[] POS_Set_CodePage(int page) {
203
+        if (page > 255) return null;
204
+
205
+        byte[] data = Arrays.copyOf(Command.ESC_t, Command.ESC_t.length);
206
+        data[2] = (byte) page;
207
+        return data;
208
+    }
209
+
210
+    /**
211
+     * 打印文本文档
212
+     *
213
+     * @param pszString    要打印的字符串
214
+     * @param encoding     打印字符对应编码
215
+     * @param codepage     设置代码页(0--255)
216
+     * @param nWidthTimes  倍宽(0--4)
217
+     * @param nHeightTimes 倍高(0--4)
218
+     * @param nFontType    字体类型(只对Ascii码有效)(0,1 48,49)
219
+     */
220
+    public static byte[] POS_Print_Text(String pszString, String encoding, int codepage,
221
+                                        int nWidthTimes, int nHeightTimes, int nFontType) {
222
+        if (codepage < 0 || codepage > 255 || pszString == null || "".equals(pszString) || pszString.length() < 1) {
223
+            return null;
224
+        }
225
+
226
+        byte[] pbString = null;
227
+        try {
228
+            pbString = pszString.getBytes(encoding);
229
+        } catch (UnsupportedEncodingException e) {
230
+            return null;
231
+        }
232
+
233
+        byte[] intToWidth = {0x00, 0x10, 0x20, 0x30};
234
+        byte[] intToHeight = {0x00, 0x01, 0x02, 0x03};
235
+        byte[] gsExclamationMark = Arrays.copyOf(Command.GS_ExclamationMark, Command.GS_ExclamationMark.length);
236
+        gsExclamationMark[2] = (byte) (intToWidth[nWidthTimes] + intToHeight[nHeightTimes]);
237
+        byte[] escT = Arrays.copyOf(Command.ESC_t, Command.ESC_t.length);
238
+        escT[2] = (byte) codepage;
239
+        byte[] escM = Arrays.copyOf(Command.ESC_M, Command.ESC_M.length);
240
+        escM[2] = (byte) nFontType;
241
+        byte[] data = null;
242
+        if (codepage == 0) {
243
+            data = concatAll(gsExclamationMark, escT, Command.FS_and, escM, pbString);
244
+        } else {
245
+            data = concatAll(gsExclamationMark, escT, Command.FS_dot, escM, pbString);
246
+        }
247
+        return data;
248
+    }
249
+
250
+    /**
251
+     * 加粗指令(最低位为1有效)
252
+     *
253
+     * @param bold
254
+     * @return
255
+     */
256
+    public static byte[] POS_Set_Bold(int bold) {
257
+        byte[] escE = Arrays.copyOf(Command.ESC_E, Command.ESC_E.length);
258
+        byte[] escG = Arrays.copyOf(Command.ESC_G, Command.ESC_G.length);
259
+
260
+        escE[2] = (byte) bold;
261
+        escG[2] = (byte) bold;
262
+        return concatAll(escE, escG);
263
+    }
264
+
265
+    /**
266
+     * 设置倒置打印模式(当最低位为1时有效)
267
+     *
268
+     * @param brace
269
+     * @return
270
+     */
271
+    public static byte[] POS_Set_LeftBrace(int brace) {
272
+        byte[] data = Arrays.copyOf(Command.ESC_LeftBrace, Command.ESC_LeftBrace.length);
273
+        data[2] = (byte) brace;
274
+        return data;
275
+    }
276
+
277
+    /**
278
+     * 设置下划线
279
+     *
280
+     * @param line
281
+     * @return
282
+     */
283
+    public static byte[] POS_Set_UnderLine(int line) {
284
+        if ((line < 0 || line > 2)) return null;
285
+        byte[] escMins = Arrays.copyOf(Command.ESC_Minus, Command.ESC_Minus.length);
286
+        escMins[2] = (byte) line;
287
+        byte[] fsMinus = Arrays.copyOf(Command.FS_Minus, Command.FS_Minus.length);
288
+        fsMinus[2] = (byte) line;
289
+        return concatAll(escMins, fsMinus);
290
+    }
291
+
292
+    /**
293
+     * 选择字体大小(倍高倍宽)
294
+     *
295
+     * @param size1
296
+     * @param size2
297
+     * @return
298
+     */
299
+    public static byte[] POS_Set_FontSize(int size1, int size2) {
300
+        if (size1 < 0 | size1 > 7 | size2 < 0 | size2 > 7) return null;
301
+        byte[] intToWidth = {0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70};
302
+        byte[] intToHeight = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
303
+        byte[] data = Arrays.copyOf(Command.GS_ExclamationMark, Command.GS_ExclamationMark.length);
304
+        data[2] = (byte) (intToWidth[size1] + intToHeight[size2]);
305
+        return data;
306
+    }
307
+
308
+    /**
309
+     * 设置反显打印
310
+     *
311
+     * @param inverse
312
+     * @return
313
+     */
314
+    public static byte[] POS_Set_Inverse(int inverse) {
315
+        byte[] data = Arrays.copyOf(Command.GS_B, Command.GS_B.length);
316
+        data[2] = (byte) inverse;
317
+        return data;
318
+    }
319
+
320
+    /**
321
+     * 设置旋转90度打印
322
+     *
323
+     * @param rotate
324
+     * @return
325
+     */
326
+    public static byte[] POS_Set_Rotate(int rotate) {
327
+        if (rotate < 0 || rotate > 1) return null;
328
+
329
+        byte[] data = Arrays.copyOf(Command.ESC_V, Command.ESC_V.length);
330
+        data[2] = (byte) rotate;
331
+        return data;
332
+    }
333
+
334
+    /**
335
+     * 选择字体字型
336
+     *
337
+     * @param font
338
+     * @return
339
+     */
340
+    public static byte[] POS_Set_ChoseFont(int font) {
341
+        if (font > 1 | font < 0) return null;
342
+
343
+        byte[] data = Arrays.copyOf(Command.ESC_M, Command.ESC_M.length);
344
+        data[2] = (byte) font;
345
+        return data;
346
+
347
+    }
348
+
349
+//***********************************以下函数为公开函数***********************************************************//
350
+
351
+    /**
352
+     * 二维码打印函数
353
+     *
354
+     * @param str                   打印二维码数据
355
+     * @param nVersion              二维码类型
356
+     * @param nErrorCorrectionLevel 纠错级别
357
+     * @param nMagnification        放大倍数
358
+     * @return
359
+     */
360
+    public static byte[] getQRCodeCommand(String str, int nVersion, int nErrorCorrectionLevel,
361
+                                       int nMagnification) {
362
+
363
+        if (nVersion < 0 | nVersion > 19 | nErrorCorrectionLevel < 0 | nErrorCorrectionLevel > 3
364
+                | nMagnification < 1 | nMagnification > 8) {
365
+            return null;
366
+        }
367
+
368
+        byte[] bCodeData = null;
369
+        try {
370
+            bCodeData = str.getBytes("GBK");
371
+
372
+        } catch (UnsupportedEncodingException e) {
373
+            e.printStackTrace();
374
+            return null;
375
+        }
376
+
377
+        byte[] command = new byte[bCodeData.length + 7];
378
+
379
+        command[0] = 27;
380
+        command[1] = 90;
381
+        command[2] = ((byte) nVersion);
382
+        command[3] = ((byte) nErrorCorrectionLevel);
383
+        command[4] = ((byte) nMagnification);
384
+        command[5] = (byte) (bCodeData.length & 0xff);
385
+        command[6] = (byte) ((bCodeData.length & 0xff00) >> 8);
386
+        System.arraycopy(bCodeData, 0, command, 7, bCodeData.length);
387
+
388
+        return command;
389
+    }
390
+
391
+    /**
392
+     * 打印一维条码
393
+     *
394
+     * @param str              打印条码字符
395
+     * @param nType            条码类型(65~73)
396
+     * @param nWidthX          条码宽度
397
+     * @param nHeight          条码高度
398
+     * @param nHriFontType     HRI字型
399
+     * @param nHriFontPosition HRI位置
400
+     * @return
401
+     */
402
+    public static byte[] getBarCodeCommand(String str, int nType, int nWidthX, int nHeight,
403
+                                           int nHriFontType, int nHriFontPosition) {
404
+
405
+        if (nType < 0x41 | nType > 0x49 | nWidthX < 2 | nWidthX > 6
406
+                | nHeight < 1 | nHeight > 255 | str.length() == 0)
407
+            return null;
408
+
409
+        byte[] bCodeData = null;
410
+        try {
411
+            bCodeData = str.getBytes("GBK");
412
+
413
+        } catch (UnsupportedEncodingException e) {
414
+            e.printStackTrace();
415
+            return null;
416
+        }
417
+
418
+        byte[] command = new byte[bCodeData.length + 16];
419
+
420
+        command[0] = 29;
421
+        command[1] = 119;
422
+        command[2] = ((byte) nWidthX);
423
+        command[3] = 29;
424
+        command[4] = 104;
425
+        command[5] = ((byte) nHeight);
426
+        command[6] = 29;
427
+        command[7] = 102;
428
+        command[8] = ((byte) (nHriFontType & 0x01));
429
+        command[9] = 29;
430
+        command[10] = 72;
431
+        command[11] = ((byte) (nHriFontPosition & 0x03));
432
+        command[12] = 29;
433
+        command[13] = 107;
434
+        command[14] = ((byte) nType);
435
+        command[15] = (byte) (byte) bCodeData.length;
436
+        System.arraycopy(bCodeData, 0, command, 16, bCodeData.length);
437
+
438
+
439
+        return command;
440
+    }
441
+
442
+    /**
443
+     * 设置打印模式(选择字体(font:A font:B),加粗,字体倍高倍宽(最大4倍高宽))
444
+     *
445
+     * @param str        打印的字符串
446
+     * @param bold       加粗
447
+     * @param font       选择字型
448
+     * @param widthsize  倍宽
449
+     * @param heigthsize 倍高
450
+     * @return
451
+     */
452
+    public static byte[] POS_Set_Font(String str, int bold, int font, int widthsize, int heigthsize) {
453
+
454
+        if (str.length() == 0 | widthsize < 0 | widthsize > 4 | heigthsize < 0 | heigthsize > 4
455
+                | font < 0 | font > 1)
456
+            return null;
457
+
458
+        byte[] strData = null;
459
+        try {
460
+            strData = str.getBytes("GBK");
461
+        } catch (UnsupportedEncodingException e) {
462
+            e.printStackTrace();
463
+            return null;
464
+        }
465
+
466
+        byte[] command = new byte[strData.length + 9];
467
+
468
+        byte[] intToWidth = {0x00, 0x10, 0x20, 0x30};//最大四倍宽
469
+        byte[] intToHeight = {0x00, 0x01, 0x02, 0x03};//最大四倍高
470
+
471
+        command[0] = 27;
472
+        command[1] = 69;
473
+        command[2] = ((byte) bold);
474
+        command[3] = 27;
475
+        command[4] = 77;
476
+        command[5] = ((byte) font);
477
+        command[6] = 29;
478
+        command[7] = 33;
479
+        command[8] = (byte) (intToWidth[widthsize] + intToHeight[heigthsize]);
480
+
481
+        System.arraycopy(strData, 0, command, 9, strData.length);
482
+        return command;
483
+    }
484
+
485
+//**********************************************************************************************************//
486
+
487
+    public static byte[] concatAll(byte[] first, byte[]... rest) {
488
+        int totalLength = first.length;
489
+        for (byte[] array : rest) {
490
+            totalLength += array.length;
491
+        }
492
+        byte[] result = Arrays.copyOf(first, totalLength);
493
+        int offset = first.length;
494
+        for (byte[] array : rest) {
495
+            System.arraycopy(array, 0, result, offset, array.length);
496
+            offset += array.length;
497
+        }
498
+        return result;
499
+    }
500
+}

+ 305
- 0
android/src/main/java/cn/jystudio/bluetooth/tsc/RNBluetoothTscPrinterModule.java View File

@@ -0,0 +1,305 @@
1
+package cn.jystudio.bluetooth.tsc;
2
+
3
+import android.graphics.Bitmap;
4
+import android.graphics.BitmapFactory;
5
+import android.util.Base64;
6
+import cn.jystudio.bluetooth.BluetoothService;
7
+import cn.jystudio.bluetooth.BluetoothServiceStateObserver;
8
+import com.facebook.react.bridge.*;
9
+
10
+import java.util.Map;
11
+import java.util.Vector;
12
+
13
+/**
14
+ * Created by januslo on 2018/9/22.
15
+ */
16
+public class RNBluetoothTscPrinterModule extends ReactContextBaseJavaModule
17
+implements BluetoothServiceStateObserver{
18
+    private static final String TAG="BluetoothTscPrinter";
19
+    private BluetoothService mService;
20
+
21
+    public RNBluetoothTscPrinterModule(ReactApplicationContext reactContext,BluetoothService bluetoothService) {
22
+        super(reactContext);
23
+        this.mService = bluetoothService;
24
+        this.mService.addStateObserver(this);
25
+    }
26
+
27
+    @Override
28
+    public String getName() {
29
+        return "BluetoothTscPrinter";
30
+    }
31
+
32
+    @ReactMethod
33
+    public void printLabel(final ReadableMap options, final Promise promise) {
34
+        int width = options.getInt("width");
35
+        int height = options.getInt("height");
36
+        int gap = options.hasKey("gap") ? options.getInt("gap") : 0;
37
+        TscCommand.SPEED speed = options.hasKey("speed")?this.findSpeed(options.getInt("speed")):null;
38
+        TscCommand.ENABLE enable = options.hasKey("tear") ?
39
+                options.getString("tear").equalsIgnoreCase(TscCommand.ENABLE.ON.getValue()) ? TscCommand.ENABLE.ON : TscCommand.ENABLE.OFF
40
+                : TscCommand.ENABLE.OFF;
41
+        ReadableArray texts = options.hasKey("text")? options.getArray("text"):null;
42
+        ReadableArray qrCodes = options.hasKey("qrcode")? options.getArray("qrcode"):null;
43
+        ReadableArray barCodes = options.hasKey("barcode")? options.getArray("barcode"):null;
44
+        ReadableArray images = options.hasKey("image")? options.getArray("image"):null;
45
+        ReadableArray reverses = options.hasKey("reverse")? options.getArray("reverse"):null;
46
+
47
+        TscCommand.DIRECTION direction = options.hasKey("direction") ?
48
+                TscCommand.DIRECTION.BACKWARD.getValue() == options.getInt("direction") ? TscCommand.DIRECTION.BACKWARD : TscCommand.DIRECTION.FORWARD
49
+                : TscCommand.DIRECTION.FORWARD;
50
+//        Not Support Yet
51
+//        TscCommand.MIRROR mirror = options.hasKey("mirror") ?
52
+//                TscCommand.MIRROR.MIRROR.getValue() == options.getInt("mirror") ? TscCommand.MIRROR.MIRROR : TscCommand.MIRROR.NORMAL
53
+//                : TscCommand.MIRROR.NORMAL;
54
+        TscCommand.DENSITY density = options.hasKey("density")?this.findDensity(options.getInt("density")):null;
55
+        ReadableArray reference = options.hasKey("reference")?options.getArray("reference"):null;
56
+
57
+        boolean sound = false;
58
+        if (options.hasKey("sound") && options.getInt("sound") == 1) {
59
+            sound = true;
60
+        }
61
+        boolean home = false;
62
+        if(options.hasKey("home") && options.getInt("home")== 1){
63
+            home = true;
64
+        }
65
+        TscCommand tsc = new TscCommand();
66
+        if(speed != null){
67
+            tsc.addSpeed(speed);//设置打印速度
68
+        }
69
+        if(density != null){
70
+            tsc.addDensity(density);//设置打印浓度
71
+        }
72
+        tsc.addSize(width,height); //设置标签尺寸,按照实际尺寸设置
73
+        tsc.addGap(gap);           //设置标签间隙,按照实际尺寸设置,如果为无间隙纸则设置为0
74
+         tsc.addDirection(direction);//设置打印方向
75
+        //设置原点坐标
76
+        if (reference != null && reference.size() == 2) {
77
+            tsc.addReference(reference.getInt(0), reference.getInt(1));
78
+        } else {
79
+            tsc.addReference(0, 0);
80
+        }
81
+        tsc.addTear(enable); //撕纸模式开启
82
+        if(home) {
83
+            tsc.addBackFeed(16);
84
+            tsc.addHome();//走纸到开始位置
85
+        }
86
+        tsc.addCls();// 清除打印缓冲区
87
+        //绘制简体中文
88
+        for (int i = 0;texts!=null&& i < texts.size(); i++) {
89
+            ReadableMap text = texts.getMap(i);
90
+            String t = text.getString("text");
91
+            int x = text.getInt("x");
92
+            int y = text.getInt("y");
93
+            TscCommand.FONTTYPE fonttype = this.findFontType(text.getString("fonttype"));
94
+            TscCommand.ROTATION rotation = this.findRotation(text.getInt("rotation"));
95
+            TscCommand.FONTMUL xscal = this.findFontMul(text.getInt("xscal"));
96
+            TscCommand.FONTMUL yscal = this.findFontMul(text.getInt("xscal"));
97
+            boolean bold = text.hasKey("bold") && text.getBoolean("bold");
98
+
99
+            try {
100
+                byte[] temp = t.getBytes("UTF-8");
101
+                String temStr = new String(temp, "UTF-8");
102
+                t = new String(temStr.getBytes("GB2312"), "GB2312");//打印的文字
103
+            } catch (Exception e) {
104
+                promise.reject("INVALID_TEXT", e);
105
+                return;
106
+            }
107
+
108
+            tsc.addText(x, y, fonttype/*字体类型*/,
109
+                    rotation/*旋转角度*/, xscal/*横向放大*/, yscal/*纵向放大*/, t);
110
+
111
+            if(bold){
112
+                tsc.addText(x+1, y, fonttype,
113
+                        rotation, xscal, yscal, t/*这里的t可能需要替换成同等长度的空格*/);
114
+                tsc.addText(x, y+1, fonttype,
115
+                        rotation, xscal, yscal, t/*这里的t可能需要替换成同等长度的空格*/);
116
+            }
117
+        }
118
+
119
+        //绘制图片
120
+        if(images != null){
121
+            for (int i = 0; i < images.size(); i++) {
122
+                ReadableMap img = images.getMap(i);
123
+                int x = img.getInt("x");
124
+                int y = img.getInt("y");
125
+                int imgWidth = img.getInt("width");
126
+                TscCommand.BITMAP_MODE mode = this.findBitmapMode(img.getInt("mode"));
127
+                String image  = img.getString("image");
128
+                byte[] decoded = Base64.decode(image, Base64.DEFAULT);
129
+                Bitmap b = BitmapFactory.decodeByteArray(decoded, 0, decoded.length);
130
+                tsc.addBitmap(x,y, mode, imgWidth,b);
131
+            }
132
+        }
133
+
134
+        if (qrCodes != null) {
135
+            for (int i = 0; i < qrCodes.size(); i++) {
136
+                ReadableMap qr = qrCodes.getMap(i);
137
+                int x = qr.getInt("x");
138
+                int y = qr.getInt("y");
139
+                int qrWidth = qr.getInt("width");
140
+                TscCommand.EEC level = this.findEEC(qr.getString("level"));
141
+                TscCommand.ROTATION rotation = this.findRotation(qr.getInt("rotation"));
142
+                String code = qr.getString("code");
143
+                tsc.addQRCode(x, y, level, qrWidth, rotation, code);
144
+            }
145
+        }
146
+        if (barCodes != null) {
147
+            for (int i = 0; i < barCodes.size(); i++) {
148
+                ReadableMap bar = barCodes.getMap(i);
149
+                int x = bar.hasKey("x") ? bar.getInt("x") : 0;
150
+                int y = bar.hasKey("y") ? bar.getInt("y") : 0;
151
+                int barHeight = bar.hasKey("height") ? bar.getInt("height") : 200;
152
+                int barWide = bar.hasKey("wide") ? bar.getInt("wide") : 2;
153
+                int narrow = bar.hasKey("narrow") ? bar.getInt("narrow") : 1;
154
+                TscCommand.ROTATION rotation = this.findRotation(bar.getInt("rotation"));
155
+                String code = bar.getString("code");
156
+                TscCommand.BARCODETYPE type = this.findBarcodeType(bar.getString("type"));
157
+                TscCommand.READABLE readable = this.findReadable(bar.getInt("readable"));
158
+                tsc.add1DBarcode(x, y, type, barHeight, barWide, narrow, readable, rotation, code);
159
+            }
160
+        }
161
+
162
+        if(reverses != null){
163
+            for(int i=0; i < reverses.size(); i++){
164
+                ReadableMap area = reverses.getMap(i);
165
+                int ax = area.getInt("x");
166
+                int ay = area.getInt("y");
167
+                int aWidth = area.getInt("width");
168
+                int aHeight = area.getInt("height");
169
+                tsc.addReverse(ax,ay,aWidth,aHeight);
170
+            }
171
+        }
172
+
173
+        tsc.addPrint(1, 1); // 打印标签
174
+        if (sound) {
175
+            tsc.addSound(2, 100); //打印标签后 蜂鸣器响
176
+        }
177
+        Vector<Byte> bytes = tsc.getCommand();
178
+        byte[] tosend = new byte[bytes.size()];
179
+        for(int i=0;i<bytes.size();i++){
180
+            tosend[i]= bytes.get(i);
181
+        }
182
+        if(sendDataByte(tosend)){
183
+            promise.resolve(null);
184
+        }else{
185
+            promise.reject("COMMAND_SEND_ERROR");
186
+        }
187
+    }
188
+
189
+    private TscCommand.BARCODETYPE findBarcodeType(String type) {
190
+        TscCommand.BARCODETYPE barcodeType = TscCommand.BARCODETYPE.CODE128;
191
+        for (TscCommand.BARCODETYPE t : TscCommand.BARCODETYPE.values()) {
192
+            if ((""+t.getValue()).equalsIgnoreCase(type)) {
193
+                barcodeType = t;
194
+                break;
195
+            }
196
+        }
197
+        return barcodeType;
198
+    }
199
+
200
+    private TscCommand.READABLE findReadable(int readable) {
201
+        TscCommand.READABLE ea = TscCommand.READABLE.EANBLE;
202
+        if (TscCommand.READABLE.DISABLE.getValue() == readable) {
203
+            ea = TscCommand.READABLE.DISABLE;
204
+        }
205
+        return ea;
206
+    }
207
+
208
+    private TscCommand.FONTMUL findFontMul(int scan) {
209
+        TscCommand.FONTMUL mul = TscCommand.FONTMUL.MUL_1;
210
+        for (TscCommand.FONTMUL m : TscCommand.FONTMUL.values()) {
211
+            if (m.getValue() == scan) {
212
+                mul = m;
213
+                break;
214
+            }
215
+        }
216
+        return mul;
217
+    }
218
+
219
+    private TscCommand.ROTATION findRotation(int rotation) {
220
+        TscCommand.ROTATION rt = TscCommand.ROTATION.ROTATION_0;
221
+        for (TscCommand.ROTATION r : TscCommand.ROTATION.values()) {
222
+            if (r.getValue() == rotation) {
223
+                rt = r;
224
+                break;
225
+            }
226
+        }
227
+        return rt;
228
+    }
229
+
230
+    private TscCommand.FONTTYPE findFontType(String fonttype) {
231
+        TscCommand.FONTTYPE ft = TscCommand.FONTTYPE.FONT_CHINESE;
232
+        for (TscCommand.FONTTYPE f : TscCommand.FONTTYPE.values()) {
233
+            if ((""+f.getValue()).equalsIgnoreCase(fonttype)) {
234
+                ft = f;
235
+                break;
236
+            }
237
+        }
238
+        return ft;
239
+    }
240
+
241
+
242
+    private TscCommand.SPEED findSpeed(int speed){
243
+        TscCommand.SPEED sd = null;
244
+        switch(speed){
245
+            case 1:
246
+                sd = TscCommand.SPEED.SPEED1DIV5;
247
+                break;
248
+            case 2:
249
+                sd = TscCommand.SPEED.SPEED2;
250
+                break;
251
+            case 3:
252
+                sd = TscCommand.SPEED.SPEED3;
253
+                break;
254
+            case 4:
255
+                sd = TscCommand.SPEED.SPEED4;
256
+                break;
257
+        }
258
+        return sd;
259
+    }
260
+
261
+    private TscCommand.EEC findEEC(String level) {
262
+        TscCommand.EEC eec = TscCommand.EEC.LEVEL_L;
263
+        for (TscCommand.EEC e : TscCommand.EEC.values()) {
264
+            if (e.getValue().equalsIgnoreCase(level)) {
265
+                eec = e;
266
+                break;
267
+            }
268
+        }
269
+        return eec;
270
+    }
271
+
272
+    private TscCommand.DENSITY findDensity(int density){
273
+        TscCommand.DENSITY ds = null;
274
+        for (TscCommand.DENSITY d : TscCommand.DENSITY.values()) {
275
+            if (d.getValue() == density) {
276
+                ds = d;
277
+                break;
278
+            }
279
+        }
280
+        return ds;
281
+    }
282
+    private TscCommand.BITMAP_MODE findBitmapMode(int mode){
283
+        TscCommand.BITMAP_MODE bm = TscCommand.BITMAP_MODE.OVERWRITE;
284
+        for (TscCommand.BITMAP_MODE m : TscCommand.BITMAP_MODE.values()) {
285
+            if (m.getValue() == mode) {
286
+                bm = m;
287
+                break;
288
+            }
289
+        }
290
+        return bm;
291
+    }
292
+
293
+    private boolean sendDataByte(byte[] data) {
294
+        if (mService.getState() != BluetoothService.STATE_CONNECTED) {
295
+            return false;
296
+        }
297
+        mService.write(data);
298
+        return true;
299
+    }
300
+
301
+    @Override
302
+    public void onBluetoothServiceStateChanged(int state, Map<String, Object> boundle) {
303
+
304
+    }
305
+}

+ 525
- 0
android/src/main/java/cn/jystudio/bluetooth/tsc/TscCommand.java View File

@@ -0,0 +1,525 @@
1
+package cn.jystudio.bluetooth.tsc;
2
+
3
+import android.graphics.Bitmap;
4
+import android.util.Log;
5
+import cn.jystudio.bluetooth.escpos.command.sdk.PrintPicture;
6
+
7
+import java.io.UnsupportedEncodingException;
8
+import java.util.Vector;
9
+
10
+public class TscCommand {
11
+    private static final String DEBUG_TAG = "TSCCommand";
12
+    private Vector<Byte> Command = null;
13
+
14
+    public static enum FOOT {
15
+        F2(0), F5(1);
16
+
17
+        private FOOT(int value) {
18
+            this.value = value;
19
+        }
20
+
21
+        private final int value;
22
+
23
+        public int getValue() {
24
+            return this.value;
25
+        }
26
+    }
27
+
28
+    public static enum SPEED {
29
+        SPEED1DIV5(1.5F), SPEED2(2.0F), SPEED3(3.0F), SPEED4(4.0F);
30
+
31
+        private SPEED(float value) {
32
+            this.value = value;
33
+        }
34
+
35
+        private final float value;
36
+
37
+        public float getValue() {
38
+            return this.value;
39
+        }
40
+    }
41
+
42
+    public static enum READABLE {
43
+        DISABLE(0), EANBLE(1);
44
+
45
+        private READABLE(int value) {
46
+            this.value = value;
47
+        }
48
+
49
+        private final int value;
50
+
51
+        public int getValue() {
52
+            return this.value;
53
+        }
54
+    }
55
+
56
+    public static enum BITMAP_MODE {
57
+        OVERWRITE(0), OR(1), XOR(2);
58
+
59
+        private BITMAP_MODE(int value) {
60
+            this.value = value;
61
+        }
62
+
63
+        private final int value;
64
+
65
+        public int getValue() {
66
+            return this.value;
67
+        }
68
+    }
69
+
70
+    public static enum DENSITY {
71
+        DNESITY0(0), DNESITY1(1), DNESITY2(2), DNESITY3(3), DNESITY4(4), DNESITY5(5), DNESITY6(6), DNESITY7(
72
+                7), DNESITY8(8), DNESITY9(9), DNESITY10(10), DNESITY11(11), DNESITY12(12), DNESITY13(13), DNESITY14(
73
+                14), DNESITY15(15);
74
+
75
+        private DENSITY(int value) {
76
+            this.value = value;
77
+        }
78
+
79
+        private final int value;
80
+
81
+        public int getValue() {
82
+            return this.value;
83
+        }
84
+    }
85
+
86
+    public static enum DIRECTION {
87
+        FORWARD(0), BACKWARD(1);
88
+
89
+        private DIRECTION(int value) {
90
+            this.value = value;
91
+        }
92
+
93
+        private final int value;
94
+
95
+        public int getValue() {
96
+            return this.value;
97
+        }
98
+    }
99
+
100
+    public static enum CODEPAGE {
101
+        PC437(437), PC850(850), PC852(852), PC860(860), PC863(863), PC865(865), WPC1250(1250), WPC1252(1252), WPC1253(
102
+                1253), WPC1254(1254);
103
+
104
+        private CODEPAGE(int value) {
105
+            this.value = value;
106
+        }
107
+
108
+        private final int value;
109
+
110
+        public int getValue() {
111
+            return this.value;
112
+        }
113
+    }
114
+
115
+    public static enum FONTMUL {
116
+        MUL_1(1), MUL_2(2), MUL_3(3), MUL_4(4), MUL_5(5), MUL_6(6), MUL_7(7), MUL_8(8), MUL_9(9), MUL_10(10);
117
+
118
+        private FONTMUL(int value) {
119
+            this.value = value;
120
+        }
121
+
122
+        private final int value;
123
+
124
+        public int getValue() {
125
+            return this.value;
126
+        }
127
+    }
128
+
129
+    public static enum FONTTYPE {
130
+        FONT_1("1"), FONT_2("2"), FONT_3("3"), FONT_4("4"), FONT_5("5"), FONT_6("6"), FONT_7("7"), FONT_8(
131
+                "8"), FONT_CHINESE("TSS24.BF2"), FONT_TAIWAN("TST24.BF2"), FONT_KOREAN("K");
132
+
133
+        private FONTTYPE(String value) {
134
+            this.value = value;
135
+        }
136
+
137
+        private final String value;
138
+
139
+        public String getValue() {
140
+            return this.value;
141
+        }
142
+    }
143
+
144
+    public static enum ROTATION {
145
+        ROTATION_0(0), ROTATION_90(90), ROTATION_180(180), ROTATION_270(270);
146
+
147
+        private ROTATION(int value) {
148
+            this.value = value;
149
+        }
150
+
151
+        private final int value;
152
+
153
+        public int getValue() {
154
+            return this.value;
155
+        }
156
+    }
157
+
158
+    public static enum BARCODETYPE {
159
+        CODE128("128"), CODE128M("128M"), EAN128("EAN128"), ITF25("25"), ITF25C("25C"), CODE39("39"), CODE39C(
160
+                "39C"), CODE39S("39S"), CODE93("93"), EAN13("EAN13"), EAN13_2("EAN13+2"), EAN13_5("EAN13+5"), EAN8(
161
+                "EAN8"), EAN8_2("EAN8+2"), EAN8_5("EAN8+5"), CODABAR("CODA"), POST("POST"), UPCA(
162
+                "EAN13"), UPCA_2("EAN13+2"), UPCA_5("EAN13+5"), UPCE("EAN13"), UPCE_2(
163
+                "EAN13+2"), UPCE_5("EAN13+5"), CPOST("CPOST"), MSI("MSI"), MSIC(
164
+                "MSIC"), PLESSEY("PLESSEY"), ITF14("ITF14"), EAN14("EAN14");
165
+
166
+        private final String value;
167
+
168
+        private BARCODETYPE(String value) {
169
+            this.value = value;
170
+        }
171
+
172
+        public String getValue() {
173
+            return this.value;
174
+        }
175
+    }
176
+
177
+    public static enum ENABLE {
178
+        ON("ON"), OFF("OFF");
179
+
180
+        private final String value;
181
+
182
+        private ENABLE(String value) {
183
+            this.value = value;
184
+        }
185
+
186
+        public String getValue() {
187
+            return this.value;
188
+        }
189
+    }
190
+
191
+    public static enum EEC {
192
+        LEVEL_L("L"),
193
+        LEVEL_M("M"),
194
+        LEVEL_Q("Q"),
195
+        LEVEL_H("H");
196
+        private final String value;
197
+
198
+        private EEC(String value) {
199
+            this.value = value;
200
+        }
201
+
202
+        public String getValue() {
203
+            return this.value;
204
+        }
205
+
206
+    }
207
+
208
+//    public static enum MIRROR {
209
+//        NORMAL(0), MIRROR(1);
210
+//        private final int value;
211
+//        private MIRROR(int value){
212
+//            this.value = value;
213
+//        }
214
+//        public int getValue(){return this.value;}
215
+//    }
216
+
217
+    public TscCommand() {
218
+        this.Command = new Vector(4096, 1024);
219
+    }
220
+
221
+    public TscCommand(int width, int height, int gap) {
222
+        this.Command = new Vector(4096, 1024);
223
+        addSize(width, height);
224
+        addGap(gap);
225
+    }
226
+
227
+    public void clrCommand() {
228
+        this.Command.clear();
229
+    }
230
+
231
+    private void addStrToCommand(String str) {
232
+        byte[] bs = null;
233
+        if (!str.equals("")) {
234
+            try {
235
+                bs = str.getBytes("GB2312");
236
+            } catch (UnsupportedEncodingException e) {
237
+                e.printStackTrace();
238
+            }
239
+            for (int i = 0; i < bs.length; i++) {
240
+                this.Command.add(Byte.valueOf(bs[i]));
241
+            }
242
+        }
243
+    }
244
+
245
+    public void addGap(int gap) {
246
+        String str = new String();
247
+        str = "GAP " + gap + " mm," + 0 + " mm" + "\r\n";
248
+        addStrToCommand(str);
249
+    }
250
+
251
+    public void addSize(int width, int height) {
252
+        String str = new String();
253
+        str = "SIZE " + width + " mm," + height + " mm" + "\r\n";
254
+        addStrToCommand(str);
255
+    }
256
+
257
+    public void addCashdrwer(FOOT m, int t1, int t2) {
258
+        String str = new String();
259
+        str = "CASHDRAWER " + m.getValue() + "," + t1 + "," + t2 + "\r\n";
260
+        addStrToCommand(str);
261
+    }
262
+
263
+    public void addOffset(int offset) {
264
+        String str = new String();
265
+        str = "OFFSET " + offset + " mm" + "\r\n";
266
+        addStrToCommand(str);
267
+    }
268
+
269
+    public void addSpeed(SPEED speed) {
270
+        String str = new String();
271
+        str = "SPEED " + speed.getValue() + "\r\n";
272
+        addStrToCommand(str);
273
+    }
274
+
275
+    public void addDensity(DENSITY density) {
276
+        String str = new String();
277
+        str = "DENSITY " + density.getValue() + "\r\n";
278
+        addStrToCommand(str);
279
+    }
280
+
281
+    public void addDirection(DIRECTION direction) {
282
+        String str = new String();
283
+        str = "DIRECTION " + direction.getValue() + "\r\n";
284
+        addStrToCommand(str);
285
+    }
286
+
287
+    public void addReference(int x, int y) {
288
+        String str = new String();
289
+        str = "REFERENCE " + x + "," + y + "\r\n";
290
+        addStrToCommand(str);
291
+    }
292
+
293
+    public void addShif(int shift) {
294
+        String str = new String();
295
+        str = "SHIFT " + shift + "\r\n";
296
+        addStrToCommand(str);
297
+    }
298
+
299
+    public void addCls() {
300
+        String str = new String();
301
+        str = "CLS\r\n";
302
+        addStrToCommand(str);
303
+    }
304
+
305
+    public void addFeed(int dot) {
306
+        String str = new String();
307
+        str = "FEED " + dot + "\r\n";
308
+        addStrToCommand(str);
309
+    }
310
+
311
+    public void addBackFeed(int dot) {
312
+        String str = new String();
313
+        str = "BACKFEED " + dot + "\r\n";
314
+        addStrToCommand(str);
315
+    }
316
+
317
+    public void addFormFeed() {
318
+        String str = new String();
319
+        str = "FORMFEED\r\n";
320
+        addStrToCommand(str);
321
+    }
322
+
323
+    public void addHome() {
324
+        String str = new String();
325
+        str = "HOME\r\n";
326
+        addStrToCommand(str);
327
+    }
328
+
329
+    public void addPrint(int m, int n) {
330
+        String str = new String();
331
+        str = "PRINT " + m + "," + n + "\r\n";
332
+        addStrToCommand(str);
333
+    }
334
+
335
+    public void addCodePage(CODEPAGE page) {
336
+        String str = new String();
337
+        str = "CODEPAGE " + page.getValue() + "\r\n";
338
+        addStrToCommand(str);
339
+    }
340
+
341
+    public void addSound(int level, int interval) {
342
+        String str = new String();
343
+        str = "SOUND " + level + "," + interval + "\r\n";
344
+        addStrToCommand(str);
345
+    }
346
+
347
+    public void addLimitFeed(int n) {
348
+        String str = new String();
349
+        str = "LIMITFEED " + n + "\r\n";
350
+        addStrToCommand(str);
351
+    }
352
+
353
+    public void addSelfTest() {
354
+        String str = new String();
355
+        str = "SELFTEST\r\n";
356
+        addStrToCommand(str);
357
+    }
358
+
359
+    public void addBar(int x, int y, int width, int height) {
360
+        String str = new String();
361
+        str = "BAR " + x + "," + y + "," + width + "," + height + "\r\n";
362
+        addStrToCommand(str);
363
+    }
364
+
365
+    public void addText(int x, int y, FONTTYPE font, ROTATION rotation, FONTMUL Xscal, FONTMUL Yscal, String text) {
366
+        String str = new String();
367
+        str = "TEXT " + x + "," + y + "," + "\"" + font.getValue() + "\"" + "," + rotation.getValue() + ","
368
+                + Xscal.getValue() + "," + Yscal.getValue() + "," + "\"" + text + "\"" + "\r\n";
369
+        addStrToCommand(str);
370
+    }
371
+
372
+    public void add1DBarcode(int x, int y, BARCODETYPE type, int height, int wide, int narrow, READABLE readable, ROTATION rotation,
373
+                             String content) {
374
+        String str = new String();
375
+        str = "BARCODE " + x + "," + y + "," + "\"" + type.getValue() + "\"" + "," + height + "," + readable.getValue()
376
+                + "," + rotation.getValue() + "," + narrow + "," + wide + "," + "\"" + content + "\"" + "\r\n";
377
+        addStrToCommand(str);
378
+    }
379
+
380
+    public void addQRCode(int x, int y, EEC level, int qrWidth, ROTATION rotation, String code) {
381
+        //var cmd = 'QRCODE 条码X方向起始点,条码Y方向起始点,纠错级别,二维码高度,A(A和M),旋转角度,M2(分为类型1和类型2),S1 (s1-s8,默认s7),\"1231你好2421341325454353\"';
382
+        String str = "QRCODE " + x + "," + y + "," + level.getValue() + "," + qrWidth + ",A," + rotation.getValue() + ",M2,S1,\"" + code + "\"\r\n";
383
+        addStrToCommand(str);
384
+    }
385
+//    public void addBitmap(int x,int y,BITMAP_MODE mode,int imgWidth, Bitmap b){
386
+//
387
+//        int width = ((imgWidth + 7) / 8) * 8;
388
+//        int height = b.getHeight() * width / b.getWidth();
389
+//        height = ((height + 7) / 8) * 8;
390
+//
391
+//        Bitmap rszBitmap = b;
392
+//        if (b.getWidth() != width) {
393
+//            rszBitmap = Bitmap.createScaledBitmap(b, width, height, true);
394
+//        }
395
+//
396
+//        Bitmap grayBitmap = PrintPicture.toGrayscale(rszBitmap);
397
+//        byte[] dithered = PrintPicture.thresholdToBWPic(grayBitmap);
398
+//        byte[] data =PrintPicture.eachLinePixToCmd(dithered, width, mode.getValue());
399
+//        height = dithered.length / width;
400
+//        width /= 8;
401
+//        //{command} {X},{Y },{width},{ height },{mode},{bitmap data }
402
+//        //  String str = "BITMAP " + x + "," + y + "," + width + "," + height + "," + mode.getValue() + ",";
403
+//        String str = "BITMAP "+x+","+y+","+width+","+height+","+mode.getValue()+",";
404
+//        addStrToCommand(str);
405
+//        for(int i=0;i<data.length;i++){
406
+//            Command.add(Byte.valueOf(data[i]));
407
+//        }
408
+//        addStrToCommand("\r\n");
409
+//    }
410
+
411
+
412
+    public void addBitmap(int x, int y, TscCommand.BITMAP_MODE mode, int nWidth, Bitmap b) {
413
+        if (b != null) {
414
+            int width = (nWidth + 7) / 8 * 8;
415
+            int height = b.getHeight() * width / b.getWidth();
416
+            Log.d("BMP", "bmp.getWidth() " + b.getWidth());
417
+            Bitmap grayBitmap = PrintPicture.toGrayscale(b);
418
+            Bitmap rszBitmap = PrintPicture.resizeImage(grayBitmap, width, height);
419
+            byte[] src = PrintPicture.bitmapToBWPix(rszBitmap);
420
+            height = src.length / width;
421
+            width /= 8;
422
+            String str = "BITMAP " + x + "," + y + "," + width + "," + height + "," + mode.getValue() + ",";
423
+            this.addStrToCommand(str);
424
+            byte[] codecontent = PrintPicture.pixToTscCmd(src);
425
+
426
+            for (int k = 0; k < codecontent.length; ++k) {
427
+                this.Command.add(Byte.valueOf(codecontent[k]));
428
+            }
429
+
430
+            Log.d("TSCCommand", "codecontent" + codecontent);
431
+            addStrToCommand("\r\n");
432
+        }
433
+
434
+    }
435
+
436
+    public void addBox(int x, int y, int xend, int yend) {
437
+        String str = new String();
438
+        str = "BAR " + x + "," + y + "," + xend + "," + yend + "\r\n";
439
+        addStrToCommand(str);
440
+    }
441
+
442
+    public void addErase(int x, int y, int xwidth, int yheight) {
443
+        String str = new String();
444
+        str = "ERASE " + x + "," + y + "," + xwidth + "," + yheight + "\r\n";
445
+        addStrToCommand(str);
446
+    }
447
+
448
+    public void addReverse(int x, int y, int xwidth, int yheight) {
449
+        String str = new String();
450
+        str = "REVERSE " + x + "," + y + "," + xwidth + "," + yheight + "\r\n";
451
+        addStrToCommand(str);
452
+    }
453
+
454
+    public Vector<Byte> getCommand() {
455
+        return this.Command;
456
+    }
457
+
458
+    public void queryPrinterType() {
459
+        String str = new String();
460
+        str = "~!T\r\n";
461
+        addStrToCommand(str);
462
+    }
463
+
464
+    public void queryPrinterStatus() {
465
+        this.Command.add(Byte.valueOf((byte) 27));
466
+        this.Command.add(Byte.valueOf((byte) 33));
467
+        this.Command.add(Byte.valueOf((byte) 63));
468
+    }
469
+
470
+    public void resetPrinter() {
471
+        this.Command.add(Byte.valueOf((byte) 27));
472
+        this.Command.add(Byte.valueOf((byte) 33));
473
+        this.Command.add(Byte.valueOf((byte) 82));
474
+    }
475
+
476
+    public void queryPrinterLife() {
477
+        String str = new String();
478
+        str = "~!@\r\n";
479
+        addStrToCommand(str);
480
+    }
481
+
482
+    public void queryPrinterMemory() {
483
+        String str = new String();
484
+        str = "~!A\r\n";
485
+        addStrToCommand(str);
486
+    }
487
+
488
+    public void queryPrinterFile() {
489
+        String str = new String();
490
+        str = "~!F\r\n";
491
+        addStrToCommand(str);
492
+    }
493
+
494
+    public void queryPrinterCodePage() {
495
+        String str = new String();
496
+        str = "~!I\r\n";
497
+        addStrToCommand(str);
498
+    }
499
+
500
+    public void addPeel(ENABLE enable) {
501
+        String str = new String();
502
+        str = "SET PEEL " + enable.getValue() + "\r\n";
503
+        addStrToCommand(str);
504
+    }
505
+
506
+    public void addTear(ENABLE enable) {
507
+        String str = new String();
508
+        str = "SET TEAR " + enable.getValue() + "\r\n";
509
+        addStrToCommand(str);
510
+    }
511
+
512
+    public void addCutter(ENABLE enable) {
513
+        String str = new String();
514
+        str = "SET CUTTER " + enable.getValue() + "\r\n";
515
+        addStrToCommand(str);
516
+    }
517
+
518
+    public void addPartialCutter(ENABLE enable) {
519
+        String str = new String();
520
+        str = "SET PARTIAL_CUTTER " + enable.getValue() + "\r\n";
521
+        addStrToCommand(str);
522
+    }
523
+
524
+
525
+}

+ 17
- 0
android/src/main/main1.iml View File

@@ -0,0 +1,17 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<module type="JAVA_MODULE" version="4">
3
+  <component name="FacetManager">
4
+    <facet type="android" name="Android">
5
+      <configuration />
6
+    </facet>
7
+  </component>
8
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
9
+    <exclude-output />
10
+    <content url="file://$MODULE_DIR$">
11
+      <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
12
+      <sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
13
+    </content>
14
+    <orderEntry type="jdk" jdkName="Android 5.1.1 Google APIs" jdkType="Android SDK" />
15
+    <orderEntry type="sourceFolder" forTests="false" />
16
+  </component>
17
+</module>

BIN
docs/ble_service_ids.png View File


+ 146
- 0
index.js View File

@@ -0,0 +1,146 @@
1
+
2
+import { NativeModules } from 'react-native';
3
+ const {BluetoothManager,BluetoothEscposPrinter,BluetoothTscPrinter}= NativeModules;
4
+
5
+BluetoothTscPrinter.DIRECTION = {
6
+    FORWARD: 0,
7
+    BACKWARD: 1
8
+};
9
+
10
+BluetoothTscPrinter.DENSITY = {
11
+    DNESITY0: 0,
12
+    DNESITY1: 1,
13
+    DNESITY2: 2,
14
+    DNESITY3: 3,
15
+    DNESITY4: 4,
16
+    DNESITY5: 5,
17
+    DNESITY6: 6,
18
+    DNESITY7: 7,
19
+    DNESITY8: 8,
20
+    DNESITY9: 9,
21
+    DNESITY10: 10,
22
+    DNESITY11: 11,
23
+    DNESITY12: 12,
24
+    DNESITY13: 13,
25
+    DNESITY14: 14,
26
+    DNESITY15: 15
27
+};
28
+BluetoothTscPrinter.BARCODETYPE = {
29
+    CODE128: "128",
30
+    CODE128M: "128M",
31
+    EAN128: "EAN128",
32
+    ITF25: "25",
33
+    ITF25C: "25C",
34
+    CODE39: "39",
35
+    CODE39C: "39C",
36
+    CODE39S: "39S",
37
+    CODE93: "93",
38
+    EAN13: "EAN13",
39
+    EAN13_2: "EAN13+2",
40
+    EAN13_5: "EAN13+5",
41
+    EAN8: "EAN8",
42
+    EAN8_2: "EAN8+2",
43
+    EAN8_5: "EAN8+5",
44
+    CODABAR: "CODA",
45
+    POST: "POST",
46
+    UPCA: "EAN13",
47
+    UPCA_2: "EAN13+2",
48
+    UPCA_5: "EAN13+5",
49
+    UPCE: "EAN13",
50
+    UPCE_2: "EAN13+2",
51
+    UPCE_5: "EAN13+5",
52
+    CPOST: "CPOST",
53
+    MSI: "MSI",
54
+    MSIC: "MSIC",
55
+    PLESSEY: "PLESSEY",
56
+    ITF14: "ITF14",
57
+    EAN14: "EAN14"
58
+};
59
+BluetoothTscPrinter.FONTTYPE = {
60
+    FONT_1: "1",
61
+    FONT_2: "2",
62
+    FONT_3: "3",
63
+    FONT_4: "4",
64
+    FONT_5: "5",
65
+    FONT_6: "6",
66
+    FONT_7: "7",
67
+    FONT_8: "8",
68
+    SIMPLIFIED_CHINESE: "TSS24.BF2",
69
+    TRADITIONAL_CHINESE: "TST24.BF2",
70
+    KOREAN: "K"
71
+};
72
+BluetoothTscPrinter.EEC = {
73
+    LEVEL_L: "L",
74
+    LEVEL_M: "M",
75
+    LEVEL_Q: "Q",
76
+    LEVEL_H: "H"
77
+
78
+};
79
+BluetoothTscPrinter.ROTATION = {
80
+    ROTATION_0: 0,
81
+    ROTATION_90: 90,
82
+    ROTATION_180: 180,
83
+    ROTATION_270: 270
84
+};
85
+ BluetoothTscPrinter.FONTMUL = {
86
+    MUL_1: 1,
87
+    MUL_2: 2,
88
+    MUL_3: 3,
89
+    MUL_4: 4,
90
+    MUL_5: 5,
91
+    MUL_6: 6,
92
+    MUL_7: 7,
93
+    MUL_8: 8,
94
+    MUL_9: 9,
95
+    MUL_10: 10
96
+};
97
+BluetoothTscPrinter.BITMAP_MODE = {
98
+    OVERWRITE: 0,
99
+    OR: 1,
100
+    XOR: 2
101
+};
102
+BluetoothTscPrinter.PRINT_SPEED = {
103
+    SPEED1DIV5:1,
104
+    SPEED2:2,
105
+    SPEED3:3,
106
+    SPEED4:4
107
+};
108
+BluetoothTscPrinter.TEAR = {
109
+	ON:'ON',
110
+	OFF:'OFF'
111
+};
112
+BluetoothTscPrinter.READABLE={
113
+  DISABLE:0,
114
+  EANBLE:1
115
+};
116
+
117
+BluetoothEscposPrinter.ERROR_CORRECTION = {
118
+    L:1,
119
+    M:0,
120
+    Q:3,
121
+    H:2
122
+};
123
+
124
+BluetoothEscposPrinter.BARCODETYPE={
125
+    UPC_A:65,//11<=n<=12
126
+    UPC_E:66,//11<=n<=12
127
+    JAN13:67,//12<=n<=12
128
+    JAN8:68,//7<=n<=8
129
+    CODE39:69,//1<=n<=255
130
+    ITF:70,//1<=n<=255(even numbers)
131
+    CODABAR:71,//1<=n<=255
132
+    CODE93:72,//1<=n<=255
133
+    CODE128:73//2<=n<=255
134
+};
135
+BluetoothEscposPrinter.ROTATION={
136
+    OFF:0,
137
+    ON:1
138
+};
139
+BluetoothEscposPrinter.ALIGN={
140
+    LEFT:0,
141
+    CENTER:1,
142
+    RIGHT:2
143
+};
144
+
145
+ module.exports ={
146
+    BluetoothManager,BluetoothEscposPrinter,BluetoothTscPrinter};

+ 11
- 0
ios/ColumnSplitedString.h View File

@@ -0,0 +1,11 @@
1
+//
2
+//  ColumnSplitedString.h
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/6.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+@interface ColumnSplitedString:NSObject
9
+@property NSInteger shorter;
10
+@property NSString *str;
11
+@end

+ 13
- 0
ios/ColumnSplitedString.m View File

@@ -0,0 +1,13 @@
1
+//
2
+//  ColumnSplitedString.m
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/6.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import "ColumnSplitedString.h"
11
+
12
+@implementation ColumnSplitedString
13
+@end

+ 19
- 0
ios/ImageUtils.h View File

@@ -0,0 +1,19 @@
1
+//
2
+//  ImageUtils.h
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/7.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+#import <Foundation/Foundation.h>
9
+#import <UIKit/UIKit.h>
10
+@interface ImageUtils :NSObject
11
++ (UIImage*)imagePadLeft:(NSInteger) left withSource: (UIImage*)source;
12
++ (uint8_t *)imageToGreyImage:(UIImage *)image;
13
++ (UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size;
14
++ (NSData*)bitmapToArray:(UIImage*) bmp;
15
++ (NSData *)eachLinePixToCmd:(unsigned char *)src nWidth:(NSInteger) nWidth nHeight:(NSInteger) nHeight nMode:(NSInteger) nMode;
16
++(unsigned char *)format_K_threshold:(unsigned char *) orgpixels
17
+                               width:(NSInteger) xsize height:(NSInteger) ysize;
18
++(NSData *)pixToTscCmd:(uint8_t *)src width:(NSInteger) width;
19
+@end

+ 277
- 0
ios/ImageUtils.m View File

@@ -0,0 +1,277 @@
1
+//
2
+//  ImageUtils.m
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/7.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import <UIKit/UIKit.h>
11
+#import "ImageUtils.h"
12
+@implementation ImageUtils : NSObject
13
+int p0[] = { 0, 0x80 };
14
+int p1[] = { 0, 0x40 };
15
+int p2[] = { 0, 0x20 };
16
+int p3[] = { 0, 0x10 };
17
+int p4[] = { 0, 0x08 };
18
+int p5[] = { 0, 0x04 };
19
+int p6[] = { 0, 0x02 };
20
+
21
++ (UIImage*)imagePadLeft:(NSInteger) left withSource: (UIImage*)source
22
+{
23
+    CGSize orgSize = [source size];
24
+    CGSize size = CGSizeMake(orgSize.width + [[NSNumber numberWithInteger: left] floatValue], orgSize.height);
25
+    UIGraphicsBeginImageContext(size);
26
+    CGContextRef context = UIGraphicsGetCurrentContext();
27
+    CGContextSetFillColorWithColor(context,
28
+                                   [[UIColor whiteColor] CGColor]);
29
+    CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
30
+    [source drawInRect:CGRectMake(left, 0, orgSize.width, orgSize.height)
31
+             blendMode:kCGBlendModeNormal alpha:1.0];
32
+    UIImage *paddedImage =  UIGraphicsGetImageFromCurrentImageContext();
33
+    UIGraphicsEndImageContext();
34
+    return paddedImage;
35
+}
36
+
37
++(uint8_t *)imageToGreyImage:(UIImage *)image {
38
+    // Create image rectangle with current image width/height
39
+    int kRed = 1;
40
+    int kGreen = 2;
41
+    int kBlue = 4;
42
+
43
+    int colors = kGreen | kBlue | kRed;
44
+
45
+    CGFloat actualWidth = image.size.width;
46
+    CGFloat actualHeight = image.size.height;
47
+    NSLog(@"actual size: %f,%f",actualWidth,actualHeight);
48
+    uint32_t *rgbImage = (uint32_t *) malloc(actualWidth * actualHeight * sizeof(uint32_t));
49
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
50
+    CGContextRef context = CGBitmapContextCreate(rgbImage, actualWidth, actualHeight, 8, actualWidth*4, colorSpace,
51
+                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
52
+    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
53
+    CGContextSetShouldAntialias(context, NO);
54
+    CGContextDrawImage(context, CGRectMake(0, 0, actualWidth, actualHeight), [image CGImage]);
55
+    CGContextRelease(context);
56
+    CGColorSpaceRelease(colorSpace);
57
+    
58
+//    CGRect imageRect = CGRectMake(0, 0, actualWidth, actualHeight);
59
+//    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
60
+//
61
+//    CGContextRef context = CGBitmapContextCreate(rgbImage, actualWidth, actualHeight, 8, actualWidth*4, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
62
+//    CGContextDrawImage(context, imageRect, [image CGImage]);
63
+//
64
+//    //CGImageRef grayImage = CGBitmapContextCreateImage(context);
65
+//    CGColorSpaceRelease(colorSpace);
66
+//    CGContextRelease(context);
67
+    
68
+//    context = CGBitmapContextCreate(nil, actualWidth, actualHeight, 8, 0, nil, kCGImageAlphaOnly);
69
+//    CGContextDrawImage(context, imageRect, [image CGImage]);
70
+//    CGImageRef mask = CGBitmapContextCreateImage(context);
71
+//    CGContextRelease(context);
72
+    
73
+//    UIImage *grayScaleImage = [UIImage imageWithCGImage:CGImageCreateWithMask(grayImage, mask) scale:image.scale orientation:image.imageOrientation];
74
+//    CGImageRelease(grayImage);
75
+ //   CGImageRelease(mask);
76
+    
77
+    // Return the new grayscale image
78
+    
79
+     //now convert to grayscale
80
+    uint8_t *m_imageData = (uint8_t *) malloc(actualWidth * actualHeight);
81
+   // NSMutableString *toLog = [[NSMutableString alloc] init];
82
+    for(int y = 0; y < actualHeight; y++) {
83
+        for(int x = 0; x < actualWidth; x++) {
84
+            uint32_t rgbPixel=rgbImage[(int)(y*actualWidth+x)];
85
+            uint32_t sum=0,count=0;
86
+            if (colors & kRed) {sum += (rgbPixel>>24)&255; count++;}
87
+            if (colors & kGreen) {sum += (rgbPixel>>16)&255; count++;}
88
+            if (colors & kBlue) {sum += (rgbPixel>>8)&255; count++;}
89
+           // [toLog appendFormat:@"pixel:%d,sum:%d,count:%d,val:%d;",rgbPixel,sum,count,(int)(sum/count)];
90
+            m_imageData[(int)(y*actualWidth+x)]=sum/count;
91
+           
92
+        }
93
+    }
94
+    //NSLog(@"m_imageData:%@",toLog);
95
+    return m_imageData;
96
+//    // Create image rectangle with current image width/height
97
+//    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
98
+//
99
+//    // Grayscale color space
100
+//    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
101
+//
102
+//    // Create bitmap content with current image size and grayscale colorspace
103
+//    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);
104
+//
105
+//    // Draw image into current context, with specified rectangle
106
+//    // using previously defined context (with grayscale colorspace)
107
+//    CGContextDrawImage(context, imageRect, [image CGImage]);
108
+//
109
+//    // Create bitmap image info from pixel data in current context
110
+//    CGImageRef imageRef = CGBitmapContextCreateImage(context);
111
+//
112
+//    // Create a new UIImage object
113
+//    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
114
+//
115
+//    // Release colorspace, context and bitmap information
116
+//    CGColorSpaceRelease(colorSpace);
117
+//    CGContextRelease(context);
118
+//    CFRelease(imageRef);
119
+//
120
+//    // Return the new grayscale image
121
+//    return newImage;
122
+    
123
+}
124
+
125
++ (UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size
126
+{
127
+    CGFloat scale = MAX(size.width/image.size.width, size.height/image.size.height);
128
+    CGFloat width = image.size.width * scale;
129
+    CGFloat height = image.size.height * scale;
130
+    CGRect imageRect = CGRectMake((size.width - width)/2.0f,
131
+                                  (size.height - height)/2.0f,
132
+                                  width,
133
+                                  height);
134
+    
135
+    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
136
+    [image drawInRect:imageRect];
137
+    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
138
+    UIGraphicsEndImageContext();
139
+    return newImage;
140
+}
141
+
142
++ (NSData*)bitmapToArray:(UIImage*) bmp
143
+{
144
+    CGDataProviderRef provider = CGImageGetDataProvider(bmp.CGImage);
145
+    NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
146
+    return data;
147
+}
148
+
149
+/**
150
+ **Raster Image - $1D $76 $30 m xL xH yL yH d1...dk
151
+ Prints a raster image
152
+ 
153
+ Format:
154
+ Hex       $1D  $76 30  m xL xH yL yH d1...dk
155
+ 
156
+ ASCII     GS   v   %   m xL xH yL yH d1...dk
157
+ 
158
+ Decimal   29  118  48  m xL xH yL yH d1...dk
159
+ 
160
+ Notes:
161
+ When ​standard mode​ is enabled, this command is only executed when there is no data in the print buffer. (Line is empty)
162
+ The defined data (​d​) defines each byte of the raster image. Each bit in every byte defines a pixel. A bit set to 1 is printed and a bit set to 0 is not printed.
163
+ If a raster bit image exceeds one line, the excess data is not printed.
164
+ This command feeds as much paper as is required to print the entire raster bit image, regardless of line spacing defined by 1/6” or 1/8” commands.
165
+ After the raster bit image is printed, the print position goes to the beginning of the line.
166
+ The following commands have no effect on a raster bit image:
167
+ Emphasized
168
+ Double Strike
169
+ Underline
170
+ White/Black Inverse Printing
171
+ Upside-Down Printing
172
+ Rotation
173
+ Left margin
174
+ Print Area Width
175
+ A raster bit image data is printed in the following order:
176
+ d1    d2    …    dx
177
+ dx + 1    dx + 2    …    dx * 2
178
+ .    .    .    .
179
+ …    dk - 2    dk - 1    dk
180
+ Defines and prints a raster bit image using the mode specified by ​m​:
181
+ m    Mode    Width Scalar    Heigh Scalar
182
+ 0, 48    Normal    x1    x1
183
+ 1, 49    Double Width    x2    x1
184
+ 2, 50    Double Height    x1    x2
185
+ 3, 51    Double Width/Height    x2    x2
186
+ xL, xH ​defines the raster bit image in the horizontal direction in ​bytes​ using two-byte number definitions. (​xL + (xH * 256)) Bytes
187
+ yL, yH ​defines the raster bit image in the vertical direction in ​dots​ using two-byte number definitions. (​yL + (yH * 256)) Dots
188
+ d ​ specifies the bit image data in raster format.
189
+ k ​indicates the number of bytes in the bit image. ​k ​is not transmitted and is there for explanation only.
190
+ **/
191
++ (NSData *)eachLinePixToCmd:(unsigned char *)src nWidth:(NSInteger) nWidth nHeight:(NSInteger) nHeight nMode:(NSInteger) nMode
192
+{
193
+    NSLog(@"SIZE OF SRC: %lu",sizeof(&src));
194
+    NSInteger nBytesPerLine = (int)nWidth/8;
195
+    unsigned char * data = malloc(nHeight*(8+nBytesPerLine));
196
+   // const char* srcData = (const char*)[src bytes];
197
+    NSInteger k = 0;
198
+   // NSMutableString *toLog = [[NSMutableString alloc] init];
199
+    for(int i=0;i<nHeight;i++){
200
+        NSInteger var10 = i*(8+nBytesPerLine);
201
+         //GS v 0 m xL xH yL yH d1....dk 打印光栅位图
202
+                data[var10 + 0] = 29;//GS
203
+                data[var10 + 1] = 118;//v
204
+                data[var10 + 2] = 48;//0
205
+                data[var10 + 3] =  (unsigned char)(nMode & 1);
206
+                data[var10 + 4] =  (unsigned char)(nBytesPerLine % 256);//xL
207
+                data[var10 + 5] =  (unsigned char)(nBytesPerLine / 256);//xH
208
+                data[var10 + 6] = 1;//yL
209
+                data[var10 + 7] = 0;//yH
210
+//        for(int l=0;l<8;l++){
211
+//            NSInteger d =data[var10 + l];
212
+//            [toLog appendFormat:@"%ld,",(long)d];
213
+//        }
214
+        
215
+        for (int j = 0; j < nBytesPerLine; ++j) {
216
+            data[var10 + 8 + j] = (int) (p0[src[k]] + p1[src[k + 1]] + p2[src[k + 2]] + p3[src[k + 3]] + p4[src[k + 4]] + p5[src[k + 5]] + p6[src[k + 6]] + src[k + 7]);
217
+            k =k+8;
218
+             //  [toLog appendFormat:@"%ld,",(long)data[var10+8+j]];
219
+        }
220
+       // [toLog appendString:@"\n\r"];
221
+    }
222
+   // NSLog(@"line datas: %@",toLog);
223
+    return [NSData dataWithBytes:data length:nHeight*(8+nBytesPerLine)];
224
+}
225
+
226
++(unsigned char *)format_K_threshold:(unsigned char *) orgpixels
227
+                        width:(NSInteger) xsize height:(NSInteger) ysize
228
+{
229
+    unsigned char * despixels = malloc(xsize*ysize);
230
+    int graytotal = 0;
231
+    int k = 0;
232
+    
233
+    int i;
234
+    int j;
235
+    int gray;
236
+    for(i = 0; i < ysize; ++i) {
237
+        for(j = 0; j < xsize; ++j) {
238
+            gray = orgpixels[k] & 255;
239
+            graytotal += gray;
240
+            ++k;
241
+        }
242
+    }
243
+    
244
+    int grayave = graytotal / ysize / xsize;
245
+    k = 0;
246
+   // NSMutableString *logStr = [[NSMutableString alloc]init];
247
+   // int oneCount = 0;
248
+    for(i = 0; i < ysize; ++i) {
249
+        for(j = 0; j < xsize; ++j) {
250
+            gray = orgpixels[k] & 255;
251
+            if(gray > grayave) {
252
+                despixels[k] = 0;
253
+            } else {
254
+                despixels[k] = 1;
255
+               // oneCount++;
256
+            }
257
+            
258
+            ++k;
259
+           // [logStr appendFormat:@"%d,",despixels[k]];
260
+        }
261
+    }
262
+   // NSLog(@"despixels [with 1 count:%d]: %@",oneCount,logStr);
263
+    return despixels;
264
+}
265
++(NSData *)pixToTscCmd:(uint8_t *)src width:(NSInteger) width
266
+{
267
+    int length = (int)width/8;
268
+    uint8_t * data = malloc(length);
269
+    int k = 0;
270
+    for(int j = 0;k<length;++k){
271
+        data[k] =(uint8_t)(p0[src[j]] + p1[src[j + 1]] + p2[src[j + 2]] + p3[src[j + 3]] + p4[src[j + 4]] + p5[src[j + 5]] + p6[src[j + 6]] + src[j + 7]);
272
+        j+=8;
273
+    }
274
+    return [[NSData alloc] initWithBytes:data length:length];
275
+}
276
+
277
+@end

+ 25
- 0
ios/PrintColumnBleWriteDelegate.h View File

@@ -0,0 +1,25 @@
1
+//
2
+//  PrintColumnBleWriteDelegate.h
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/6.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+#import <React/RCTBridgeModule.h>
9
+#import "RNBluetoothManager.h"
10
+#import "RNBluetoothEscposPrinter.h"
11
+
12
+@interface PrintColumnBleWriteDelegate:NSObject<WriteDataToBleDelegate>
13
+@property NSInteger now;
14
+@property Boolean error;
15
+@property RCTPromiseResolveBlock pendingResolve;
16
+@property RCTPromiseRejectBlock pendingReject;
17
+@property RNBluetoothEscposPrinter *printer;
18
+@property Boolean canceled;
19
+@property NSString *encodig;
20
+@property NSInteger codePage;
21
+@property NSInteger widthTimes;
22
+@property NSInteger heightTimes;
23
+@property NSInteger fontType;
24
+-(void)printColumn:(NSMutableArray<NSMutableString *> *) columnsToPrint withMaxcount:(NSInteger)maxcount;
25
+@end

+ 53
- 0
ios/PrintColumnBleWriteDelegate.m View File

@@ -0,0 +1,53 @@
1
+//
2
+//  PrintColumnBleWriteDelegate.m
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/6.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import "PrintColumnBleWriteDelegate.h"
11
+@implementation PrintColumnBleWriteDelegate
12
+
13
+NSMutableArray<NSMutableString *>  *columns;
14
+NSInteger maxRowCount;
15
+
16
+- (void)didWriteDataToBle:(BOOL)success {NSLog(@"Call back deletgate: %lu",_now+1);
17
+    if(_canceled){
18
+           if(_pendingReject) _pendingReject(@"ERROR_IN_PRINT_COLUMN",@"ERROR_IN_PRINT_COLUMN",nil);
19
+        return;
20
+    }
21
+    _now = _now+1;
22
+    if(_now >= maxRowCount){
23
+        if(_error && _pendingReject){
24
+            _pendingReject(@"ERROR_IN_PRINT_COLUMN",@"ERROR_IN_PRINT_COLUMN",nil);
25
+        }else if(_pendingResolve){
26
+            _pendingResolve(nil);
27
+        }
28
+    }else{
29
+        if(!success){
30
+            _error = true;
31
+        }
32
+        [self print];
33
+    }
34
+    [NSThread sleepForTimeInterval:0.05f];//slow down.
35
+}
36
+-(void)printColumn:( NSMutableArray<NSMutableString *> *)columnsToPrint withMaxcount:(NSInteger)maxcount{
37
+    columns = columnsToPrint;
38
+    maxRowCount = maxcount;
39
+    [self print];
40
+}
41
+-(void)print{
42
+    [(NSMutableString *)[columns objectAtIndex:_now] appendString:@"\n\r"];//wrap line..
43
+    @try {
44
+        [self.printer textPrint:[columns objectAtIndex:_now] inEncoding:_encodig withCodePage:_codePage widthTimes:_widthTimes heightTimes:_heightTimes fontType:_fontType delegate:self];
45
+    }
46
+    @catch (NSException *e){
47
+        NSLog(@"ERROR IN PRINTING COLUMN:%@",e);
48
+        _pendingReject(@"ERROR_IN_PRINT_COLUMN",@"ERROR_IN_PRINT_COLUMN",nil);
49
+        self.canceled = true;
50
+    }
51
+}
52
+
53
+@end;

+ 19
- 0
ios/PrintImageBleWriteDelegate.h View File

@@ -0,0 +1,19 @@
1
+//
2
+//  PrintImageBleWriteDelegate.h
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/8.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+#import <React/RCTBridgeModule.h>
9
+#import "RNBluetoothManager.h"
10
+#import "RNBluetoothEscposPrinter.h"
11
+@interface PrintImageBleWriteDelegate :NSObject<WriteDataToBleDelegate>
12
+@property NSData *toPrint;
13
+@property NSInteger width;
14
+@property NSInteger now;
15
+@property RNBluetoothManager *printer;
16
+@property RCTPromiseRejectBlock pendingReject;
17
+@property RCTPromiseResolveBlock pendingResolve;
18
+-(void) print;
19
+@end

+ 61
- 0
ios/PrintImageBleWriteDelegate.m View File

@@ -0,0 +1,61 @@
1
+//
2
+//  PrintImageBleWriteDelegate.m
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/8.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import "PrintImageBleWriteDelegate.h"
11
+@implementation PrintImageBleWriteDelegate
12
+
13
+
14
+- (void) didWriteDataToBle: (BOOL)success
15
+{NSLog(@"PrintImageBleWriteDelete diWriteDataToBle: %d",success?1:0);
16
+    if(success){
17
+        if(_now == -1){
18
+             if(_pendingResolve) {_pendingResolve(nil); _pendingResolve=nil;}
19
+        }else if(_now>=[_toPrint length]){
20
+//            ASCII ESC M 0 CR LF
21
+//            Hex 1B 4D 0 0D 0A
22
+//            Decimal 27 77 0 13 10
23
+            unsigned char * initPrinter = malloc(5);
24
+            initPrinter[0]=27;
25
+            initPrinter[1]=77;
26
+            initPrinter[2]=0;
27
+            initPrinter[3]=13;
28
+            initPrinter[4]=10;
29
+            [RNBluetoothManager writeValue:[NSData dataWithBytes:initPrinter length:5] withDelegate:self];
30
+            _now = -1;
31
+            [NSThread sleepForTimeInterval:0.01f];
32
+        }else {
33
+            [self print];
34
+        }
35
+    }else if(_pendingReject){
36
+        _pendingReject(@"PRINT_IMAGE_FAILED",@"PRINT_IMAGE_FAILED",nil);
37
+        _pendingReject = nil;
38
+    }
39
+    
40
+}
41
+
42
+-(void) print
43
+{
44
+    @synchronized (self) {
45
+     NSInteger sizePerLine = (int)(_width/8);
46
+   // do{
47
+//        if(sizePerLine+_now>=[_toPrint length]){
48
+//            sizePerLine = [_toPrint length] - _now;
49
+//        }
50
+       // if(sizePerLine>0){
51
+            NSData *subData = [_toPrint subdataWithRange:NSMakeRange(_now, sizePerLine)];
52
+            NSLog(@"Write data:%@",subData);
53
+            [RNBluetoothManager writeValue:subData withDelegate:self];
54
+        //}
55
+        _now = _now+sizePerLine;
56
+        [NSThread sleepForTimeInterval:0.01f];
57
+        
58
+    }
59
+    //}while(_now<[_toPrint length]);
60
+}
61
+@end

+ 16
- 0
ios/RNBluetoothEscposPrinter.h View File

@@ -0,0 +1,16 @@
1
+
2
+#import <React/RCTBridgeModule.h>
3
+#import "RNBluetoothManager.h";
4
+
5
+@interface RNBluetoothEscposPrinter : NSObject <RCTBridgeModule,WriteDataToBleDelegate>
6
+
7
+@property (nonatomic,assign) NSInteger deviceWidth;
8
+-(void) textPrint:(NSString *) text
9
+       inEncoding:(NSString *) encoding
10
+     withCodePage:(NSInteger) codePage
11
+       widthTimes:(NSInteger) widthTimes
12
+      heightTimes:(NSInteger) heightTimes
13
+         fontType:(NSInteger) fontType
14
+         delegate:(NSObject<WriteDataToBleDelegate> *) delegate;
15
+@end
16
+  

+ 626
- 0
ios/RNBluetoothEscposPrinter.m View File

@@ -0,0 +1,626 @@
1
+
2
+#import <Foundation/Foundation.h>
3
+#import <UIKit/UIKit.h>
4
+#import "RNBluetoothManager.h"
5
+#import "RNBluetoothEscposPrinter.h"
6
+#import "ColumnSplitedString.h"
7
+#import "PrintColumnBleWriteDelegate.h"
8
+#import "ImageUtils.h"
9
+#import "ZXingObjC/ZXingObjC.h"
10
+#import "PrintImageBleWriteDelegate.h"
11
+@implementation RNBluetoothEscposPrinter
12
+
13
+int WIDTH_58 = 384;
14
+int WIDTH_80 = 576;
15
+Byte ESC[] = {0x1b};
16
+//NSInteger ESC = 0x1b;
17
+Byte ESC_FS[] = {0x1c};
18
+//NSInteger FS = 0x1C;
19
+Byte ESC_GS[] = {0x1D};
20
+Byte US[] = {0x1F};
21
+Byte DLE[] = {0x10};
22
+Byte DC4[] = {0x14};
23
+Byte DC1[] = {0x11};
24
+Byte SP[] = {0x20};
25
+Byte NL[] = {0x0A};
26
+Byte FF[] = {0x0C};
27
+Byte PIECE[] = {0xFF};
28
+Byte NUL[] =  {0x00};
29
+Byte SIGN[] = {0x21};//!
30
+Byte T[] = {0x74};//t
31
+Byte AND[] ={0x26}; //&
32
+Byte M[] = {0x4d};//M
33
+Byte V[] = {0x56};//V
34
+Byte A[] = {0x61};//a
35
+Byte E[] = {0x45};//E
36
+Byte G[] = {0x47};//G
37
+
38
+RCTPromiseResolveBlock pendingResolve;
39
+RCTPromiseRejectBlock pendingReject;
40
+
41
+-(id)init {
42
+    if (self = [super init])  {
43
+        self.deviceWidth = WIDTH_58;
44
+    }
45
+    return self;
46
+}
47
+
48
+
49
+- (dispatch_queue_t)methodQueue
50
+{
51
+    return dispatch_get_main_queue();
52
+}
53
++ (BOOL)requiresMainQueueSetup
54
+{
55
+    return YES;
56
+}
57
+
58
+
59
+/**
60
+ * Exports the constants to javascritp.
61
+ **/
62
+- (NSDictionary *)constantsToExport
63
+{
64
+    return @{ @"width58":[NSString stringWithFormat:@"%i", WIDTH_58],
65
+              @"width80":[NSString stringWithFormat:@"%i", WIDTH_80]};
66
+}
67
+
68
+RCT_EXPORT_MODULE(BluetoothEscposPrinter);
69
+
70
+/**
71
+ * Sets the current deivce width
72
+ **/
73
+RCT_EXPORT_METHOD(setWidth:(int) width)
74
+{
75
+    self.deviceWidth = width;
76
+}
77
+
78
+//public void printerInit(final Promise promise){
79
+//    if(sendDataByte(PrinterCommand.POS_Set_PrtInit())){
80
+//        promise.resolve(null);
81
+//    }else{
82
+//        promise.reject("COMMAND_NOT_SEND");
83
+//    }
84
+//}
85
+
86
+RCT_EXPORT_METHOD(printerInit:(RCTPromiseResolveBlock)resolve
87
+                  rejecter:(RCTPromiseRejectBlock)reject)
88
+{
89
+    if(RNBluetoothManager.isConnected){
90
+        NSMutableData *data = [[NSMutableData alloc] init];
91
+        Byte at[] = {'@'};
92
+        [data appendBytes:ESC length:1];
93
+        [data appendBytes:at length:1];
94
+        pendingResolve = resolve;
95
+        pendingReject = reject;
96
+        [RNBluetoothManager writeValue:data withDelegate:self];
97
+    }else{
98
+        reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
99
+    }
100
+    
101
+}
102
+
103
+//{GS, 'L', 0x00 , 0x00 }
104
+// data[2] = (byte) (left % 100);
105
+//data[3] = (byte) (left / 100);
106
+RCT_EXPORT_METHOD(printerLeftSpace:(int) sp
107
+                  withResolver:(RCTPromiseResolveBlock)resolve
108
+                  rejecter:(RCTPromiseRejectBlock)reject)
109
+{
110
+    if(sp>255 || sp<0){
111
+        reject(@"COMMAND_NOT_SEND",@"INVALID_VALUE",nil);
112
+        return;
113
+    }
114
+    
115
+    if(RNBluetoothManager.isConnected){
116
+        NSMutableData *data = [[NSMutableData alloc] init];
117
+        Byte left[] = {'L'};
118
+        Byte sp_up[] = {(sp%100)};
119
+        Byte sp_down[] = {(sp/100)};
120
+        [data appendBytes:ESC_GS length:1];
121
+        [data appendBytes:left length:1];
122
+        [data appendBytes:sp_up length:1];
123
+        [data appendBytes:sp_down length:1];
124
+        pendingResolve = resolve;
125
+        pendingReject = reject;
126
+        [RNBluetoothManager writeValue:data withDelegate:self];
127
+    }else{
128
+        reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
129
+    }
130
+}
131
+
132
+//{ESC, 45, 0x00 };
133
+//{FS, 45, 0x00 };
134
+RCT_EXPORT_METHOD(printerUnderLine:(int)sp withResolver:(RCTPromiseResolveBlock) resolve
135
+                  rejecter:(RCTPromiseRejectBlock) reject)
136
+{
137
+    if(sp<0 || sp>2){
138
+          reject(@"COMMAND_NOT_SEND",@"INVALID_VALUE",nil);
139
+        return;
140
+    }
141
+    if(RNBluetoothManager.isConnected){
142
+        NSMutableData *data = [[NSMutableData alloc] init];
143
+        Byte under_line[] = {45};
144
+        Byte spb[] = {sp};
145
+        [data appendBytes:ESC length:1];
146
+        [data appendBytes:under_line length:1];
147
+        [data appendBytes:spb length:1];
148
+        [data appendBytes:ESC_FS length:1];
149
+        [data appendBytes:under_line length:1];
150
+        [data appendBytes:spb length:1];
151
+        pendingResolve = resolve;
152
+        pendingReject = reject;
153
+        [RNBluetoothManager writeValue:data withDelegate:self];
154
+    }else{
155
+        reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
156
+    }
157
+    
158
+}
159
+
160
+RCT_EXPORT_METHOD(printText:(NSString *) text withOptions:(NSDictionary *) options
161
+                  resolver:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject)
162
+{NSLog(@"printing text...with options: %@",options);
163
+    if(!RNBluetoothManager.isConnected){
164
+          reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
165
+    }else{
166
+        @try{
167
+    //encoding:'GBK',
168
+    //codepage:0,
169
+    //widthtimes:0,
170
+    //heigthtimes:0,
171
+    //fonttype:1
172
+        NSString *encodig = [options valueForKey:@"encoding"];
173
+        if(!encodig) encodig=@"GBK";
174
+            NSInteger codePage = [[options valueForKey:@"codepage"] integerValue];NSLog(@"Got codepage from options: %ld",codePage);
175
+        if(!codePage) codePage = 0;
176
+        NSInteger widthTimes = [[options valueForKey:@"widthtimes"] integerValue];
177
+        if(!widthTimes) widthTimes = 0;
178
+        NSInteger heigthTime = [[options valueForKey:@"heigthtimes"] integerValue];
179
+        if(!heigthTime) heigthTime =0;
180
+        NSInteger fontType = [[options valueForKey:@"fontType"] integerValue];
181
+        if(!fontType) fontType = 0;
182
+            pendingResolve = resolve;
183
+            pendingReject = reject;
184
+            [self textPrint:text inEncoding:encodig withCodePage:codePage widthTimes:widthTimes heightTimes:heigthTime fontType:fontType delegate:self];
185
+        }
186
+        @catch (NSException *e){
187
+            NSLog(@"print text exception: %@",e);
188
+            reject(e.name.description,e.name.description,nil);
189
+        }
190
+    }
191
+}
192
+-(NSStringEncoding) toNSEncoding:(NSString *)encoding
193
+{NSLog(@"encoding: %@",encoding);
194
+    NSStringEncoding nsEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
195
+    if([@"UTF-8" isEqualToString:encoding] || [@"utf-8" isEqualToString:encoding] ){
196
+        nsEncoding = NSUTF8StringEncoding;
197
+    }
198
+    
199
+    return nsEncoding;
200
+}
201
+-(void) textPrint:(NSString *) text
202
+       inEncoding:(NSString *) encoding
203
+     withCodePage:(NSInteger) codePage
204
+       widthTimes:(NSInteger) widthTimes
205
+      heightTimes:(NSInteger) heightTimes
206
+         fontType:(NSInteger) fontType
207
+     delegate:(NSObject<WriteDataToBleDelegate> *) delegate
208
+{
209
+    Byte *intToWidth[] = {0x00, 0x10, 0x20, 0x30};
210
+    Byte *intToHeight[] = {0x00, 0x01, 0x02, 0x03};
211
+    Byte *multTime[] = {intToWidth[widthTimes],intToHeight[heightTimes]};
212
+    NSData *bytes = [text dataUsingEncoding:[self toNSEncoding:encoding]];
213
+    NSLog(@"Got bytes length:%lu",[bytes length]);
214
+    
215
+    NSMutableData *toSend = [[NSMutableData alloc] init];
216
+    
217
+    //gsExclamationMark:{GS, '!', 0x00 };
218
+    [toSend appendBytes:ESC_GS length:sizeof(ESC_GS)];
219
+    [toSend appendBytes:SIGN length:sizeof(SIGN)];
220
+    [toSend appendBytes:multTime length:sizeof(multTime)];
221
+    //escT:  {ESC, 't', 0x00 };
222
+    [toSend appendBytes:ESC length:sizeof(ESC)];
223
+    [toSend appendBytes:T length:sizeof(T)];
224
+    [toSend appendBytes:&codePage length:sizeof(codePage)];NSLog(@"codepage: %lu",codePage);
225
+    if(codePage == 0){
226
+        //FS_and :{FS, '&' };
227
+        [toSend appendBytes:ESC_FS length:sizeof(ESC_FS)];
228
+        [toSend appendBytes:AND length:sizeof(AND)];
229
+    }else{NSLog(@"{FS,46}");
230
+        //FS_dot: {FS, 46 };
231
+        NSInteger fourtySix= 46;
232
+        [toSend appendBytes:ESC_FS length:sizeof(ESC_FS)];
233
+        [toSend appendBytes:&fourtySix length:sizeof(fourtySix)];
234
+    }
235
+//    escM:{ESC, 'M', 0x00 };
236
+    [toSend appendBytes:ESC length:sizeof(ESC)];
237
+    [toSend appendBytes:M length:sizeof(M)];
238
+    [toSend appendBytes:&fontType length:sizeof(fontType)];
239
+    // text data
240
+    [toSend appendData:bytes];
241
+    //LF
242
+   // [toSend appendBytes:&NL length:sizeof(NL)];
243
+  
244
+    NSLog(@"Goting to write text : %@",text);
245
+    NSLog(@"With data: %@",toSend);
246
+    [RNBluetoothManager writeValue:toSend withDelegate:delegate];
247
+}
248
+
249
+RCT_EXPORT_METHOD(rotate:(NSInteger *)rotate
250
+                  withResolver:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject)
251
+{
252
+    if(RNBluetoothManager.isConnected){
253
+        //    //取消/选择90度旋转打印
254
+       // public static byte[] ESC_V = new byte[] {ESC, 'V', 0x00 };
255
+        NSMutableData *data = [[NSMutableData alloc] init];
256
+        Byte rotateBytes[] = {(int)rotate};
257
+        [data appendBytes:ESC length:1];
258
+        [data appendBytes:V length:1];
259
+        [data appendBytes:rotateBytes length:1];
260
+        pendingReject = reject;
261
+        pendingResolve = resolve;
262
+        [RNBluetoothManager writeValue:data withDelegate:self];
263
+    }else{
264
+           reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
265
+    }
266
+//        if(sendDataByte(PrinterCommand.POS_Set_Rotate(rotate))){
267
+//            promise.resolve(null);
268
+//        }else{
269
+//            promise.reject("COMMAND_NOT_SEND");
270
+//        }
271
+}
272
+
273
+RCT_EXPORT_METHOD(printerAlign:(NSInteger *) align
274
+                   withResolver:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject)
275
+{
276
+    if(RNBluetoothManager.isConnected){
277
+        //if ((align < 0 || align > 2) && (align < 48 || align > 50)) return null;
278
+        if((align < 0 || align > 2) && (align < 48 || align > 50)){
279
+             reject(@"INVALD_PARAMETERS",@"INVALD_PARAMETERS",nil);
280
+        }else{
281
+            //{ESC, 'a', 0x00 }
282
+            NSMutableData *toSend = [[NSMutableData alloc] init];
283
+            [toSend appendBytes:ESC length:sizeof(ESC)];
284
+            [toSend appendBytes:A length:sizeof(A)];
285
+            [toSend appendBytes:&align length:sizeof(align)];
286
+            pendingReject =reject;
287
+            pendingResolve =resolve;
288
+            [RNBluetoothManager writeValue:toSend withDelegate:self];
289
+        }
290
+    }else{
291
+         reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
292
+    }
293
+}
294
+
295
+RCT_EXPORT_METHOD(printColumn:(NSArray *)columnWidths
296
+                  withAligns:(NSArray *) columnAligns
297
+                  texts:(NSArray *) columnTexts
298
+                  options:(NSDictionary *)options
299
+                  resolver:(RCTPromiseResolveBlock) resolve
300
+                  rejecter:(RCTPromiseRejectBlock) reject)
301
+{
302
+    if(!RNBluetoothManager.isConnected){
303
+        reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
304
+    }else{
305
+        @try{
306
+            NSString *encodig = [options valueForKey:@"encoding"];
307
+            if(!encodig) encodig=@"GBK";
308
+            NSInteger codePage = [[options valueForKey:@"codepage"] integerValue];NSLog(@"Got codepage from options: %ld",codePage);
309
+            if(!codePage) codePage = 0;
310
+            NSInteger widthTimes = [[options valueForKey:@"widthtimes"] integerValue];
311
+            if(!widthTimes) widthTimes = 0;
312
+            NSInteger heigthTime = [[options valueForKey:@"heigthtimes"] integerValue];
313
+            if(!heigthTime) heigthTime =0;
314
+            NSInteger fontType = [[options valueForKey:@"fontType"] integerValue];
315
+            if(!fontType) fontType = 0;
316
+          /**
317
+                 * [column1-1,
318
+                 * column1-2,
319
+                 * column1-3 ... column1-n]
320
+                 * ,
321
+                 *  [column2-1,
322
+                 * column2-2,
323
+                 * column2-3 ... column2-n]
324
+                 *
325
+                 * ...
326
+                 *
327
+                 */
328
+            NSMutableArray *table =[[NSMutableArray alloc] init];
329
+            
330
+                /**splits the column text to few rows and applies the alignment **/
331
+                int padding = 1;
332
+                for(int i=0;i< [columnWidths count];i++){
333
+                    NSInteger width =[[columnWidths objectAtIndex:i ] integerValue] - padding;//1 char padding
334
+                    NSString *text = [columnTexts objectAtIndex:i]; //String.copyValueOf(columnTexts.getString(i).toCharArray());
335
+                    NSLog(@"Text in column: %@",text);
336
+                    NSMutableArray<ColumnSplitedString *> *splited = [[NSMutableArray alloc] init];
337
+                    //List<ColumnSplitedString> splited = new ArrayList<ColumnSplitedString>();
338
+                    int shorter = 0;
339
+                    int counter = 0;
340
+                   NSMutableString *temp = [[NSMutableString alloc] init];
341
+                   
342
+                    for(int c=0;c<[text length];c++){
343
+                        unichar ch = [text characterAtIndex:c];
344
+                        int l = (ch>= 0x4e00 && ch <= 0x9fff)?2:1;
345
+                        if (l==2){
346
+                            shorter=shorter+1;
347
+                        }
348
+                        [temp appendString:[text substringWithRange:NSMakeRange(c, 1)]];
349
+                        if(counter+l<width){
350
+                            counter = counter+l;
351
+                        }else{
352
+                            ColumnSplitedString *css = [[ColumnSplitedString alloc] init];
353
+                            css.str = temp;
354
+                            css.shorter = shorter;
355
+                            [splited addObject:css];
356
+                            temp = [[NSMutableString alloc] init];
357
+                            counter=0;
358
+                            shorter=0;
359
+                        }
360
+                    }
361
+                    if([temp length]>0) {
362
+                        ColumnSplitedString *css = [[ColumnSplitedString alloc] init];
363
+                        css.str = temp;
364
+                        css.shorter = shorter;
365
+                        [splited addObject:css];
366
+                    }
367
+                    NSInteger align =[[columnAligns objectAtIndex:i] integerValue];
368
+            
369
+                    NSMutableArray *formated = [[NSMutableArray alloc] init];
370
+                    for(ColumnSplitedString *s in splited){
371
+                        NSMutableString *empty = [[NSMutableString alloc] init];
372
+                        for(int w=0;w<(width+padding-s.shorter);w++){
373
+                            [empty appendString:@" "];
374
+                        }
375
+                        int startIdx = 0;
376
+                        NSString *ss = s.str;
377
+                        if(align == 1 && [ss length]<(width-s.shorter)){
378
+                            startIdx = (int)(width-s.shorter-[ss length])/2;
379
+                            if(startIdx+[ss length]>width-s.shorter){
380
+                                startIdx--;
381
+                            }
382
+                            if(startIdx<0){
383
+                                startIdx=0;
384
+                            }
385
+                        }else if(align==2 && [ss length]<(width-s.shorter)){
386
+                            startIdx =(int)(width - s.shorter-[ss length]);
387
+                        }
388
+                        NSInteger length =[ss length];
389
+//                        if(length+startIdx>[empty length]){
390
+//                            length = [empty length]-startIdx;
391
+//                        }
392
+                        NSLog(@"empty(length: %lu) replace from %d length %lu with str:%@)",[empty length],startIdx,length,ss);
393
+                        [empty replaceCharactersInRange:NSMakeRange(startIdx, length) withString:ss];
394
+                        [formated addObject:empty];
395
+                    }
396
+                    [table addObject:formated];
397
+                }
398
+            
399
+            /**  try to find the max row count of the table **/
400
+                NSInteger maxRowCount = 0;
401
+                for(int i=0;i<[table count]/*column count*/;i++){
402
+                    NSArray *rows = [table objectAtIndex:i]; // row data in current column
403
+                    if([rows count]>maxRowCount){
404
+                        maxRowCount = [rows count];// try to find the max row count;
405
+                    }
406
+                }
407
+            
408
+                /** loop table again to fill the rows **/
409
+            NSMutableArray<NSMutableString *> *rowsToPrint = [[NSMutableArray alloc] init];
410
+                for(int column=0;column<[table count]/*column count*/;column++){
411
+                    NSArray *rows = [table objectAtIndex:column]; // row data in current column
412
+                    for(int row=0;row<maxRowCount;row++){
413
+                        if([rowsToPrint count]<=row || [rowsToPrint objectAtIndex:row] ==nil){
414
+                           [rowsToPrint setObject:[[NSMutableString alloc] init] atIndexedSubscript:row];
415
+                        }
416
+                        if(row<[rows count]){
417
+                            //got the row of this column
418
+                            [(NSMutableString *)[rowsToPrint objectAtIndex:row] appendString:[rows objectAtIndex:row]];//.append(rows.get(row));
419
+                        }else{
420
+                            NSInteger w = [[columnWidths objectAtIndex:column] integerValue]; //columnWidths.getInt(column);
421
+                            NSMutableString *empty = [[NSMutableString alloc] init];
422
+                            for(int i=0;i<w;i++){
423
+                                [empty appendString:@" "]; //empty.append(" ");
424
+                            }
425
+                             [(NSMutableString *)[rowsToPrint objectAtIndex:row] appendString:empty];//Append spaces to ensure the format
426
+                        }
427
+                    }
428
+                }
429
+            
430
+                /** loops the rows and print **/
431
+            PrintColumnBleWriteDelegate *delegate = [[PrintColumnBleWriteDelegate alloc] init];
432
+            delegate.now = 0;
433
+            delegate.error = false;
434
+            delegate.pendingReject = reject;
435
+            delegate.pendingResolve =resolve;
436
+            delegate.canceled = false;
437
+            delegate.encodig = encodig;
438
+            delegate.widthTimes = widthTimes;
439
+            delegate.heightTimes = heigthTime;
440
+            delegate.fontType = fontType;
441
+            delegate.codePage = codePage;
442
+            delegate.printer = self;
443
+            [delegate printColumn:rowsToPrint withMaxcount:maxRowCount];
444
+        }
445
+        @catch(NSException *e){
446
+            NSLog(@"print text exception: %@",[e callStackSymbols]);
447
+            reject(e.name.description,e.name.description,nil);
448
+        }
449
+        
450
+    }
451
+}
452
+
453
+RCT_EXPORT_METHOD(setBlob:(NSInteger) sp
454
+                  withResolver:(RCTPromiseResolveBlock) resolve
455
+                  rejecter:(RCTPromiseRejectBlock) reject)
456
+{
457
+    //\\    //选择/取消加粗指令
458
+//    public static byte[] ESC_G = new byte[] {ESC, 'G', 0x00 };
459
+//    public static byte[] ESC_E = new byte[] {ESC, 'E', 0x00 };
460
+    //E+G
461
+    NSMutableData *toSend = [[NSMutableData alloc] init];
462
+    [toSend appendBytes:&ESC length:sizeof(ESC)];
463
+    [toSend appendBytes:&G length:sizeof(G)];
464
+    [toSend appendBytes:&sp length:sizeof(sp)];
465
+    [toSend appendBytes:&ESC length:sizeof(ESC)];
466
+    [toSend appendBytes:&E length:sizeof(E)];
467
+    [toSend appendBytes:&sp length:sizeof(sp)];
468
+    pendingReject =reject;
469
+    pendingResolve = resolve;
470
+    [RNBluetoothManager writeValue:toSend withDelegate:self];
471
+}
472
+
473
+RCT_EXPORT_METHOD(printPic:(NSString *) base64encodeStr withOptions:(NSDictionary *) options
474
+                  resolver:(RCTPromiseResolveBlock) resolve
475
+                  rejecter:(RCTPromiseRejectBlock) reject)
476
+{
477
+    if(RNBluetoothManager.isConnected){
478
+        @try{
479
+            NSInteger nWidth = [[options valueForKey:@"width"] integerValue];
480
+            if(!nWidth) nWidth = _deviceWidth;
481
+            //TODO:need to handel param "left" in the options.
482
+            NSInteger paddingLeft = [[options valueForKey:@"left"] integerValue];
483
+            if(!paddingLeft) paddingLeft = 0;
484
+            NSData *decoded = [[NSData alloc] initWithBase64EncodedString:base64encodeStr options:0 ];
485
+            UIImage *srcImage = [[UIImage alloc] initWithData:decoded scale:1];
486
+            NSData *jpgData = UIImageJPEGRepresentation(srcImage, 1);
487
+            UIImage *jpgImage = [[UIImage alloc] initWithData:jpgData];
488
+            //mBitmap.getHeight() * width / mBitmap.getWidth();
489
+            NSInteger imgHeight = jpgImage.size.height;
490
+            NSInteger imagWidth = jpgImage.size.width;
491
+            NSInteger width = nWidth;//((int)(((nWidth*0.86)+7)/8))*8-7;
492
+            CGSize size = CGSizeMake(width, imgHeight*width/imagWidth);
493
+            UIImage *scaled = [ImageUtils imageWithImage:jpgImage scaledToFillSize:size];
494
+            if(paddingLeft>0){
495
+                scaled = [ImageUtils imagePadLeft:paddingLeft withSource:scaled];
496
+                size =[scaled size];
497
+            }
498
+            
499
+            unsigned char * graImage = [ImageUtils imageToGreyImage:scaled];
500
+            unsigned char * formatedData = [ImageUtils format_K_threshold:graImage width:size.width height:size.height];
501
+            NSData *dataToPrint = [ImageUtils eachLinePixToCmd:formatedData nWidth:size.width nHeight:size.height nMode:0];
502
+            PrintImageBleWriteDelegate *delegate = [[PrintImageBleWriteDelegate alloc] init];
503
+            delegate.pendingResolve = resolve;
504
+            delegate.pendingReject = reject;
505
+            delegate.width = width;
506
+            delegate.toPrint  = dataToPrint;
507
+            delegate.now = 0;
508
+            [delegate print];
509
+        }
510
+        @catch(NSException *e){
511
+            NSLog(@"ERROR IN PRINTING IMG: %@",[e callStackSymbols]);
512
+              reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
513
+        }
514
+    }else{
515
+        reject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
516
+    }
517
+}
518
+
519
+RCT_EXPORT_METHOD(printQRCode:(NSString *)content
520
+                  withSize:(NSInteger) size
521
+                  correctionLevel:(NSInteger) correctionLevel
522
+                  andResolver:(RCTPromiseResolveBlock) resolve
523
+                  rejecter:(RCTPromiseRejectBlock) reject)
524
+{
525
+    NSLog(@"QRCODE TO PRINT: %@",content);
526
+    NSError *error = nil;
527
+    ZXEncodeHints *hints = [ZXEncodeHints hints];
528
+    hints.encoding=NSUTF8StringEncoding;
529
+    hints.margin=0;
530
+    hints.errorCorrectionLevel = [self findCorrectionLevel:correctionLevel];
531
+    
532
+    ZXMultiFormatWriter *writer = [ZXMultiFormatWriter writer];
533
+    ZXBitMatrix *result = [writer encode:content
534
+                                  format:kBarcodeFormatQRCode
535
+                                   width:(int)size
536
+                                  height:(int)size
537
+                                    hints:hints
538
+                                   error:&error];
539
+    if(error || !result){
540
+        reject(@"ERROR_IN_CREATE_QRCODE",@"ERROR_IN_CREATE_QRCODE",nil);
541
+    }else{
542
+        CGImageRef image = [[ZXImage imageWithMatrix:result] cgimage];
543
+        uint8_t * graImage = [ImageUtils imageToGreyImage:[UIImage imageWithCGImage:image]];
544
+        unsigned char * formatedData = [ImageUtils format_K_threshold:graImage width:size height:size];
545
+        NSData *dataToPrint = [ImageUtils eachLinePixToCmd:formatedData nWidth:size nHeight:size nMode:0];
546
+        PrintImageBleWriteDelegate *delegate = [[PrintImageBleWriteDelegate alloc] init];
547
+        delegate.pendingResolve=resolve;
548
+        delegate.pendingReject = reject;
549
+        delegate.width = size;
550
+        delegate.toPrint  = dataToPrint;
551
+        delegate.now = 0;
552
+        [delegate print];
553
+    }
554
+}
555
+
556
+RCT_EXPORT_METHOD(printBarCode:(NSString *) str withType:(NSInteger)
557
+                  nType width:(NSInteger) nWidth heigth:(NSInteger) nHeight
558
+                  hriFontType:(NSInteger) nHriFontType hriFontPosition:(NSInteger) nHriFontPosition
559
+                  andResolver:(RCTPromiseResolveBlock) resolve
560
+                  rejecter:(RCTPromiseRejectBlock) reject)
561
+{
562
+    if (nType < 0x41 | nType > 0x49 | nWidth < 2 | nWidth > 6
563
+        | nHeight < 1 | nHeight > 255 | (!str||[str length]<1))
564
+      {
565
+          reject(@"INVALID_PARAMETER",@"INVALID_PARAMETER",nil);
566
+          return;
567
+      }
568
+    
569
+    NSData *conentData = [str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
570
+    NSMutableData *toPrint = [[NSMutableData alloc] init];
571
+    int8_t * command = malloc(16);
572
+        command[0] = 29 ;//GS
573
+        command[1] = 119;//W
574
+        command[2] = nWidth;
575
+        command[3] = 29;//GS
576
+        command[4] = 104;//h
577
+        command[5] = nHeight;
578
+        command[6] = 29;//GS
579
+        command[7] = 102;//f
580
+        command[8] = (nHriFontType & 0x01);
581
+        command[9] = 29;//GS
582
+        command[10] = 72;//H
583
+        command[11] = (nHriFontPosition & 0x03);
584
+        command[12] = 29;//GS
585
+        command[13] = 107;//k
586
+        command[14] = nType;
587
+        command[15] = [conentData length];
588
+    [toPrint appendBytes:command length:16];
589
+    [toPrint appendData:conentData];
590
+    
591
+    pendingReject = reject;
592
+    pendingResolve = resolve;
593
+    [RNBluetoothManager writeValue:toPrint withDelegate:self];
594
+}
595
+//  L:1,
596
+//M:0,
597
+//Q:3,
598
+//H:2
599
+-(ZXQRCodeErrorCorrectionLevel *)findCorrectionLevel:(NSInteger)level
600
+{
601
+    switch (level) {
602
+        case 1:
603
+            return [[ZXQRCodeErrorCorrectionLevel alloc] initWithOrdinal:0 bits:0x01 name:@"L"];
604
+            break;
605
+        case 2:
606
+             return [[ZXQRCodeErrorCorrectionLevel alloc] initWithOrdinal:3 bits:0x02 name:@"H"];
607
+        case 3:
608
+             return [[ZXQRCodeErrorCorrectionLevel alloc] initWithOrdinal:2 bits:0x03 name:@"Q"];
609
+        default:
610
+             return [[ZXQRCodeErrorCorrectionLevel alloc] initWithOrdinal:1 bits:0x00 name:@"M"];
611
+            break;
612
+    }
613
+}
614
+
615
+- (void) didWriteDataToBle: (BOOL)success{
616
+    if(success){
617
+        pendingResolve(nil);
618
+    }else{NSLog(@"REJECT<REJECT<REJECT<REJECT<REJECT<");
619
+        pendingReject(@"COMMAND_NOT_SEND",@"COMMAND_NOT_SEND",nil);
620
+    }
621
+    pendingReject = nil;
622
+    pendingResolve = nil;
623
+    [NSThread sleepForTimeInterval:0.05f];//slow down
624
+}
625
+
626
+@end

+ 444
- 0
ios/RNBluetoothEscposPrinter.xcodeproj/project.pbxproj View File

@@ -0,0 +1,444 @@
1
+// !$*UTF8*$!
2
+{
3
+	archiveVersion = 1;
4
+	classes = {
5
+	};
6
+	objectVersion = 46;
7
+	objects = {
8
+
9
+/* Begin PBXBuildFile section */
10
+		83A1E920216BA095004F0811 /* PrintImageBleWriteDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 83A1E91F216BA095004F0811 /* PrintImageBleWriteDelegate.m */; };
11
+		83A1E92D216CF6C4004F0811 /* RNTscCommand.m in Sources */ = {isa = PBXBuildFile; fileRef = 83A1E92C216CF6C3004F0811 /* RNTscCommand.m */; };
12
+		83B72B45216A0FEA007780F3 /* PrintColumnBleWriteDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 83B72B3B216A0FE9007780F3 /* PrintColumnBleWriteDelegate.m */; };
13
+		83B72B46216A0FEA007780F3 /* ColumnSplitedString.m in Sources */ = {isa = PBXBuildFile; fileRef = 83B72B44216A0FEA007780F3 /* ColumnSplitedString.m */; };
14
+		83B72B48216A0FF4007780F3 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83B72B47216A0FF4007780F3 /* UIKit.framework */; };
15
+		83B72B7C216A70D2007780F3 /* ImageUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 83B72B7B216A70D1007780F3 /* ImageUtils.m */; };
16
+		83B72B7D216A70D6007780F3 /* libZXingObjC-iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 83E5D46E215E51A30009D216 /* libZXingObjC-iOS.a */; };
17
+		83E5D47C215E57100009D216 /* RNBluetoothManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 83E5D47B215E57100009D216 /* RNBluetoothManager.m */; };
18
+		83E5D47F215E5A880009D216 /* CoreBluetooth.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83E5D47E215E5A880009D216 /* CoreBluetooth.framework */; };
19
+		83FAD6B12161C9C6001C4911 /* RNBluetoothTscPrinter.m in Sources */ = {isa = PBXBuildFile; fileRef = 83FAD6B02161C9C6001C4911 /* RNBluetoothTscPrinter.m */; };
20
+		B3E7B58A1CC2AC0600A0062D /* RNBluetoothEscposPrinter.m in Sources */ = {isa = PBXBuildFile; fileRef = B3E7B5891CC2AC0600A0062D /* RNBluetoothEscposPrinter.m */; };
21
+/* End PBXBuildFile section */
22
+
23
+/* Begin PBXContainerItemProxy section */
24
+		83E5D46D215E51A30009D216 /* PBXContainerItemProxy */ = {
25
+			isa = PBXContainerItemProxy;
26
+			containerPortal = 83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */;
27
+			proxyType = 2;
28
+			remoteGlobalIDString = 25403CB3166A96FA00E13304;
29
+			remoteInfo = "ZXingObjC-iOS";
30
+		};
31
+		83E5D46F215E51A30009D216 /* PBXContainerItemProxy */ = {
32
+			isa = PBXContainerItemProxy;
33
+			containerPortal = 83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */;
34
+			proxyType = 2;
35
+			remoteGlobalIDString = 25403CC4166A96FA00E13304;
36
+			remoteInfo = "Unit Tests iOS";
37
+		};
38
+		83E5D471215E51A30009D216 /* PBXContainerItemProxy */ = {
39
+			isa = PBXContainerItemProxy;
40
+			containerPortal = 83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */;
41
+			proxyType = 2;
42
+			remoteGlobalIDString = 25404166166AADAC00E13304;
43
+			remoteInfo = "ZXingObjC-osx";
44
+		};
45
+		83E5D473215E51A30009D216 /* PBXContainerItemProxy */ = {
46
+			isa = PBXContainerItemProxy;
47
+			containerPortal = 83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */;
48
+			proxyType = 2;
49
+			remoteGlobalIDString = 25404178166AADAC00E13304;
50
+			remoteInfo = "Unit Tests OS X";
51
+		};
52
+		83E5D475215E51A30009D216 /* PBXContainerItemProxy */ = {
53
+			isa = PBXContainerItemProxy;
54
+			containerPortal = 83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */;
55
+			proxyType = 2;
56
+			remoteGlobalIDString = 2540439E166ABA0A00E13304;
57
+			remoteInfo = "OS X Framework";
58
+		};
59
+		83E5D477215E51A30009D216 /* PBXContainerItemProxy */ = {
60
+			isa = PBXContainerItemProxy;
61
+			containerPortal = 83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */;
62
+			proxyType = 2;
63
+			remoteGlobalIDString = DB72547F1A523C9200EFF81B;
64
+			remoteInfo = "iOS Framework";
65
+		};
66
+/* End PBXContainerItemProxy section */
67
+
68
+/* Begin PBXCopyFilesBuildPhase section */
69
+		58B511D91A9E6C8500147676 /* CopyFiles */ = {
70
+			isa = PBXCopyFilesBuildPhase;
71
+			buildActionMask = 2147483647;
72
+			dstPath = "include/$(PRODUCT_NAME)";
73
+			dstSubfolderSpec = 16;
74
+			files = (
75
+			);
76
+			runOnlyForDeploymentPostprocessing = 0;
77
+		};
78
+/* End PBXCopyFilesBuildPhase section */
79
+
80
+/* Begin PBXFileReference section */
81
+		134814201AA4EA6300B7C361 /* libRNBluetoothEscposPrinter.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libRNBluetoothEscposPrinter.a; sourceTree = BUILT_PRODUCTS_DIR; };
82
+		83A1E918216BA094004F0811 /* PrintImageBleWriteDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrintImageBleWriteDelegate.h; sourceTree = "<group>"; };
83
+		83A1E91F216BA095004F0811 /* PrintImageBleWriteDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PrintImageBleWriteDelegate.m; sourceTree = "<group>"; };
84
+		83A1E925216CF6C3004F0811 /* RNTscCommand.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNTscCommand.h; sourceTree = "<group>"; };
85
+		83A1E92C216CF6C3004F0811 /* RNTscCommand.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNTscCommand.m; sourceTree = "<group>"; };
86
+		83B72B3B216A0FE9007780F3 /* PrintColumnBleWriteDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PrintColumnBleWriteDelegate.m; sourceTree = "<group>"; };
87
+		83B72B42216A0FEA007780F3 /* PrintColumnBleWriteDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrintColumnBleWriteDelegate.h; sourceTree = "<group>"; };
88
+		83B72B43216A0FEA007780F3 /* ColumnSplitedString.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ColumnSplitedString.h; sourceTree = "<group>"; };
89
+		83B72B44216A0FEA007780F3 /* ColumnSplitedString.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ColumnSplitedString.m; sourceTree = "<group>"; };
90
+		83B72B47216A0FF4007780F3 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
91
+		83B72B74216A70D1007780F3 /* ImageUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ImageUtils.h; sourceTree = "<group>"; };
92
+		83B72B7B216A70D1007780F3 /* ImageUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ImageUtils.m; sourceTree = "<group>"; };
93
+		83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = ZXingObjC.xcodeproj; path = "ZXingObjC-3.2.2/ZXingObjC.xcodeproj"; sourceTree = "<group>"; };
94
+		83E5D47A215E564B0009D216 /* RNBluetoothManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RNBluetoothManager.h; sourceTree = "<group>"; };
95
+		83E5D47B215E57100009D216 /* RNBluetoothManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RNBluetoothManager.m; sourceTree = "<group>"; };
96
+		83E5D47E215E5A880009D216 /* CoreBluetooth.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreBluetooth.framework; path = System/Library/Frameworks/CoreBluetooth.framework; sourceTree = SDKROOT; };
97
+		83FAD6A92161C977001C4911 /* RNBluetoothTscPrinter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RNBluetoothTscPrinter.h; sourceTree = "<group>"; };
98
+		83FAD6B02161C9C6001C4911 /* RNBluetoothTscPrinter.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RNBluetoothTscPrinter.m; sourceTree = "<group>"; };
99
+		B3E7B5881CC2AC0600A0062D /* RNBluetoothEscposPrinter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNBluetoothEscposPrinter.h; sourceTree = "<group>"; };
100
+		B3E7B5891CC2AC0600A0062D /* RNBluetoothEscposPrinter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNBluetoothEscposPrinter.m; sourceTree = "<group>"; };
101
+/* End PBXFileReference section */
102
+
103
+/* Begin PBXFrameworksBuildPhase section */
104
+		58B511D81A9E6C8500147676 /* Frameworks */ = {
105
+			isa = PBXFrameworksBuildPhase;
106
+			buildActionMask = 2147483647;
107
+			files = (
108
+				83B72B7D216A70D6007780F3 /* libZXingObjC-iOS.a in Frameworks */,
109
+				83B72B48216A0FF4007780F3 /* UIKit.framework in Frameworks */,
110
+				83E5D47F215E5A880009D216 /* CoreBluetooth.framework in Frameworks */,
111
+			);
112
+			runOnlyForDeploymentPostprocessing = 0;
113
+		};
114
+/* End PBXFrameworksBuildPhase section */
115
+
116
+/* Begin PBXGroup section */
117
+		134814211AA4EA7D00B7C361 /* Products */ = {
118
+			isa = PBXGroup;
119
+			children = (
120
+				134814201AA4EA6300B7C361 /* libRNBluetoothEscposPrinter.a */,
121
+			);
122
+			name = Products;
123
+			sourceTree = "<group>";
124
+		};
125
+		58B511D21A9E6C8500147676 = {
126
+			isa = PBXGroup;
127
+			children = (
128
+				83A1E925216CF6C3004F0811 /* RNTscCommand.h */,
129
+				83A1E92C216CF6C3004F0811 /* RNTscCommand.m */,
130
+				83A1E918216BA094004F0811 /* PrintImageBleWriteDelegate.h */,
131
+				83A1E91F216BA095004F0811 /* PrintImageBleWriteDelegate.m */,
132
+				83B72B74216A70D1007780F3 /* ImageUtils.h */,
133
+				83B72B7B216A70D1007780F3 /* ImageUtils.m */,
134
+				83B72B43216A0FEA007780F3 /* ColumnSplitedString.h */,
135
+				83B72B44216A0FEA007780F3 /* ColumnSplitedString.m */,
136
+				83B72B42216A0FEA007780F3 /* PrintColumnBleWriteDelegate.h */,
137
+				83B72B3B216A0FE9007780F3 /* PrintColumnBleWriteDelegate.m */,
138
+				83FAD6B02161C9C6001C4911 /* RNBluetoothTscPrinter.m */,
139
+				83FAD6A92161C977001C4911 /* RNBluetoothTscPrinter.h */,
140
+				83E5D47B215E57100009D216 /* RNBluetoothManager.m */,
141
+				83E5D47A215E564B0009D216 /* RNBluetoothManager.h */,
142
+				83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */,
143
+				B3E7B5881CC2AC0600A0062D /* RNBluetoothEscposPrinter.h */,
144
+				B3E7B5891CC2AC0600A0062D /* RNBluetoothEscposPrinter.m */,
145
+				134814211AA4EA7D00B7C361 /* Products */,
146
+				83E5D47D215E5A880009D216 /* Frameworks */,
147
+			);
148
+			sourceTree = "<group>";
149
+		};
150
+		83E5D465215E51A20009D216 /* Products */ = {
151
+			isa = PBXGroup;
152
+			children = (
153
+				83E5D46E215E51A30009D216 /* libZXingObjC-iOS.a */,
154
+				83E5D470215E51A30009D216 /* Unit Tests iOS.xctest */,
155
+				83E5D472215E51A30009D216 /* libZXingObjC-osx.a */,
156
+				83E5D474215E51A30009D216 /* Unit Tests OS X.xctest */,
157
+				83E5D476215E51A30009D216 /* ZXingObjC.framework */,
158
+				83E5D478215E51A30009D216 /* ZXingObjC.framework */,
159
+			);
160
+			name = Products;
161
+			sourceTree = "<group>";
162
+		};
163
+		83E5D47D215E5A880009D216 /* Frameworks */ = {
164
+			isa = PBXGroup;
165
+			children = (
166
+				83B72B47216A0FF4007780F3 /* UIKit.framework */,
167
+				83E5D47E215E5A880009D216 /* CoreBluetooth.framework */,
168
+			);
169
+			name = Frameworks;
170
+			sourceTree = "<group>";
171
+		};
172
+/* End PBXGroup section */
173
+
174
+/* Begin PBXNativeTarget section */
175
+		58B511DA1A9E6C8500147676 /* RNBluetoothEscposPrinter */ = {
176
+			isa = PBXNativeTarget;
177
+			buildConfigurationList = 58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNBluetoothEscposPrinter" */;
178
+			buildPhases = (
179
+				58B511D71A9E6C8500147676 /* Sources */,
180
+				58B511D81A9E6C8500147676 /* Frameworks */,
181
+				58B511D91A9E6C8500147676 /* CopyFiles */,
182
+			);
183
+			buildRules = (
184
+			);
185
+			dependencies = (
186
+			);
187
+			name = RNBluetoothEscposPrinter;
188
+			productName = RCTDataManager;
189
+			productReference = 134814201AA4EA6300B7C361 /* libRNBluetoothEscposPrinter.a */;
190
+			productType = "com.apple.product-type.library.static";
191
+		};
192
+/* End PBXNativeTarget section */
193
+
194
+/* Begin PBXProject section */
195
+		58B511D31A9E6C8500147676 /* Project object */ = {
196
+			isa = PBXProject;
197
+			attributes = {
198
+				LastUpgradeCheck = 0830;
199
+				ORGANIZATIONNAME = Facebook;
200
+				TargetAttributes = {
201
+					58B511DA1A9E6C8500147676 = {
202
+						CreatedOnToolsVersion = 6.1.1;
203
+					};
204
+				};
205
+			};
206
+			buildConfigurationList = 58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "RNBluetoothEscposPrinter" */;
207
+			compatibilityVersion = "Xcode 3.2";
208
+			developmentRegion = English;
209
+			hasScannedForEncodings = 0;
210
+			knownRegions = (
211
+				en,
212
+			);
213
+			mainGroup = 58B511D21A9E6C8500147676;
214
+			productRefGroup = 58B511D21A9E6C8500147676;
215
+			projectDirPath = "";
216
+			projectReferences = (
217
+				{
218
+					ProductGroup = 83E5D465215E51A20009D216 /* Products */;
219
+					ProjectRef = 83E5D464215E51A20009D216 /* ZXingObjC.xcodeproj */;
220
+				},
221
+			);
222
+			projectRoot = "";
223
+			targets = (
224
+				58B511DA1A9E6C8500147676 /* RNBluetoothEscposPrinter */,
225
+			);
226
+		};
227
+/* End PBXProject section */
228
+
229
+/* Begin PBXReferenceProxy section */
230
+		83E5D46E215E51A30009D216 /* libZXingObjC-iOS.a */ = {
231
+			isa = PBXReferenceProxy;
232
+			fileType = archive.ar;
233
+			path = "libZXingObjC-iOS.a";
234
+			remoteRef = 83E5D46D215E51A30009D216 /* PBXContainerItemProxy */;
235
+			sourceTree = BUILT_PRODUCTS_DIR;
236
+		};
237
+		83E5D470215E51A30009D216 /* Unit Tests iOS.xctest */ = {
238
+			isa = PBXReferenceProxy;
239
+			fileType = wrapper.cfbundle;
240
+			path = "Unit Tests iOS.xctest";
241
+			remoteRef = 83E5D46F215E51A30009D216 /* PBXContainerItemProxy */;
242
+			sourceTree = BUILT_PRODUCTS_DIR;
243
+		};
244
+		83E5D472215E51A30009D216 /* libZXingObjC-osx.a */ = {
245
+			isa = PBXReferenceProxy;
246
+			fileType = archive.ar;
247
+			path = "libZXingObjC-osx.a";
248
+			remoteRef = 83E5D471215E51A30009D216 /* PBXContainerItemProxy */;
249
+			sourceTree = BUILT_PRODUCTS_DIR;
250
+		};
251
+		83E5D474215E51A30009D216 /* Unit Tests OS X.xctest */ = {
252
+			isa = PBXReferenceProxy;
253
+			fileType = wrapper.cfbundle;
254
+			path = "Unit Tests OS X.xctest";
255
+			remoteRef = 83E5D473215E51A30009D216 /* PBXContainerItemProxy */;
256
+			sourceTree = BUILT_PRODUCTS_DIR;
257
+		};
258
+		83E5D476215E51A30009D216 /* ZXingObjC.framework */ = {
259
+			isa = PBXReferenceProxy;
260
+			fileType = wrapper.framework;
261
+			path = ZXingObjC.framework;
262
+			remoteRef = 83E5D475215E51A30009D216 /* PBXContainerItemProxy */;
263
+			sourceTree = BUILT_PRODUCTS_DIR;
264
+		};
265
+		83E5D478215E51A30009D216 /* ZXingObjC.framework */ = {
266
+			isa = PBXReferenceProxy;
267
+			fileType = wrapper.framework;
268
+			path = ZXingObjC.framework;
269
+			remoteRef = 83E5D477215E51A30009D216 /* PBXContainerItemProxy */;
270
+			sourceTree = BUILT_PRODUCTS_DIR;
271
+		};
272
+/* End PBXReferenceProxy section */
273
+
274
+/* Begin PBXSourcesBuildPhase section */
275
+		58B511D71A9E6C8500147676 /* Sources */ = {
276
+			isa = PBXSourcesBuildPhase;
277
+			buildActionMask = 2147483647;
278
+			files = (
279
+				83B72B45216A0FEA007780F3 /* PrintColumnBleWriteDelegate.m in Sources */,
280
+				B3E7B58A1CC2AC0600A0062D /* RNBluetoothEscposPrinter.m in Sources */,
281
+				83A1E92D216CF6C4004F0811 /* RNTscCommand.m in Sources */,
282
+				83B72B46216A0FEA007780F3 /* ColumnSplitedString.m in Sources */,
283
+				83B72B7C216A70D2007780F3 /* ImageUtils.m in Sources */,
284
+				83E5D47C215E57100009D216 /* RNBluetoothManager.m in Sources */,
285
+				83FAD6B12161C9C6001C4911 /* RNBluetoothTscPrinter.m in Sources */,
286
+				83A1E920216BA095004F0811 /* PrintImageBleWriteDelegate.m in Sources */,
287
+			);
288
+			runOnlyForDeploymentPostprocessing = 0;
289
+		};
290
+/* End PBXSourcesBuildPhase section */
291
+
292
+/* Begin XCBuildConfiguration section */
293
+		58B511ED1A9E6C8500147676 /* Debug */ = {
294
+			isa = XCBuildConfiguration;
295
+			buildSettings = {
296
+				ALWAYS_SEARCH_USER_PATHS = YES;
297
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
298
+				CLANG_CXX_LIBRARY = "libc++";
299
+				CLANG_ENABLE_MODULES = YES;
300
+				CLANG_ENABLE_OBJC_ARC = YES;
301
+				CLANG_WARN_BOOL_CONVERSION = YES;
302
+				CLANG_WARN_CONSTANT_CONVERSION = YES;
303
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
304
+				CLANG_WARN_EMPTY_BODY = YES;
305
+				CLANG_WARN_ENUM_CONVERSION = YES;
306
+				CLANG_WARN_INFINITE_RECURSION = YES;
307
+				CLANG_WARN_INT_CONVERSION = YES;
308
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
309
+				CLANG_WARN_SUSPICIOUS_MOVE = YES;
310
+				CLANG_WARN_UNREACHABLE_CODE = YES;
311
+				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
312
+				COPY_PHASE_STRIP = NO;
313
+				ENABLE_STRICT_OBJC_MSGSEND = YES;
314
+				ENABLE_TESTABILITY = YES;
315
+				GCC_C_LANGUAGE_STANDARD = gnu99;
316
+				GCC_DYNAMIC_NO_PIC = NO;
317
+				GCC_NO_COMMON_BLOCKS = YES;
318
+				GCC_OPTIMIZATION_LEVEL = 0;
319
+				GCC_PREPROCESSOR_DEFINITIONS = (
320
+					"DEBUG=1",
321
+					"$(inherited)",
322
+				);
323
+				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
324
+				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
325
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
326
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
327
+				GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
328
+				GCC_WARN_UNUSED_FUNCTION = YES;
329
+				GCC_WARN_UNUSED_VARIABLE = YES;
330
+				HEADER_SEARCH_PATHS = (
331
+					"$(inherited)",
332
+					/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
333
+					"$(SRCROOT)/../../../React/**",
334
+					"$(SRCROOT)/../../react-native/React/**",
335
+					"$(SRCROOT)/ZXingObjC-3.2.2/**",
336
+				);
337
+				IPHONEOS_DEPLOYMENT_TARGET = 8.0;
338
+				MTL_ENABLE_DEBUG_INFO = YES;
339
+				ONLY_ACTIVE_ARCH = YES;
340
+				SDKROOT = iphoneos;
341
+			};
342
+			name = Debug;
343
+		};
344
+		58B511EE1A9E6C8500147676 /* Release */ = {
345
+			isa = XCBuildConfiguration;
346
+			buildSettings = {
347
+				ALWAYS_SEARCH_USER_PATHS = YES;
348
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
349
+				CLANG_CXX_LIBRARY = "libc++";
350
+				CLANG_ENABLE_MODULES = YES;
351
+				CLANG_ENABLE_OBJC_ARC = YES;
352
+				CLANG_WARN_BOOL_CONVERSION = YES;
353
+				CLANG_WARN_CONSTANT_CONVERSION = YES;
354
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
355
+				CLANG_WARN_EMPTY_BODY = YES;
356
+				CLANG_WARN_ENUM_CONVERSION = YES;
357
+				CLANG_WARN_INFINITE_RECURSION = YES;
358
+				CLANG_WARN_INT_CONVERSION = YES;
359
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
360
+				CLANG_WARN_SUSPICIOUS_MOVE = YES;
361
+				CLANG_WARN_UNREACHABLE_CODE = YES;
362
+				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
363
+				COPY_PHASE_STRIP = YES;
364
+				ENABLE_NS_ASSERTIONS = NO;
365
+				ENABLE_STRICT_OBJC_MSGSEND = YES;
366
+				GCC_C_LANGUAGE_STANDARD = gnu99;
367
+				GCC_NO_COMMON_BLOCKS = YES;
368
+				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
369
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
370
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
371
+				GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
372
+				GCC_WARN_UNUSED_FUNCTION = YES;
373
+				GCC_WARN_UNUSED_VARIABLE = YES;
374
+				HEADER_SEARCH_PATHS = (
375
+					"$(inherited)",
376
+					/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
377
+					"$(SRCROOT)/../../../React/**",
378
+					"$(SRCROOT)/../../react-native/React/**",
379
+					"$(SRCROOT)/ZXingObjC-3.2.2/**",
380
+				);
381
+				IPHONEOS_DEPLOYMENT_TARGET = 8.0;
382
+				MTL_ENABLE_DEBUG_INFO = NO;
383
+				SDKROOT = iphoneos;
384
+				VALIDATE_PRODUCT = YES;
385
+			};
386
+			name = Release;
387
+		};
388
+		58B511F01A9E6C8500147676 /* Debug */ = {
389
+			isa = XCBuildConfiguration;
390
+			buildSettings = {
391
+				HEADER_SEARCH_PATHS = (
392
+					"$(inherited)",
393
+					/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
394
+					"$(SRCROOT)/../../../React/**",
395
+					"$(SRCROOT)/../../react-native/React/**",
396
+				);
397
+				LIBRARY_SEARCH_PATHS = "$(inherited)";
398
+				OTHER_LDFLAGS = "-ObjC";
399
+				PRODUCT_NAME = RNBluetoothEscposPrinter;
400
+				SKIP_INSTALL = YES;
401
+			};
402
+			name = Debug;
403
+		};
404
+		58B511F11A9E6C8500147676 /* Release */ = {
405
+			isa = XCBuildConfiguration;
406
+			buildSettings = {
407
+				HEADER_SEARCH_PATHS = (
408
+					"$(inherited)",
409
+					/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
410
+					"$(SRCROOT)/../../../React/**",
411
+					"$(SRCROOT)/../../react-native/React/**",
412
+				);
413
+				LIBRARY_SEARCH_PATHS = "$(inherited)";
414
+				OTHER_LDFLAGS = "-ObjC";
415
+				PRODUCT_NAME = RNBluetoothEscposPrinter;
416
+				SKIP_INSTALL = YES;
417
+			};
418
+			name = Release;
419
+		};
420
+/* End XCBuildConfiguration section */
421
+
422
+/* Begin XCConfigurationList section */
423
+		58B511D61A9E6C8500147676 /* Build configuration list for PBXProject "RNBluetoothEscposPrinter" */ = {
424
+			isa = XCConfigurationList;
425
+			buildConfigurations = (
426
+				58B511ED1A9E6C8500147676 /* Debug */,
427
+				58B511EE1A9E6C8500147676 /* Release */,
428
+			);
429
+			defaultConfigurationIsVisible = 0;
430
+			defaultConfigurationName = Release;
431
+		};
432
+		58B511EF1A9E6C8500147676 /* Build configuration list for PBXNativeTarget "RNBluetoothEscposPrinter" */ = {
433
+			isa = XCConfigurationList;
434
+			buildConfigurations = (
435
+				58B511F01A9E6C8500147676 /* Debug */,
436
+				58B511F11A9E6C8500147676 /* Release */,
437
+			);
438
+			defaultConfigurationIsVisible = 0;
439
+			defaultConfigurationName = Release;
440
+		};
441
+/* End XCConfigurationList section */
442
+	};
443
+	rootObject = 58B511D31A9E6C8500147676 /* Project object */;
444
+}

+ 7
- 0
ios/RNBluetoothEscposPrinter.xcodeproj/project.xcworkspace/contents.xcworkspacedata View File

@@ -0,0 +1,7 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<Workspace
3
+   version = "1.0">
4
+   <FileRef
5
+      location = "self:">
6
+   </FileRef>
7
+</Workspace>

+ 8
- 0
ios/RNBluetoothEscposPrinter.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist View File

@@ -0,0 +1,8 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+<plist version="1.0">
4
+<dict>
5
+	<key>IDEDidComputeMac32BitWarning</key>
6
+	<true/>
7
+</dict>
8
+</plist>

BIN
ios/RNBluetoothEscposPrinter.xcodeproj/project.xcworkspace/xcuserdata/januslo.xcuserdatad/UserInterfaceState.xcuserstate View File


+ 14
- 0
ios/RNBluetoothEscposPrinter.xcodeproj/xcuserdata/januslo.xcuserdatad/xcschemes/xcschememanagement.plist View File

@@ -0,0 +1,14 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+<plist version="1.0">
4
+<dict>
5
+	<key>SchemeUserState</key>
6
+	<dict>
7
+		<key>RNBluetoothEscposPrinter.xcscheme_^#shared#^_</key>
8
+		<dict>
9
+			<key>orderHint</key>
10
+			<integer>4</integer>
11
+		</dict>
12
+	</dict>
13
+</dict>
14
+</plist>

+ 9
- 0
ios/RNBluetoothEscposPrinter.xcworkspace/contents.xcworkspacedata View File

@@ -0,0 +1,9 @@
1
+// !$*UTF8*$!
2
+<?xml version="1.0" encoding="UTF-8"?>
3
+<Workspace
4
+   version = "1.0">
5
+   <FileRef
6
+      location = "group:RNBluetoothEscposPrinter.xcodeproj">
7
+   </FileRef>
8
+</Workspace>
9
+  

+ 29
- 0
ios/RNBluetoothManager.h View File

@@ -0,0 +1,29 @@
1
+//
2
+//  RNBluetoothManager.h
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/9/28.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+#import <React/RCTBridgeModule.h>
9
+#import <React/RCTEventEmitter.h>
10
+#import <CoreBluetooth/CoreBluetooth.h>
11
+
12
+@protocol WriteDataToBleDelegate <NSObject>
13
+@required
14
+- (void) didWriteDataToBle: (BOOL)success;
15
+@end
16
+
17
+@interface RNBluetoothManager <CBCentralManagerDelegate,CBPeripheralDelegate> : RCTEventEmitter <RCTBridgeModule>
18
+@property (strong, nonatomic) CBCentralManager      *centralManager;
19
+@property (nonatomic,copy) RCTPromiseResolveBlock scanResolveBlock;
20
+@property (nonatomic,copy) RCTPromiseRejectBlock scanRejectBlock;
21
+@property (strong,nonatomic) NSMutableDictionary <NSString *,CBPeripheral *> *foundDevices;
22
+@property (strong,nonatomic) NSString *waitingConnect;
23
+@property (nonatomic,copy) RCTPromiseResolveBlock connectResolveBlock;
24
+@property (nonatomic,copy) RCTPromiseRejectBlock connectRejectBlock;
25
++(void)writeValue:(NSData *) data withDelegate:(NSObject<WriteDataToBleDelegate> *) delegate;
26
++(Boolean)isConnected;
27
+-(void)initSupportServices;
28
+-(void)callStop;
29
+@end

+ 571
- 0
ios/RNBluetoothManager.m View File

@@ -0,0 +1,571 @@
1
+//
2
+//  RNBluethManager.m
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/9/28.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import "RNBluetoothManager.h"
11
+#import <CoreBluetooth/CoreBluetooth.h>
12
+@implementation RNBluetoothManager
13
+
14
+NSString *EVENT_DEVICE_ALREADY_PAIRED = @"EVENT_DEVICE_ALREADY_PAIRED";
15
+NSString *EVENT_DEVICE_DISCOVER_DONE = @"EVENT_DEVICE_DISCOVER_DONE";
16
+NSString *EVENT_DEVICE_FOUND = @"EVENT_DEVICE_FOUND";
17
+NSString *EVENT_CONNECTION_LOST = @"EVENT_CONNECTION_LOST";
18
+NSString *EVENT_UNABLE_CONNECT=@"EVENT_UNABLE_CONNECT";
19
+NSString *EVENT_CONNECTED=@"EVENT_CONNECTED";
20
+static NSArray<CBUUID *> *supportServices = nil;
21
+static NSDictionary *writeableCharactiscs = nil;
22
+bool hasListeners;
23
+static CBPeripheral *connected;
24
+static RNBluetoothManager *instance;
25
+static NSObject<WriteDataToBleDelegate> *writeDataDelegate;// delegate of write data resule;
26
+static NSData *toWrite;
27
+static NSTimer *timer;
28
+
29
++(Boolean)isConnected{
30
+    return !(connected==nil);
31
+}
32
+
33
++(void)writeValue:(NSData *) data withDelegate:(NSObject<WriteDataToBleDelegate> *) delegate
34
+{
35
+    @try{
36
+        writeDataDelegate = delegate;
37
+        toWrite = data;
38
+        connected.delegate = instance;
39
+        [connected discoverServices:supportServices];
40
+//    [connected writeValue:data forCharacteristic:[writeableCharactiscs objectForKey:supportServices[0]] type:CBCharacteristicWriteWithoutResponse];
41
+    }
42
+    @catch(NSException *e){
43
+        NSLog(@"error in writing data to %@,issue:%@",connected,e);
44
+        [writeDataDelegate didWriteDataToBle:false];
45
+    }
46
+}
47
+
48
+// Will be called when this module's first listener is added.
49
+-(void)startObserving {
50
+    hasListeners = YES;
51
+    // Set up any upstream listeners or background tasks as necessary
52
+}
53
+
54
+// Will be called when this module's last listener is removed, or on dealloc.
55
+-(void)stopObserving {
56
+    hasListeners = NO;
57
+    // Remove upstream listeners, stop unnecessary background tasks
58
+}
59
+
60
+/**
61
+ * Exports the constants to javascritp.
62
+ **/
63
+- (NSDictionary *)constantsToExport
64
+{
65
+    
66
+    /*
67
+     EVENT_DEVICE_ALREADY_PAIRED    Emits the devices array already paired
68
+     EVENT_DEVICE_DISCOVER_DONE    Emits when the scan done
69
+     EVENT_DEVICE_FOUND    Emits when device found during scan
70
+     EVENT_CONNECTION_LOST    Emits when device connection lost
71
+     EVENT_UNABLE_CONNECT    Emits when error occurs while trying to connect device
72
+     EVENT_CONNECTED    Emits when device connected
73
+     */
74
+
75
+    return @{ EVENT_DEVICE_ALREADY_PAIRED: EVENT_DEVICE_ALREADY_PAIRED,
76
+              EVENT_DEVICE_DISCOVER_DONE:EVENT_DEVICE_DISCOVER_DONE,
77
+              EVENT_DEVICE_FOUND:EVENT_DEVICE_FOUND,
78
+              EVENT_CONNECTION_LOST:EVENT_CONNECTION_LOST,
79
+              EVENT_UNABLE_CONNECT:EVENT_UNABLE_CONNECT,
80
+              EVENT_CONNECTED:EVENT_CONNECTED
81
+              };
82
+}
83
+- (dispatch_queue_t)methodQueue
84
+{
85
+    return dispatch_get_main_queue();
86
+}
87
+
88
++ (BOOL)requiresMainQueueSetup
89
+{
90
+    return YES;
91
+}
92
+
93
+/**
94
+ * Defines the event would be emited.
95
+ **/
96
+- (NSArray<NSString *> *)supportedEvents
97
+{
98
+    return @[EVENT_DEVICE_DISCOVER_DONE,
99
+             EVENT_DEVICE_FOUND,
100
+             EVENT_UNABLE_CONNECT,
101
+             EVENT_CONNECTION_LOST,
102
+             EVENT_CONNECTED,
103
+             EVENT_DEVICE_ALREADY_PAIRED];
104
+}
105
+
106
+
107
+RCT_EXPORT_MODULE(BluetoothManager);
108
+
109
+
110
+//isBluetoothEnabled
111
+RCT_EXPORT_METHOD(isBluetoothEnabled:(RCTPromiseResolveBlock)resolve
112
+                  rejecter:(RCTPromiseRejectBlock)reject)
113
+{
114
+    CBManagerState state = [self.centralManager  state];
115
+    resolve(state == CBManagerStatePoweredOn?@"true":@"false");//canot pass boolean or int value to resolve directly.
116
+}
117
+
118
+//enableBluetooth
119
+RCT_EXPORT_METHOD(enableBluetooth:(RCTPromiseResolveBlock)resolve
120
+                  rejecter:(RCTPromiseRejectBlock)reject)
121
+{
122
+    resolve(nil);
123
+}
124
+//disableBluetooth
125
+RCT_EXPORT_METHOD(disableBluetooth:(RCTPromiseResolveBlock)resolve
126
+                  rejecter:(RCTPromiseRejectBlock)reject)
127
+{
128
+    resolve(nil);
129
+}
130
+//scanDevices
131
+RCT_EXPORT_METHOD(scanDevices:(RCTPromiseResolveBlock)resolve
132
+                  rejecter:(RCTPromiseRejectBlock)reject)
133
+{
134
+    @try{
135
+        if(!self.centralManager || self.centralManager.state!=CBManagerStatePoweredOn){
136
+            reject(@"BLUETOOTCH_INVALID_STATE",@"BLUETOOTCH_INVALID_STATE",nil);
137
+            return;
138
+        }
139
+        if(self.centralManager.isScanning){
140
+            [self.centralManager stopScan];
141
+        }
142
+        self.scanResolveBlock = resolve;
143
+        self.scanRejectBlock = reject;
144
+        if(connected && connected.identifier){
145
+            NSDictionary *idAndName =@{@"address":connected.identifier.UUIDString,@"name":connected.name?connected.name:@""};
146
+            NSDictionary *peripheralStored = @{connected.identifier.UUIDString:connected};
147
+            if(!self.foundDevices){
148
+                self.foundDevices = [[NSMutableDictionary alloc] init];
149
+            }
150
+            [self.foundDevices addEntriesFromDictionary:peripheralStored];
151
+            if(hasListeners){
152
+                [self sendEventWithName:EVENT_DEVICE_FOUND body:@{@"device":idAndName}];
153
+            }
154
+        }
155
+        [self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@NO}];
156
+        //Callbacks:
157
+        //centralManager:didDiscoverPeripheral:advertisementData:RSSI:
158
+        NSLog(@"Scanning started with services.");
159
+        if(timer && timer.isValid){
160
+            [timer invalidate];
161
+            timer = nil;
162
+        }
163
+        timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(callStop) userInfo:nil repeats:NO];
164
+    
165
+    }
166
+    @catch(NSException *exception){
167
+        NSLog(@"ERROR IN STARTING SCANE %@",exception);
168
+        reject([exception name],[exception name],nil);
169
+    }
170
+}
171
+
172
+//stop scan
173
+RCT_EXPORT_METHOD(stopScan:(RCTPromiseResolveBlock)resolve
174
+                  rejecter:(RCTPromiseRejectBlock)reject)
175
+{
176
+    [self callStop];
177
+    resolve(nil);
178
+}
179
+
180
+//connect(address)
181
+RCT_EXPORT_METHOD(connect:(NSString *)address
182
+                  findEventsWithResolver:(RCTPromiseResolveBlock)resolve
183
+                  rejecter:(RCTPromiseRejectBlock)reject)
184
+{
185
+    NSLog(@"Trying to connect....%@",address);
186
+    [self callStop];
187
+    if(connected){
188
+        NSString *connectedAddress =connected.identifier.UUIDString;
189
+        if([address isEqualToString:connectedAddress]){
190
+            resolve(nil);
191
+            return;
192
+        }else{
193
+            [self.centralManager cancelPeripheralConnection:connected];
194
+            //Callbacks:
195
+            //entralManager:didDisconnectPeripheral:error:
196
+        }
197
+    }
198
+    CBPeripheral *peripheral = [self.foundDevices objectForKey:address];
199
+    self.connectResolveBlock = resolve;
200
+    self.connectRejectBlock = reject;
201
+    if(peripheral){
202
+          _waitingConnect = address;
203
+          NSLog(@"Trying to connectPeripheral....%@",address);
204
+        [self.centralManager connectPeripheral:peripheral options:nil];
205
+        // Callbacks:
206
+        //    centralManager:didConnectPeripheral:
207
+        //    centralManager:didFailToConnectPeripheral:error:
208
+    }else{
209
+          //starts the scan.
210
+        _waitingConnect = address;
211
+         NSLog(@"Scan to find ....%@",address);
212
+        [self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@NO}];
213
+        //Callbacks:
214
+        //centralManager:didDiscoverPeripheral:advertisementData:RSSI:
215
+    }
216
+}
217
+//unpaire(address)
218
+
219
+
220
+-(void)callStop{
221
+    if(self.centralManager.isScanning){
222
+        [self.centralManager stopScan];
223
+        NSMutableArray *devices = [[NSMutableArray alloc] init];
224
+        for(NSString *key in self.foundDevices){
225
+            NSLog(@"insert found devies:%@ =>%@",key,[self.foundDevices objectForKey:key]);
226
+            NSString *name = [self.foundDevices objectForKey:key].name;
227
+            if(!name){
228
+                name = @"";
229
+            }
230
+            [devices addObject:@{@"address":key,@"name":name}];
231
+        }
232
+        NSError *error = nil;
233
+        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:devices options:NSJSONWritingPrettyPrinted error:&error];
234
+        NSString * jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
235
+        if(hasListeners){
236
+            [self sendEventWithName:EVENT_DEVICE_DISCOVER_DONE body:@{@"found":jsonStr,@"paired":@"[]"}];
237
+        }
238
+        if(self.scanResolveBlock){
239
+            RCTPromiseResolveBlock rsBlock = self.scanResolveBlock;
240
+            rsBlock(@{@"found":jsonStr,@"paired":@"[]"});
241
+            self.scanResolveBlock = nil;
242
+        }
243
+    }
244
+    if(timer && timer.isValid){
245
+        [timer invalidate];
246
+        timer = nil;
247
+    }
248
+    self.scanRejectBlock = nil;
249
+    self.scanResolveBlock = nil;
250
+}
251
+- (void) initSupportServices
252
+{
253
+    if(!supportServices){
254
+        CBUUID *issc = [CBUUID UUIDWithString: @"49535343-FE7D-4AE5-8FA9-9FAFD205E455"];
255
+        supportServices = [NSArray arrayWithObject:issc];/*ISSC*/
256
+        writeableCharactiscs = @{issc:@"49535343-8841-43F4-A8D4-ECBE34729BB3"};
257
+    }
258
+}
259
+
260
+- (CBCentralManager *) centralManager
261
+{
262
+    @synchronized(_centralManager)
263
+    {
264
+        if (!_centralManager)
265
+        {
266
+            if (![CBCentralManager instancesRespondToSelector:@selector(initWithDelegate:queue:options:)])
267
+            {
268
+                //for ios version lowser than 7.0
269
+                self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
270
+            }else
271
+            {
272
+                self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options: nil];
273
+            }
274
+        }
275
+        if(!instance){
276
+            instance = self;
277
+        }
278
+    }
279
+    [self initSupportServices];
280
+    return _centralManager;
281
+}
282
+
283
+/**
284
+ * CBCentralManagerDelegate
285
+ **/
286
+- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
287
+    NSLog(@"%ld",(long)central.state);
288
+}
289
+
290
+- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI{
291
+    NSLog(@"did discover peripheral: %@",peripheral);
292
+    NSDictionary *idAndName =@{@"address":peripheral.identifier.UUIDString,@"name":peripheral.name?peripheral.name:@""};
293
+    NSDictionary *peripheralStored = @{peripheral.identifier.UUIDString:peripheral};
294
+    if(!self.foundDevices){
295
+        self.foundDevices = [[NSMutableDictionary alloc] init];
296
+    }
297
+    [self.foundDevices addEntriesFromDictionary:peripheralStored];
298
+    if(hasListeners){
299
+        [self sendEventWithName:EVENT_DEVICE_FOUND body:@{@"device":idAndName}];
300
+    }
301
+    if(_waitingConnect && [_waitingConnect isEqualToString: peripheral.identifier.UUIDString]){
302
+        [self.centralManager connectPeripheral:peripheral options:nil];
303
+        [self callStop];
304
+    }
305
+}
306
+
307
+- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
308
+    NSLog(@"did connected: %@",peripheral);
309
+    connected = peripheral;
310
+    NSString *pId = peripheral.identifier.UUIDString;
311
+    if(_waitingConnect && [_waitingConnect isEqualToString: pId] && self.connectResolveBlock){
312
+        NSLog(@"Predefined the support services, stop to looking up services.");
313
+//        peripheral.delegate=self;
314
+//        [peripheral discoverServices:nil];
315
+        self.connectResolveBlock(nil);
316
+        _waitingConnect = nil;
317
+        self.connectRejectBlock = nil;
318
+        self.connectResolveBlock = nil;
319
+    }
320
+       NSLog(@"going to emit EVENT_CONNECTED.");
321
+    if(hasListeners){
322
+        [self sendEventWithName:EVENT_CONNECTED body:@{@"device":@{@"name":peripheral.name?peripheral.name:@"",@"address":peripheral.identifier.UUIDString}}];
323
+    }
324
+}
325
+
326
+- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
327
+    if(!connected && _waitingConnect && [_waitingConnect isEqualToString:peripheral.identifier.UUIDString]){
328
+        if(self.connectRejectBlock){
329
+            RCTPromiseRejectBlock rjBlock = self.connectRejectBlock;
330
+            rjBlock(@"",@"",error);
331
+            self.connectRejectBlock = nil;
332
+            self.connectResolveBlock = nil;
333
+            _waitingConnect=nil;
334
+        }
335
+        connected = nil;
336
+        if(hasListeners){
337
+            [self sendEventWithName:EVENT_UNABLE_CONNECT body:@{@"name":peripheral.name?peripheral.name:@"",@"address":peripheral.identifier.UUIDString}];
338
+        }
339
+    }else{
340
+        connected = nil;
341
+        if(hasListeners){
342
+            [self sendEventWithName:EVENT_CONNECTION_LOST body:nil];
343
+        }
344
+    }
345
+}
346
+
347
+- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error{
348
+    if(self.connectRejectBlock){
349
+        RCTPromiseRejectBlock rjBlock = self.connectRejectBlock;
350
+        rjBlock(@"",@"",error);
351
+        self.connectRejectBlock = nil;
352
+        self.connectResolveBlock = nil;
353
+        _waitingConnect = nil;
354
+    }
355
+    connected = nil;
356
+    if(hasListeners){
357
+        [self sendEventWithName:EVENT_UNABLE_CONNECT body:@{@"name":peripheral.name?peripheral.name:@"",@"address":peripheral.identifier.UUIDString}];
358
+    }
359
+    }
360
+
361
+/**
362
+ * END OF CBCentralManagerDelegate
363
+ **/
364
+
365
+/*!
366
+ *  @method peripheral:didDiscoverServices:
367
+ *
368
+ *  @param peripheral    The peripheral providing this information.
369
+ *    @param error        If an error occurred, the cause of the failure.
370
+ *
371
+ *  @discussion            This method returns the result of a @link discoverServices: @/link call. If the service(s) were read successfully, they can be retrieved via
372
+ *                        <i>peripheral</i>'s @link services @/link property.
373
+ *
374
+ */
375
+- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error{
376
+    if (error){
377
+        NSLog(@"扫描外设服务出错:%@-> %@", peripheral.name, [error localizedDescription]);
378
+        return;
379
+    }
380
+    NSLog(@"扫描到外设服务:%@ -> %@",peripheral.name,peripheral.services);
381
+    for (CBService *service in peripheral.services) {
382
+        [peripheral discoverCharacteristics:nil forService:service];
383
+         NSLog(@"服务id:%@",service.UUID.UUIDString);
384
+    }
385
+    NSLog(@"开始扫描外设服务的特征 %@...",peripheral.name);
386
+    
387
+    if(error && self.connectRejectBlock){
388
+        RCTPromiseRejectBlock rjBlock = self.connectRejectBlock;
389
+         rjBlock(@"",@"",error);
390
+        self.connectRejectBlock = nil;
391
+        self.connectResolveBlock = nil;
392
+        connected = nil;
393
+    }else
394
+    if(_waitingConnect && _waitingConnect == peripheral.identifier.UUIDString){
395
+        RCTPromiseResolveBlock rsBlock = self.connectResolveBlock;
396
+        rsBlock(peripheral.identifier.UUIDString);
397
+        self.connectRejectBlock = nil;
398
+        self.connectResolveBlock = nil;
399
+        connected = peripheral;
400
+    }
401
+}
402
+
403
+/*!
404
+ *  @method peripheral:didDiscoverCharacteristicsForService:error:
405
+ *
406
+ *  @param peripheral    The peripheral providing this information.
407
+ *  @param service        The <code>CBService</code> object containing the characteristic(s).
408
+ *    @param error        If an error occurred, the cause of the failure.
409
+ *
410
+ *  @discussion            This method returns the result of a @link discoverCharacteristics:forService: @/link call. If the characteristic(s) were read successfully,
411
+ *                        they can be retrieved via <i>service</i>'s <code>characteristics</code> property.
412
+ */
413
+- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{
414
+    if(toWrite && connected
415
+       && [connected.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]
416
+       && [service.UUID.UUIDString isEqualToString:supportServices[0].UUIDString]){
417
+        if(error){
418
+            NSLog(@"Discrover charactoreristics error:%@",error);
419
+           if(writeDataDelegate)
420
+           {
421
+               [writeDataDelegate didWriteDataToBle:false];
422
+               return;
423
+           }
424
+        }
425
+        for(CBCharacteristic *cc in service.characteristics){
426
+            NSLog(@"Characterstic found: %@ in service: %@" ,cc,service.UUID.UUIDString);
427
+            if([cc.UUID.UUIDString isEqualToString:[writeableCharactiscs objectForKey: supportServices[0]]]){
428
+                @try{
429
+                    [connected writeValue:toWrite forCharacteristic:cc type:CBCharacteristicWriteWithoutResponse];
430
+                   if(writeDataDelegate) [writeDataDelegate didWriteDataToBle:true];
431
+                    if(toWrite){
432
+                        NSLog(@"Value wrote: %lu",[toWrite length]);
433
+                    }
434
+                }
435
+                @catch(NSException *e){
436
+                    NSLog(@"ERRO IN WRITE VALUE: %@",e);
437
+                      [writeDataDelegate didWriteDataToBle:false];
438
+                }
439
+            }
440
+        }
441
+        
442
+        
443
+    }
444
+    
445
+    if(error){
446
+        NSLog(@"Discrover charactoreristics error:%@",error);
447
+        return;
448
+    }
449
+    
450
+//    ServiceUUID:49535343-fe7d-4ae5-8fa9-9fafd205e455;
451
+//    写的是
452
+//characteristicUUID:49535343-8841-43f4-a8d4-ecbe34729bb3;
453
+//    读的是
454
+//characteristicUUID:49535343-1e4d-4bd9-ba61-23c647249616;
455
+//
456
+//    如果要写,翻译成base64位;
457
+//
458
+//    调用监听改变,需要去使能设备的Notify,var param={
459
+//    serviceUUID: '000018f0-0000-1000-8000-00805f9b34fb',//service的UUID  这个值需要获取查看设备,我暂认为他是通用的
460
+//    characteristicUUID:'00002af0-0000-1000-8000-00805f9b34fb',//characteristic的UUID  这个值也需要获取查看,我认为他是通用的
461
+//    enable:true //true 或false,开启或关闭监听
462
+//    };
463
+//    param = JSON.stringify(param);
464
+//    uexBluetoothLE.setCharacteristicNotification(param);
465
+    
466
+    
467
+    /** TESTING NSLOG OUTPUT:: ***/
468
+//    2018-10-01 21:29:24.136033+0800 bluetoothEscposPrinterExamples[8239:4598148] Trying to connect....D7D39238-EF56-71A7-7DCC-D464EFD3BFF1
469
+//    2018-10-01 21:29:24.302880+0800 bluetoothEscposPrinterExamples[8239:4598148] did connected: <CBPeripheral: 0x1c4302d90, identifier = D7D39238-EF56-71A7-7DCC-D464EFD3BFF1, name = BlueTooth Printer, state = connected>
470
+//    2018-10-01 21:29:24.302982+0800 bluetoothEscposPrinterExamples[8239:4598148] going to discover services.
471
+//    2018-10-01 21:29:24.303375+0800 bluetoothEscposPrinterExamples[8239:4598148] going to emit EVEnT_CONNECTED.
472
+//    2018-10-01 21:29:24.431164+0800 bluetoothEscposPrinterExamples[8239:4598148] 扫描到外设服务:BlueTooth Printer -> (
473
+//                                                                                                               "<CBService: 0x1c246b200, isPrimary = YES, UUID = 49535343-FE7D-4AE5-8FA9-9FAFD205E455>",
474
+//                                                                                                               "<CBService: 0x1c246b280, isPrimary = YES, UUID = 18F0>",
475
+//                                                                                                               "<CBService: 0x1c246a740, isPrimary = YES, UUID = E7810A71-73AE-499D-8C15-FAA9AEF0C3F2>"
476
+//                                                                                                               )
477
+//    2018-10-01 21:29:24.431354+0800 bluetoothEscposPrinterExamples[8239:4598148] 服务id:49535343-FE7D-4AE5-8FA9-9FAFD205E455
478
+//    2018-10-01 21:29:24.431448+0800 bluetoothEscposPrinterExamples[8239:4598148] 服务id:18F0
479
+//    2018-10-01 21:29:24.431535+0800 bluetoothEscposPrinterExamples[8239:4598148] 服务id:E7810A71-73AE-499D-8C15-FAA9AEF0C3F2
480
+//    2018-10-01 21:29:24.431552+0800 bluetoothEscposPrinterExamples[8239:4598148] 开始扫描外设服务的特征 BlueTooth Printer...
481
+//    2018-10-01 21:29:24.432374+0800 bluetoothEscposPrinterExamples[8239:4598148] Characterstic found: <CBCharacteristic: 0x1c04afa20, UUID = 49535343-1E4D-4BD9-BA61-23C647249616, properties = 0x10, value = <5f47505f 4c383031 3630>, notifying = NO> in service: 49535343-FE7D-4AE5-8FA9-9FAFD205E455
482
+//    2018-10-01 21:29:24.432406+0800 bluetoothEscposPrinterExamples[8239:4598148] Notify
483
+//    2018-10-01 21:29:24.432417+0800 bluetoothEscposPrinterExamples[8239:4598148] known properties: 16
484
+//    2018-10-01 21:29:24.432455+0800 bluetoothEscposPrinterExamples[8239:4598148] Characterstic found: <CBCharacteristic: 0x1c04af480, UUID = 49535343-8841-43F4-A8D4-ECBE34729BB3, properties = 0xC, value = (null), notifying = NO> in service: 49535343-FE7D-4AE5-8FA9-9FAFD205E455
485
+//    2018-10-01 21:29:24.432753+0800 bluetoothEscposPrinterExamples[8239:4598148] WriteWithoutResponse
486
+//    2018-10-01 21:29:24.432772+0800 bluetoothEscposPrinterExamples[8239:4598148] Write
487
+//    2018-10-01 21:29:24.432785+0800 bluetoothEscposPrinterExamples[8239:4598148] known properties: 12
488
+//    2018-10-01 21:29:24.432988+0800 bluetoothEscposPrinterExamples[8239:4598148] Characterstic found: <CBCharacteristic: 0x1c44ac9c0, UUID = 2AF0, properties = 0x30, value = (null), notifying = NO> in service: 18F0
489
+//    2018-10-01 21:29:24.433005+0800 bluetoothEscposPrinterExamples[8239:4598148] Notify
490
+//    2018-10-01 21:29:24.433015+0800 bluetoothEscposPrinterExamples[8239:4598148] Indicate
491
+//    2018-10-01 21:29:24.433024+0800 bluetoothEscposPrinterExamples[8239:4598148] known properties: 48
492
+//    2018-10-01 21:29:24.433079+0800 bluetoothEscposPrinterExamples[8239:4598148] Characterstic found: <CBCharacteristic: 0x1c44aca80, UUID = 2AF1, properties = 0xC, value = (null), notifying = NO> in service: 18F0
493
+//    2018-10-01 21:29:24.433647+0800 bluetoothEscposPrinterExamples[8239:4598148] WriteWithoutResponse
494
+//    2018-10-01 21:29:24.433662+0800 bluetoothEscposPrinterExamples[8239:4598148] Write
495
+//    2018-10-01 21:29:24.433672+0800 bluetoothEscposPrinterExamples[8239:4598148] known properties: 12
496
+//    2018-10-01 21:29:24.433900+0800 bluetoothEscposPrinterExamples[8239:4598148] Characterstic found: <CBCharacteristic: 0x1c44ac780, UUID = BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F, properties = 0x3E, value = (null), notifying = NO> in service: E7810A71-73AE-499D-8C15-FAA9AEF0C3F2
497
+//    2018-10-01 21:29:24.433928+0800 bluetoothEscposPrinterExamples[8239:4598148] Read
498
+//    2018-10-01 21:29:24.433953+0800 bluetoothEscposPrinterExamples[8239:4598148] WriteWithoutResponse
499
+//    2018-10-01 21:29:24.433964+0800 bluetoothEscposPrinterExamples[8239:4598148] Write
500
+//    2018-10-01 21:29:24.433973+0800 bluetoothEscposPrinterExamples[8239:4598148] Notify
501
+//    2018-10-01 21:29:24.434378+0800 bluetoothEscposPrinterExamples[8239:4598148] Indicate
502
+//    2018-10-01 21:29:24.434389+0800 bluetoothEscposPrinterExamples[8239:4598148] known properties: 62
503
+    
504
+//    for(CBCharacteristic *cc in service.characteristics){
505
+//       // NSLog(@"Characterstic found: %@ in service: %@" ,cc,service.UUID.UUIDString);
506
+//        CBCharacteristicProperties pro = cc.properties;
507
+//        Byte p = (Byte)pro;
508
+////        CBCharacteristicPropertyBroadcast                                                = 0x01,
509
+////        CBCharacteristicPropertyRead                                                    = 0x02,
510
+////        CBCharacteristicPropertyWriteWithoutResponse                                    = 0x04,
511
+////        CBCharacteristicPropertyWrite                                                    = 0x08,
512
+////        CBCharacteristicPropertyNotify                                                    = 0x10,
513
+////        CBCharacteristicPropertyIndicate                                                = 0x20,
514
+////        CBCharacteristicPropertyAuthenticatedSignedWrites                                = 0x40,
515
+////        CBCharacteristicPropertyExtendedProperties                                        = 0x80,
516
+////        CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(10_9, 6_0)    = 0x100,
517
+////        CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(10_9, 6_0)    = 0x200
518
+//        if((p) & 0x01){
519
+//            NSLog(@"Broadcast");
520
+//        }
521
+//        if((p>>1) & 0x01){
522
+//            NSLog(@"Read");
523
+//        }
524
+//        if((p>>2) & 0x01){
525
+//            NSLog(@"WriteWithoutResponse");
526
+//        }
527
+//        if((p>>3) & 0x01){
528
+//            NSLog(@"Write");
529
+//        }
530
+//        if((p>>4) & 0x01){
531
+//              NSLog(@"Notify");
532
+//        }
533
+//        if((p>>5) & 0x01){
534
+//               NSLog(@"Indicate");
535
+//        }
536
+//        if((p>>6) & 0x01){
537
+//            NSLog(@"AuthenticatedSignedWrites");
538
+//        }
539
+//        if((p>>7) & 0x01){
540
+//            NSLog(@"ExtendedProperties");
541
+//        }
542
+//        {
543
+//            NSLog(@"known properties: %lu", pro);
544
+//        }
545
+//    }
546
+}
547
+
548
+/*!
549
+ *  @method peripheral:didWriteValueForCharacteristic:error:
550
+ *
551
+ *  @param peripheral        The peripheral providing this information.
552
+ *  @param characteristic    A <code>CBCharacteristic</code> object.
553
+ *    @param error            If an error occurred, the cause of the failure.
554
+ *
555
+ *  @discussion                This method returns the result of a {@link writeValue:forCharacteristic:type:} call, when the <code>CBCharacteristicWriteWithResponse</code> type is used.
556
+ */
557
+- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
558
+    if(error){
559
+        NSLog(@"Error in writing bluetooth: %@",error);
560
+        if(writeDataDelegate){
561
+            [writeDataDelegate didWriteDataToBle:false];
562
+        }
563
+    }
564
+    
565
+    NSLog(@"Write bluetooth success.");
566
+    if(writeDataDelegate){
567
+        [writeDataDelegate didWriteDataToBle:true];
568
+    }
569
+}
570
+ 
571
+@end

+ 13
- 0
ios/RNBluetoothTscPrinter.h View File

@@ -0,0 +1,13 @@
1
+//
2
+//  RNBluetoothTscPrinter.h
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/1.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+#import <React/RCTBridgeModule.h>
9
+#import "RNBluetoothManager.h"
10
+@interface RNBluetoothTscPrinter : NSObject <RCTBridgeModule,WriteDataToBleDelegate>
11
+
12
+@end
13
+

+ 168
- 0
ios/RNBluetoothTscPrinter.m View File

@@ -0,0 +1,168 @@
1
+//
2
+//  RNBluetoothTscPrinter.m
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/1.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import "RNBluetoothTscPrinter.h"
11
+#import "RNTscCommand.h"
12
+#import "RNBluetoothManager.h"
13
+
14
+@implementation RNBluetoothTscPrinter
15
+
16
+NSData *toPrint;
17
+RCTPromiseRejectBlock _pendingReject;
18
+RCTPromiseResolveBlock _pendingResolve;
19
+NSInteger now;
20
+
21
+- (dispatch_queue_t)methodQueue
22
+{
23
+    return dispatch_get_main_queue();
24
+}
25
++ (BOOL)requiresMainQueueSetup
26
+{
27
+    return YES;
28
+}
29
+
30
+RCT_EXPORT_MODULE(BluetoothTscPrinter);
31
+//printLabel(final ReadableMap options, final Promise promise)
32
+RCT_EXPORT_METHOD(printLabel:(NSDictionary *) options withResolve:(RCTPromiseResolveBlock)resolve
33
+                  rejecter:(RCTPromiseRejectBlock)reject)
34
+{
35
+    NSInteger width = [[options valueForKey:@"width"] integerValue];
36
+    NSInteger height = [[options valueForKey:@"height"] integerValue];
37
+    NSInteger gap = [[options valueForKey:@"gap"] integerValue];
38
+    NSInteger home = [[options valueForKey:@"home"] integerValue];
39
+    NSString *tear = [options valueForKey:@"tear"];
40
+    if(!tear || ![@"ON" isEqualToString:tear]) tear = @"OFF";
41
+    NSArray *texts = [options objectForKey:@"text"];
42
+    NSArray *qrCodes = [options objectForKey:@"qrcode"];
43
+    NSArray *barCodes = [options objectForKey:@"barcode"];
44
+    NSArray *images = [options objectForKey:@"image"];
45
+    NSArray *reverses = [options objectForKey:@"revers"];
46
+    NSInteger direction = [[options valueForKey:@"direction"] integerValue];
47
+    NSInteger density = [[options valueForKey:@"density"] integerValue];
48
+    NSArray* reference = [options objectForKey:@"reference"];
49
+    NSInteger sound = [[options valueForKey:@"sound"] integerValue];
50
+    NSInteger speed = [[options valueForKey:@"speed"] integerValue];
51
+    RNTscCommand *tsc = [[RNTscCommand alloc] init];
52
+    if(speed){
53
+        [tsc addSpeed:[tsc findSpeedValue:speed]];
54
+    }
55
+    if(density){
56
+        [tsc addDensity:density];
57
+    }
58
+    [tsc addSize:width height:height];
59
+    [tsc addGap:gap];
60
+    [tsc addDirection:direction];
61
+    if(reference && [reference count] ==2){
62
+        NSInteger x = [[reference objectAtIndex:0] integerValue];
63
+        NSInteger y = [[reference objectAtIndex:1] integerValue];
64
+        NSLog(@"refernce  %ld y:%ld ",x,y);
65
+        [tsc addReference:x y:y];
66
+    }else{
67
+        [tsc addReference:0 y:0];
68
+    }
69
+    [tsc addTear:tear];
70
+    if(home && home == 1){
71
+      [tsc addBackFeed:16];
72
+      [tsc addHome];
73
+    }
74
+    [tsc addCls];
75
+
76
+    //Add Texts
77
+    for(int i=0; texts && i<[texts count];i++){
78
+        NSDictionary * text = [texts objectAtIndex:i];
79
+        NSString *t = [text valueForKey:@"text"];
80
+        NSInteger x = [[text valueForKey:@"x"] integerValue];
81
+        NSInteger y = [[text valueForKey:@"y"] integerValue];
82
+        NSString *fontType = [text valueForKey:@"fonttype"];
83
+        NSInteger rotation = [[text valueForKey:@"rotation"] integerValue];
84
+        NSInteger xscal = [[text valueForKey:@"xscal"] integerValue];
85
+        NSInteger yscal = [[text valueForKey:@"yscal"] integerValue];
86
+        Boolean bold = [[text valueForKey:@"bold"] boolValue];
87
+
88
+        [tsc addText:x y:y fontType:fontType rotation:rotation xscal:xscal yscal:yscal text:t];
89
+        if(bold){
90
+            [tsc addText:x+1 y:y fontType:fontType
91
+                rotation:rotation xscal:xscal yscal:yscal  text:t];
92
+            [tsc addText:x y:y+1 fontType:fontType
93
+                rotation:rotation xscal:xscal yscal:yscal  text:t];
94
+        }
95
+    }
96
+
97
+  //images
98
+        for (int i = 0; images && i < [images count]; i++) {
99
+            NSDictionary *img = [images objectAtIndex:i];
100
+            NSInteger x = [[img valueForKey:@"x"] integerValue];
101
+            NSInteger y = [[img valueForKey:@"y"] integerValue];
102
+            NSInteger imgWidth = [[img valueForKey:@"width"] integerValue];
103
+            NSInteger mode = [[img valueForKey:@"mode"] integerValue];
104
+            NSString *image  = [img valueForKey:@"image"];
105
+            NSData *imageData = [[NSData alloc] initWithBase64EncodedString:image options:0];
106
+            UIImage *uiImage = [[UIImage alloc] initWithData:imageData];
107
+            [tsc addBitmap:x y:y bitmapMode:mode width:imgWidth bitmap:uiImage];
108
+        }
109
+
110
+    //QRCode
111
+    for (int i = 0; qrCodes && i < [qrCodes count]; i++) {
112
+        NSDictionary *qr = [qrCodes objectAtIndex:i];
113
+        NSInteger x = [[qr valueForKey:@"x"] integerValue];
114
+        NSInteger y = [[qr valueForKey:@"y"] integerValue];
115
+        NSInteger qrWidth = [[qr valueForKey:@"width"] integerValue];
116
+        NSString *level = [qr valueForKey:@"level"];
117
+        if(!level)level = @"M";
118
+        NSInteger rotation = [[qr valueForKey:@"rotation"] integerValue];
119
+        NSString *code = [qr valueForKey:@"code"];
120
+        [tsc addQRCode:x y:y errorCorrectionLevel:level width:qrWidth rotation:rotation code:code];
121
+    }
122
+
123
+    //BarCode
124
+   for (int i = 0; barCodes && i < [barCodes count]; i++) {
125
+       NSDictionary *bar = [barCodes objectAtIndex:i];
126
+       NSInteger x = [[bar valueForKey:@"x"] integerValue];
127
+       NSInteger y = [[bar valueForKey:@"y"] integerValue];
128
+       NSInteger barWide =[[bar valueForKey:@"wide"] integerValue];
129
+       if(!barWide) barWide = 2;
130
+       NSInteger barHeight = [[bar valueForKey:@"height"] integerValue];
131
+       NSInteger narrow = [[bar valueForKey:@"narrow"] integerValue];
132
+       if(!narrow) narrow = 2;
133
+       NSInteger rotation = [[bar valueForKey:@"rotation"] integerValue];
134
+       NSString *code = [bar valueForKey:@"code"];
135
+       NSString *type = [bar valueForKey:@"type"];
136
+       NSInteger readable = [[bar valueForKey:@"readable"] integerValue];
137
+       [tsc add1DBarcode:x y:y barcodeType:type height:barHeight wide:barWide narrow:narrow readable:readable rotation:rotation content:code];
138
+    }
139
+    for(int i=0; reverses&& i < [reverses count]; i++){
140
+        NSDictionary *area = [reverses objectAtIndex:i];
141
+        NSInteger ax = [[area valueForKey:@"x"] integerValue];
142
+        NSInteger ay = [[area valueForKey:@"y"] integerValue];
143
+        NSInteger aWidth = [[area valueForKey:@"width"] integerValue];
144
+        NSInteger aHeight = [[area valueForKey:@"height"] integerValue];
145
+        [tsc addReverse:ax y:ay xwidth:aWidth yheigth:aHeight];
146
+    }
147
+    [tsc addPrint:1 n:1];
148
+    if (sound) {
149
+        [tsc addSound:2 interval:100];
150
+    }
151
+    _pendingReject = reject;
152
+    _pendingResolve = resolve;
153
+    toPrint = tsc.command;
154
+    now = 0;
155
+    [RNBluetoothManager writeValue:toPrint withDelegate:self];
156
+}
157
+
158
+- (void) didWriteDataToBle: (BOOL)success{
159
+    if(success){
160
+        if(_pendingResolve){
161
+            _pendingResolve(nil);
162
+        }
163
+    }else if(_pendingReject){
164
+        _pendingReject(@"PRINT_ERROR",@"PRINT_ERROR",nil);
165
+    }
166
+}
167
+
168
+@end

+ 72
- 0
ios/RNTscCommand.h View File

@@ -0,0 +1,72 @@
1
+//
2
+//  RNTscCommand.h
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/9.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+#import <Foundation/Foundation.h>
9
+#import <React/RCTBridgeModule.h>
10
+@interface RNTscCommand : NSObject
11
+@property NSMutableData *command;
12
+-(id)init;
13
+-(id)initWithSize:(NSInteger)width height:(NSInteger) height andGap:(NSInteger)gap;
14
+-(void)addStrToCommand:(NSString *)str;
15
+-(void)addGap:(NSInteger)gap;
16
+-(void)addSize:(NSInteger)width height:(NSInteger) height;
17
+-(void)addCashdrwer:(NSInteger) m/*0,1*/ t1:(NSInteger) t1 t2:(NSInteger) t2;
18
+-(void)addOffset:(NSInteger) offset;
19
+-(void)addSpeed:(float) speed;/*   SPEED1DIV5(1.5F), SPEED2(2.0F), SPEED3(3.0F), SPEED4(4.0F); */
20
+
21
+/*   DNESITY0(0), DNESITY1(1), DNESITY2(2), DNESITY3(3), DNESITY4(4), DNESITY5(5), DNESITY6(6), DNESITY7(
22
+ 7), DNESITY8(8), DNESITY9(9), DNESITY10(10), DNESITY11(11), DNESITY12(12), DNESITY13(13), DNESITY14(
23
+ 14), DNESITY15(15) */
24
+-(void)addDensity:(NSInteger)density;
25
+-(void)addDirection:(NSInteger) direction;/*  FORWARD(0), BACKWARD(1);*/
26
+-(void)addReference:(NSInteger) x y:(NSInteger) y;
27
+-(void)addShif:(NSInteger) shif;
28
+-(void)addCls;
29
+-(void)addFeed:(NSInteger) dot;
30
+-(void)addBackFeed:(NSInteger) backDot;
31
+-(void)addFormFeed;
32
+-(void)addHome;
33
+-(void)addPrint:(NSInteger) m n:(NSInteger) n;
34
+
35
+/*       PC437(437), PC850(850), PC852(852), PC860(860), PC863(863), PC865(865), WPC1250(1250), WPC1252(1252), WPC1253(
36
+ 1253), WPC1254(1254);  */
37
+-(void)addCodePage:(NSInteger) page;
38
+-(void)addSound:(NSInteger) level  interval:(NSInteger) interval;
39
+-(void)addLimitFeed:(NSInteger) n;
40
+-(void)addSelfTest;
41
+
42
+-(void)addBar:(NSInteger) x y:(NSInteger) y
43
+        width:(NSInteger) width heigth:(NSInteger) height;
44
+
45
+-(void)addText:(NSInteger) x y:(NSInteger) y
46
+      fontType:(NSString *) font rotation:(NSInteger) rotation
47
+         xscal:(NSInteger) Xscal yscal:(NSInteger) Yscal
48
+          text:(NSString *) text;
49
+
50
+-(void)add1DBarcode:(NSInteger) x y:(NSInteger) y
51
+        barcodeType:(NSString *) type height:(NSInteger) height
52
+        wide:(NSInteger) wide narrow:(NSInteger) narrow
53
+           readable:(NSInteger) readable rotation:(NSInteger) rotation
54
+            content:(NSString *) content;
55
+-(void)addQRCode:(NSInteger) x y:(NSInteger) y errorCorrectionLevel:(NSString *) level
56
+           width:(NSInteger) qrWidth rotation:(NSInteger) rotation
57
+            code:(NSString *) code;
58
+
59
+-(void)addBitmap:(NSInteger) x y:(NSInteger) y
60
+      bitmapMode:(NSInteger) mode width:(NSInteger) nWidth
61
+          bitmap:(UIImage *) b;
62
+-(void)addBox:(NSInteger) x y:(NSInteger) y xend:(NSInteger) xend yend:(NSInteger) yend;
63
+-(void)addErase:(NSInteger) x y:(NSInteger) y xwidth:(NSInteger) xwidth yheigth:(NSInteger) yheight;
64
+-(void)addReverse:(NSInteger) x y:(NSInteger) y xwidth:(NSInteger) xwidth yheigth:(NSInteger) yheight;
65
+-(void)addPeel:(NSString *) enable;
66
+-(void)addTear:(NSString *) enable;
67
+-(void)addCutter:(NSString *) enable;
68
+-(void)addPartialCutter :(NSString *) enable;
69
+
70
+-(float)findSpeedValue:(NSInteger) sp;
71
+
72
+@end

+ 233
- 0
ios/RNTscCommand.m View File

@@ -0,0 +1,233 @@
1
+//
2
+//  RNTscCommand.m
3
+//  RNBluetoothEscposPrinter
4
+//
5
+//  Created by januslo on 2018/10/9.
6
+//  Copyright © 2018年 Facebook. All rights reserved.
7
+//
8
+
9
+#import <Foundation/Foundation.h>
10
+#import <UIKit/UIKit.h>
11
+#import "RNTscCommand.h"
12
+#import "ImageUtils.h"
13
+@implementation RNTscCommand
14
+-(id)init
15
+{
16
+    _command = [[NSMutableData alloc] init];
17
+    return self;
18
+}
19
+-(id)initWithSize:(NSInteger)width height:(NSInteger) height andGap:(NSInteger)gap
20
+{
21
+    _command = [[NSMutableData alloc] init];
22
+    [self addSize:width height:height];
23
+    [self addGap:gap];
24
+    return self;
25
+}
26
+-(void)addStrToCommand:(NSString *)str
27
+{
28
+    if(str){
29
+    //encoding GBK? UTF-8? GB2312?
30
+        [_command appendData:[str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)]];
31
+    }
32
+}
33
+-(void)addGap:(NSInteger)gap
34
+{
35
+    [self addStrToCommand:[NSString stringWithFormat:@"GAP %lu mm,%d mm\r\n",(int)gap,0]];
36
+}
37
+-(void)addSize:(NSInteger)width height:(NSInteger) height
38
+{
39
+     [self addStrToCommand:[NSString stringWithFormat:@"SIZE %ld mm,%ld mm\r\n",width,height]];
40
+}
41
+-(void)addCashdrwer:(NSInteger) m/*0,1*/ t1:(NSInteger) t1 t2:(NSInteger) t2
42
+{
43
+      [self addStrToCommand:[NSString stringWithFormat:@"CASHDRAWER %ld,%ld,%ld\r\n",m,t1,t2]];
44
+}
45
+-(void)addOffset:(NSInteger) offset
46
+{
47
+      [self addStrToCommand:[NSString stringWithFormat:@"OFFSET %ld mm\r\n",offset]];
48
+}
49
+
50
+/*   SPEED1DIV5(1.5F), SPEED2(2.0F), SPEED3(3.0F), SPEED4(4.0F){ } */
51
+-(void)addSpeed:(float) speed
52
+{
53
+      [self addStrToCommand:[NSString stringWithFormat:@"SPEED %f\r\n",speed]];
54
+}
55
+
56
+/*   DNESITY0(0), DNESITY1(1), DNESITY2(2), DNESITY3(3), DNESITY4(4), DNESITY5(5), DNESITY6(6), DNESITY7(
57
+ 7), DNESITY8(8), DNESITY9(9), DNESITY10(10), DNESITY11(11), DNESITY12(12), DNESITY13(13), DNESITY14(
58
+ 14), DNESITY15(15) */
59
+-(void)addDensity:(NSInteger)density
60
+{
61
+      [self addStrToCommand:[NSString stringWithFormat:@"DENSITY %ld\r\n",density]];
62
+}
63
+
64
+/*  FORWARD(0), BACKWARD(1){ }*/
65
+-(void)addDirection:(NSInteger) direction
66
+{
67
+    [self addStrToCommand:[NSString stringWithFormat:@"DIRECTION %ld\r\n",direction]];
68
+}
69
+
70
+-(void)addReference:(NSInteger) x y:(NSInteger) y
71
+{
72
+      [self addStrToCommand:[NSString stringWithFormat:@"REFERENCE %ld,%ld\r\n",x,y]];
73
+}
74
+-(void)addShif:(NSInteger) shif
75
+{
76
+      [self addStrToCommand:[NSString stringWithFormat:@"SHIFT %ld\r\n",shif]];
77
+}
78
+-(void)addCls
79
+{
80
+      [self addStrToCommand:@"CLS\r\n"];
81
+}
82
+-(void)addFeed:(NSInteger) dot
83
+{
84
+      [self addStrToCommand:[NSString stringWithFormat:@"FEED %ld\r\n",dot]];
85
+}
86
+-(void)addBackFeed:(NSInteger) backDot
87
+{
88
+      [self addStrToCommand:[NSString stringWithFormat:@"BACKFEED %ld\r\n",backDot]];
89
+}
90
+-(void)addFormFeed
91
+{
92
+    [self addStrToCommand:@"FORMFEED\r\n"];
93
+}
94
+-(void)addHome
95
+{
96
+      [self addStrToCommand:@"HOME\r\n"];
97
+}
98
+-(void)addPrint:(NSInteger) m n:(NSInteger) n
99
+{
100
+      [self addStrToCommand:[NSString stringWithFormat:@"PRINT %ld,%ld\r\n",m,n]];
101
+}
102
+
103
+/*       PC437(437), PC850(850), PC852(852), PC860(860), PC863(863), PC865(865), WPC1250(1250), WPC1252(1252), WPC1253(
104
+ 1253), WPC1254(1254){ }  */
105
+-(void)addCodePage:(NSInteger) page
106
+{
107
+      [self addStrToCommand:[NSString stringWithFormat:@"CODEPAGE %ld\r\n",page]];
108
+}
109
+-(void)addSound:(NSInteger) level  interval:(NSInteger) interval
110
+{
111
+      [self addStrToCommand:[NSString stringWithFormat:@"SOUND %ld,%ld\r\n",level,interval]];
112
+}
113
+-(void)addLimitFeed:(NSInteger) n
114
+{
115
+      [self addStrToCommand:[NSString stringWithFormat:@"LIMITFEED %ld\r\n",n]];
116
+}
117
+-(void)addSelfTest
118
+{
119
+      [self addStrToCommand:@"SELFTEST\r\n"];
120
+}
121
+
122
+-(void)addBar:(NSInteger) x y:(NSInteger) y
123
+width:(NSInteger) width heigth:(NSInteger) height
124
+{
125
+      [self addStrToCommand:[NSString stringWithFormat:@"BAR %ld,%ld,%ld,%ld\r\n",
126
+                             x,y,width,height]];
127
+}
128
+
129
+-(void)addText:(NSInteger) x y:(NSInteger) y
130
+fontType:(NSString *) font rotation:(NSInteger) rotation
131
+xscal:(NSInteger) Xscal yscal:(NSInteger) Yscal
132
+text:(NSString *) text
133
+{
134
+    [self addStrToCommand:[NSString stringWithFormat:@"TEXT %ld,%ld,\"%@\",%ld,%ld,%ld,\"%@\"\r\n",
135
+                           x,y,font,rotation,Xscal,Yscal,text]];
136
+}
137
+
138
+-(void)add1DBarcode:(NSInteger) x y:(NSInteger) y
139
+barcodeType:(NSString *) type height:(NSInteger) height
140
+  wide:(NSInteger) wide narrow:(NSInteger) narrow
141
+readable:(NSInteger) readable rotation:(NSInteger) rotation
142
+content:(NSString *) content
143
+{
144
+    //str = "BARCODE " + x + "," + y + "," + "\"" + type.getValue() + "\"" + "," + height + "," + readable.getValue()
145
+   // + "," + rotation.getValue() + "," + narrow + "," + wide + "," + "\"" + content + "\"" + "\r\n";
146
+    NSString *c =[NSString stringWithFormat:@"BARCODE %ld,%ld,\"%@\",%ld,%ld,%ld,%d,%d,\"%@\"\r\n",
147
+                  x,y,type,height,readable,rotation,narrow,wide,content];
148
+    NSLog(@"BARCODE COMMAND:%@",c);
149
+    [self addStrToCommand:c];
150
+}
151
+
152
+-(void)addQRCode:(NSInteger) x y:(NSInteger) y errorCorrectionLevel:(NSString *) level
153
+width:(NSInteger) qrWidth rotation:(NSInteger) rotation
154
+code:(NSString *) code
155
+{
156
+    [self addStrToCommand:[NSString stringWithFormat:@"QRCODE %ld,%ld,%@,%ld,A,%ld,M2,S1,\"%@\"\r\n",
157
+                           x,y,level,qrWidth,rotation,code]];
158
+}
159
+
160
+-(void)addBitmap:(NSInteger) x y:(NSInteger) y
161
+bitmapMode:(NSInteger) mode width:(NSInteger) nWidth
162
+bitmap:(UIImage *) b{
163
+    //todo: NEED TO IMPLEMENT>>>>>>
164
+    if (b) {
165
+        CGFloat imgWidth = b.size.width;
166
+        CGFloat imgHeigth = b.size.height;
167
+        NSInteger width = (nWidth + 7) / 8 * 8;
168
+        NSInteger height = imgHeigth * width / imgWidth;
169
+        UIImage *resized = [ImageUtils imageWithImage:b scaledToFillSize:CGSizeMake(width, height)];
170
+        uint8_t * graybits = [ImageUtils imageToGreyImage:resized];
171
+        NSInteger srcLen = (int)resized.size.width*resized.size.height;
172
+        NSData *codecontent = [ImageUtils pixToTscCmd:graybits width:srcLen];
173
+        height = srcLen / width;
174
+        width /= 8;
175
+        NSString *str =[NSString stringWithFormat:@ "BITMAP %ld,%ld,%ld,%ld,%ld,",
176
+                        x,y,width,height,mode];
177
+        [self addStrToCommand:str];
178
+        [_command appendData:codecontent];
179
+        [self addStrToCommand:@"\r\n"];
180
+    }
181
+    
182
+}
183
+-(void)addBox:(NSInteger) x y:(NSInteger) y xend:(NSInteger) xend yend:(NSInteger) yend
184
+{
185
+    [self addStrToCommand:[NSString stringWithFormat:@"BAR %ld,%ld,%ld,%ld\r\n",
186
+                           x,y,xend,yend]];
187
+}
188
+-(void)addErase:(NSInteger) x y:(NSInteger) y xwidth:(NSInteger) xwidth yheigth:(NSInteger) yheight
189
+{
190
+    [self addStrToCommand:[NSString stringWithFormat:@"ERASE %ld,%ld,%ld,%ld\r\n",
191
+                           x,y,xwidth,yheight]];
192
+}
193
+-(void)addReverse:(NSInteger) x y:(NSInteger) y xwidth:(NSInteger) xwidth yheigth:(NSInteger) yheight
194
+{
195
+    [self addStrToCommand:[NSString stringWithFormat:@"REVERSE %ld,%ld,%ld,%ld\r\n",
196
+                           x,y,xwidth,yheight]];
197
+}
198
+-(void)addPeel:(NSString *) enable
199
+{
200
+    [self addStrToCommand:[NSString stringWithFormat:@"SET PEEL %@\r\n",enable]];
201
+}
202
+-(void)addTear:(NSString *) enable
203
+{
204
+      [self addStrToCommand:[NSString stringWithFormat:@"SET TEAR %@\r\n",enable]];
205
+}
206
+-(void)addCutter:(NSString *) enable
207
+{
208
+      [self addStrToCommand:[NSString stringWithFormat:@"SET CUTTER %@\r\n",enable]];
209
+}
210
+-(void)addPartialCutter :(NSString *) enable
211
+{
212
+     [self addStrToCommand:[NSString stringWithFormat:@"SET PARTIAL_CUTTER %@\r\n",enable]];
213
+}
214
+
215
+-(float)findSpeedValue:(NSInteger) sp{
216
+    // SPEED1DIV5(1.5F), SPEED2(2.0F), SPEED3(3.0F), SPEED4(4.0F);
217
+    switch (sp) {
218
+        case 2:
219
+            return 2.0f;
220
+            break;
221
+        case 3:
222
+            return 3.0f;
223
+            break;
224
+        case 4:
225
+            return 4.0f;
226
+            break;
227
+        case 1:
228
+        default:
229
+            return 1.5f;
230
+            break;
231
+    }
232
+}
233
+@end

+ 1
- 0
ios/ZXingObjC-3.2.2/.gitattributes View File

@@ -0,0 +1 @@
1
+*.pbxproj merge=union

+ 0
- 0
ios/ZXingObjC-3.2.2/.npmignore View File


Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save