Skip to content

Commit 210af76

Browse files
committed
fix: update readme
1 parent 1902492 commit 210af76

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+745
-137
lines changed

README.md

+144-3
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,152 @@ yarn add react-native-ble-printer
1717
## Usage
1818

1919
```js
20-
import { multiply } from 'react-native-ble-printer';
20+
import { useEffect, useState } from 'react';
21+
import {
22+
Alert,
23+
Button,
24+
ScrollView,
25+
StyleSheet,
26+
Text,
27+
View,
28+
type EmitterSubscription,
29+
} from 'react-native';
30+
import { DeviceItem } from './components/DeviceItem';
31+
import BlePrinter, { type Device } from 'react-native-ble-printer';
2132

22-
// ...
33+
export default function App() {
34+
const [connectedDevice, setConnectedDevice] = useState<Device | null>(null);
35+
const [pairedDevices, setPairedDevices] = useState<Device[]>([]);
36+
const [foundDevices, setFoundDevices] = useState<Device[]>([]);
37+
const [isScanning, setScanning] = useState<boolean>(false);
38+
39+
async function handlePrintReceipt() {
40+
try {
41+
await BlePrinter.printText('Hello world!');
42+
} catch (error) {
43+
console.log(error);
44+
}
45+
}
46+
47+
async function handleScanDevices() {
48+
const isEnabled = await BlePrinter.bluetoothIsEnabled();
49+
50+
if (!isEnabled) {
51+
Alert.alert('Oops!', 'Enable bluetooth');
52+
return;
53+
}
54+
55+
setScanning(true);
56+
57+
try {
58+
setFoundDevices([]);
59+
setPairedDevices([]);
60+
await BlePrinter.scanDevices();
61+
} catch (error) {
62+
console.log(error);
63+
}
64+
setScanning(false);
65+
}
66+
67+
const handleDeviceFounds = (device: Device) => {
68+
setFoundDevices((oldDevices) => [...oldDevices, device]);
69+
};
70+
71+
const handleDevicePaired = (device: Device) => {
72+
setPairedDevices((oldDevices) => [...oldDevices, device]);
73+
};
74+
75+
useEffect(() => {
76+
var listeners: EmitterSubscription[] = [];
77+
78+
listeners.push(BlePrinter.onDeviceFound(handleDeviceFounds));
79+
listeners.push(BlePrinter.onDevicePaired(handleDevicePaired));
80+
81+
return () => {
82+
for (var listener of listeners) {
83+
listener.remove();
84+
}
85+
};
86+
}, []);
87+
88+
return (
89+
<View style={styles.container}>
90+
<View style={styles.header}>
91+
<Text style={styles.headerTitle}>BLEPrinter</Text>
92+
<View style={styles.headerActions}>
93+
<Button
94+
title="Scan Devices"
95+
onPress={handleScanDevices}
96+
disabled={isScanning}
97+
/>
98+
</View>
99+
</View>
100+
101+
<ScrollView contentContainerStyle={styles.body}>
102+
{/* Options */}
103+
104+
{/* Paired devices */}
105+
<Text>Dispositivos pareados:</Text>
106+
{pairedDevices.map((device, i) => (
107+
<DeviceItem
108+
isConnected={device.address === connectedDevice?.address}
109+
item={device}
110+
key={i}
111+
onConnectDevice={setConnectedDevice}
112+
/>
113+
))}
114+
115+
{/* Found devices */}
116+
<Text>Dispositivos encontrados:</Text>
117+
{foundDevices.map((device, i) => (
118+
<DeviceItem
119+
item={device}
120+
isConnected={device.address === connectedDevice?.address}
121+
key={i}
122+
onConnectDevice={setConnectedDevice}
123+
/>
124+
))}
125+
</ScrollView>
126+
127+
{connectedDevice && (
128+
<Button title="Print Receipt" onPress={handlePrintReceipt} />
129+
)}
130+
</View>
131+
);
132+
}
133+
134+
const styles = StyleSheet.create({
135+
container: {
136+
flex: 1,
137+
backgroundColor: '#eee',
138+
},
139+
header: {
140+
padding: 20,
141+
flexDirection: 'row',
142+
alignItems: 'center',
143+
backgroundColor: 'white',
144+
elevation: 5,
145+
shadowColor: 'rgba(0,0,0,0.8)',
146+
},
147+
headerActions: {
148+
flexDirection: 'row',
149+
alignItems: 'center',
150+
justifyContent: 'flex-end',
151+
gap: 10,
152+
flex: 1,
153+
},
154+
headerTitle: {
155+
fontSize: 17,
156+
fontWeight: 'bold',
157+
},
158+
body: {
159+
paddingHorizontal: 10,
160+
gap: 10,
161+
paddingTop: 10,
162+
paddingBottom: 100,
163+
},
164+
});
23165

24-
const result = await multiply(3, 7);
25166
```
26167
27168
## Contributing

android/src/main/AndroidManifestNew.xml

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,7 @@
66

77
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
88
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
9-
<!-- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>-->
9+
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
10+
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
11+
<!-- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>-->
1012
</manifest>

android/src/main/java/com/bleprinter/BlePrinterModule.kt

+43-28
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,15 @@ import android.content.IntentFilter
1313
import android.content.pm.PackageManager
1414
import android.graphics.Paint
1515
import android.graphics.Typeface
16+
import android.os.Build
17+
import androidx.annotation.RequiresApi
1618
import androidx.core.app.ActivityCompat
1719
import com.facebook.react.bridge.Promise
1820
import com.facebook.react.bridge.ReactApplicationContext
1921
import com.facebook.react.bridge.ReactContext.RCTDeviceEventEmitter
2022
import com.facebook.react.bridge.ReactContextBaseJavaModule
2123
import com.facebook.react.bridge.ReactMethod
24+
import com.facebook.react.bridge.ReadableArray
2225
import org.json.JSONObject
2326
import java.io.OutputStream
2427
import java.util.Collections
@@ -35,6 +38,7 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
3538
private val EVENT_FOUND_DEVICES = "EVENT_FOUND_DEVICES"
3639
private val EVENT_PAIRED_DEVICES = "EVENT_PAIRED_DEVICES"
3740
private val EVENT_DISCOVERY_FINISHED = "EVENT_DISCOVERY_FINISHED"
41+
private var promiseScan: Promise? = null
3842

3943
private val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
4044

@@ -59,7 +63,6 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
5963
return bleAdapter
6064
}
6165

62-
6366
@ReactMethod
6467
fun bluetoothIsEnabled(promise: Promise) {
6568
val adapter = getAdapter()
@@ -114,6 +117,8 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
114117
}
115118
}
116119

120+
@SuppressLint("MissingPermission")
121+
@RequiresApi(Build.VERSION_CODES.ECLAIR)
117122
@ReactMethod
118123
fun scanDevices(promise: Promise) {
119124
val checkBluetoothScanPermission = ActivityCompat.checkSelfPermission(
@@ -135,10 +140,7 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
135140

136141
val bleAdapter = getAdapter()
137142
try {
138-
if (bleAdapter != null && bleAdapter.isDiscovering) {
139-
bleAdapter.cancelDiscovery()
140-
return
141-
}
143+
stopScan()
142144

143145

144146
val pairedDevices = bleAdapter?.bondedDevices
@@ -151,11 +153,22 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
151153

152154
devices.clear()
153155
bleAdapter?.startDiscovery()
156+
promiseScan = promise
154157
} catch (e: Exception) {
155158
promise.reject("SCAN", e.message)
156159
}
157160
}
158161

162+
@RequiresApi(Build.VERSION_CODES.ECLAIR)
163+
@SuppressLint("MissingPermission")
164+
fun stopScan() {
165+
val bleAdapter = getAdapter()
166+
if (bleAdapter != null && bleAdapter.isDiscovering) {
167+
bleAdapter.cancelDiscovery()
168+
return
169+
}
170+
}
171+
159172
@ReactMethod
160173
fun printText(
161174
text: String,
@@ -176,10 +189,11 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
176189
}
177190

178191
@ReactMethod
179-
fun printUnderline(promise: Promise) {
192+
fun printStroke(strokeHeight: Int = 20, strokeWidth: Float = 5f , strokeDash: ReadableArray? = null, promise: Promise) {
180193
val stream = getStream()
181194
try {
182-
stream?.write(Utils().line())
195+
val dash = if(strokeDash != null) FloatArray(strokeDash.size()) { strokeDash.getInt(it).toFloat() } else null
196+
stream?.write(Utils().createStyledStrokeBitmap(strokeHeight, strokeWidth, dash))
183197
promise.resolve("Print Underline")
184198
} catch (e: Exception) {
185199
promise.reject("PrintError", e.message)
@@ -198,13 +212,11 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
198212
}
199213

200214
@ReactMethod
201-
fun printLines(lines: Int, promise: Promise) {
215+
fun printSpace(lines: Int, promise: Promise) {
202216
val stream = getStream()
203217
try {
204-
var n = 1;
205-
while (n < lines) {
206-
n++
207-
stream?.write(byteArrayOf(0x0A))
218+
for (i in 0..lines) {
219+
stream?.write("\n".toByteArray())
208220
}
209221

210222
promise.resolve("PRINTED LINES")
@@ -213,32 +225,34 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
213225
}
214226
}
215227

216-
217228
@ReactMethod
218-
fun printColumns(
229+
fun printTwoColumns(
219230
leftText: String,
220231
rightText: String,
221232
bold: Boolean = false,
222233
size: Float = 24f,
223234
promise: Promise
224235
) {
225-
val paint = Paint().apply {
226-
textSize = size // Tamanho da fonte
227-
typeface = if (bold) Typeface.DEFAULT_BOLD else Typeface.DEFAULT // Fonte padrão
228-
}
229-
val leftWidth = paint.measureText(leftText)
230-
val rightWidth = paint.measureText(rightText)
231-
232-
// Calcula o espaço disponível entre os textos
233-
val totalSpace = 374 - (leftWidth + rightWidth)
234-
235-
// Adiciona espaços entre os textos
236-
val spaces = " ".repeat((totalSpace / paint.measureText(" ")).toInt())
237-
val line = "$leftText$spaces$rightText"
236+
val text = Utils().twoColumns(leftText, rightText, bold, size)
237+
printText(text, bold = bold, size = size, promise = promise)
238+
}
238239

239-
printText(line, bold = bold, size = size, promise = promise)
240+
@ReactMethod
241+
fun printColumns(texts: ReadableArray, columnWidths: ReadableArray, alignments: ReadableArray, bold: Boolean = false, textSize: Float = 24f, promise: Promise) {
242+
val textList = Array(texts.size()) { texts.getString(it) ?: "" }
243+
val columnWidthList = Array(columnWidths.size()) { columnWidths.getInt(it) }
244+
val alignmentList = Array(alignments.size()) { alignments.getString(it) ?: "LEFT" }
245+
val columnBitmap = Utils().createColumnTextBitmap(textList, columnWidthList, alignmentList, bold, textSize)
246+
val stream = getStream()
247+
try {
248+
stream?.write(columnBitmap)
249+
promise.resolve("Printed Text")
250+
} catch (e: Exception) {
251+
promise.resolve(e.message)
252+
}
240253
}
241254

255+
242256
private val receiver = object : BroadcastReceiver() {
243257

244258
@SuppressLint("MissingPermission")
@@ -264,6 +278,7 @@ class BlePrinterModule(reactContext: ReactApplicationContext) :
264278
}
265279

266280
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
281+
promiseScan?.resolve("SCAN")
267282
reactEmitEvent(EVENT_DISCOVERY_FINISHED)
268283
}
269284
}

0 commit comments

Comments
 (0)