-
Notifications
You must be signed in to change notification settings - Fork 82
/
HomeScreen.tsx
466 lines (446 loc) · 13.5 KB
/
HomeScreen.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/* eslint-disable react-native/no-inline-styles */
import {Picker} from '@react-native-picker/picker';
import * as React from 'react';
import {
StyleSheet,
View,
Text,
Platform,
Alert,
TouchableOpacity,
Dimensions,
TextInput,
} from 'react-native';
import {
BLEPrinter,
NetPrinter,
USBPrinter,
IUSBPrinter,
IBLEPrinter,
INetPrinter,
ColumnAlignment,
COMMANDS,
} from 'react-native-thermal-receipt-printer-image-qr';
import Loading from '../Loading';
import {DeviceType} from './FindPrinter';
import {navigate} from './App';
import AntIcon from 'react-native-vector-icons/AntDesign';
import QRCode from 'react-native-qrcode-svg';
import {useRef} from 'react';
import {Buffer} from 'buffer';
const printerList: Record<string, any> = {
ble: BLEPrinter,
net: NetPrinter,
usb: USBPrinter,
};
export interface SelectedPrinter
extends Partial<IUSBPrinter & IBLEPrinter & INetPrinter> {
printerType?: keyof typeof printerList;
}
export const PORT: string = '9100';
export enum DevicesEnum {
usb = 'usb',
net = 'net',
blu = 'blu',
}
const deviceWidth = Dimensions.get('window').width;
const EscPosEncoder = require('esc-pos-encoder');
export const HomeScreen = ({route}: any) => {
const [selectedValue, setSelectedValue] = React.useState<
keyof typeof printerList
>(DevicesEnum.net);
const [devices, setDevices] = React.useState([]);
// const [connected, setConnected] = React.useState(false);
const [loading, setLoading] = React.useState<boolean>(false);
const [selectedPrinter, setSelectedPrinter] = React.useState<SelectedPrinter>(
{},
);
let QrRef = useRef<any>(null);
const [selectedNetPrinter, setSelectedNetPrinter] =
React.useState<DeviceType>({
device_name: 'My Net Printer',
host: '192.168.0.101', // your host
port: PORT, // your port
printerType: DevicesEnum.net,
});
React.useEffect(() => {
if (route.params?.printer) {
setSelectedNetPrinter({
...selectedNetPrinter,
...route.params.printer,
});
}
}, [route.params?.printer]);
const getListDevices = async () => {
const Printer = printerList[selectedValue];
// get list device for net printers is support scanning in local ip but not recommended
if (selectedValue === DevicesEnum.net) {
await Printer.init();
setLoading(false);
return;
}
requestAnimationFrame(async () => {
try {
await Printer.init();
const results = await Printer.getDeviceList();
setDevices(
results?.map((item: any) => ({
...item,
printerType: selectedValue,
})),
);
} catch (err) {
console.warn(err);
} finally {
setLoading(false);
}
});
};
React.useEffect(() => {
setLoading(true);
getListDevices().then();
}, [selectedValue]);
const handleConnectSelectedPrinter = async () => {
setLoading(true);
const connect = async () => {
try {
switch (
selectedValue === DevicesEnum.net
? selectedNetPrinter.printerType
: selectedPrinter.printerType
) {
case 'ble':
if (selectedPrinter?.inner_mac_address) {
await BLEPrinter.connectPrinter(
selectedPrinter?.inner_mac_address || '',
);
}
break;
case 'net':
if (!selectedNetPrinter) {
break;
}
try {
// if (connected) {
// await NetPrinter.closeConn();
// setConnected(!connected);
// }
const status = await NetPrinter.connectPrinter(
selectedNetPrinter?.host || '',
9100,
);
setLoading(false);
console.log('connect -> status', status);
Alert.alert(
'Connect successfully!',
`Connected to ${status.host ?? 'Printers'} !`,
);
// setConnected(true);
} catch (err) {
Alert.alert('Connect failed!', `${err} !`);
}
break;
case 'usb':
if (selectedPrinter?.vendor_id) {
await USBPrinter.connectPrinter(
selectedPrinter?.vendor_id || '',
selectedPrinter?.product_id || '',
);
}
break;
default:
}
} catch (err) {
console.warn(err);
} finally {
setLoading(false);
}
};
await connect();
};
const handlePrint = async () => {
try {
const Printer = printerList[selectedValue];
Printer.printText('<C>sample text</C>', {
cut: false,
});
Printer.printImage(
'https://sportshub.cbsistatic.com/i/2021/04/09/9df74632-fde2-421e-bc6f-d4bf631bf8e5/one-piece-trafalgar-law-wano-anime-1246430.jpg',
);
Printer.printBill('<C>sample text</C>');
} catch (err) {
console.warn(err);
}
};
const handlePrintBill = async () => {
let address = '2700 S123 Grand Ave, Los Angeles, CA 90007223, USA.';
const BOLD_ON = COMMANDS.TEXT_FORMAT.TXT_BOLD_ON;
const BOLD_OFF = COMMANDS.TEXT_FORMAT.TXT_BOLD_OFF;
const CENTER = COMMANDS.TEXT_FORMAT.TXT_ALIGN_CT;
const OFF_CENTER = COMMANDS.TEXT_FORMAT.TXT_ALIGN_LT;
try {
const getDataURL = () => {
(QrRef as any).toDataURL(callback);
};
const callback = async (dataURL: string) => {
let qrProcessed = dataURL.replace(/(\r\n|\n|\r)/gm, '');
// Can print android and ios with the same type or with encoder for android
if (Platform.OS === 'android' || Platform.OS === 'ios') {
const Printer: typeof NetPrinter = printerList[selectedValue];
Printer.printImage(
`https://sportshub.cbsistatic.com/i/2021/04/09/9df74632-fde2-421e-bc6f-d4bf631bf8e5/one-piece-trafalgar-law-wano-anime-1246430.jpg`,
{
imageWidth: 300,
imageHeight: 300,
},
);
Printer.printText(`${CENTER}${BOLD_ON} BILLING ${BOLD_OFF}\n`);
Printer.printText(`${CENTER}${address}${OFF_CENTER}`);
Printer.printText('090 3399 031 555\n');
Printer.printText(`Date : 15- 09 - 2021 /15 : 29 : 57 / Admin`);
Printer.printText(`Product : Total - 4 / No. (1,2,3,4)\n`);
Printer.printText(
`${CENTER}${COMMANDS.HORIZONTAL_LINE.HR_80MM}${CENTER}`,
);
let orderList = [
['1. Skirt Palas Labuh Muslimah Fashion', 'x2', '500$'],
['2. BLOUSE ROPOL VIRAL MUSLIMAH FASHION', 'x4222', '500$'],
[
'3. Women Crew Neck Button Down Ruffle Collar Loose Blouse',
'x1',
'30000000000000$',
],
['4. Retro Buttons Up Full Sleeve Loose', 'x10', '200$'],
['5. Retro Buttons Up', 'x10', '200$'],
];
let columnAlignment = [
ColumnAlignment.LEFT,
ColumnAlignment.CENTER,
ColumnAlignment.RIGHT,
];
let columnWidth = [46 - (7 + 12), 7, 12];
const header = ['Product list', 'Qty', 'Price'];
Printer.printColumnsText(header, columnWidth, columnAlignment, [
`${BOLD_ON}`,
'',
'',
]);
Printer.printText(
`${CENTER}${COMMANDS.HORIZONTAL_LINE.HR3_80MM}${CENTER}`,
);
for (let i in orderList) {
Printer.printColumnsText(
orderList[i],
columnWidth,
columnAlignment,
[`${BOLD_OFF}`, '', ''],
);
}
Printer.printText(`\n`);
Printer.printImageBase64(qrProcessed, {
imageWidth: 50,
imageHeight: 50,
});
Printer.printBill(`${CENTER}Thank you\n`, {beep: false});
} else {
// optional for android
// android
const Printer = printerList[selectedValue];
const encoder = new EscPosEncoder();
let _encoder = encoder
.initialize()
.align('center')
.line('BILLING')
.qrcode('https://nielsleenheer.com')
.encode();
let base64String = Buffer.from(_encoder).toString('base64');
Printer.printRaw(base64String);
}
};
getDataURL();
} catch (err) {
console.warn(err);
}
};
const handlePrintBillWithImage = async () => {
const Printer: typeof NetPrinter = printerList[selectedValue];
Printer.printImage(
'https://media-cdn.tripadvisor.com/media/photo-m/1280/1b/3a/bd/b5/the-food-bill.jpg',
{
imageWidth: 575,
// imageHeight: 1000,
// paddingX: 100
},
);
Printer.printBill('', {beep: false});
};
const handleChangePrinterType = async (type: keyof typeof printerList) => {
setSelectedValue(prev => {
printerList[prev].closeConn();
return type;
});
setSelectedPrinter({});
};
const findPrinter = () => {
navigate('Find');
};
const onChangeText = (text: string) => {
setSelectedNetPrinter({...selectedNetPrinter, host: text});
};
const _renderNet = () => (
<>
<Text style={[styles.text, {color: 'black', marginLeft: 0}]}>
Your printer ip....
</Text>
<TextInput
style={{
borderBottomWidth: 1,
height: 45,
}}
placeholder={'Your printer port...'}
value={selectedNetPrinter?.host}
onChangeText={onChangeText}
/>
<View
style={{
marginTop: 10,
}}>
<TouchableOpacity
style={[styles.button, {backgroundColor: 'grey', height: 30}]}
// disabled={!selectedPrinter?.device_name}
onPress={findPrinter}>
<AntIcon name={'search1'} color={'white'} size={18} />
<Text style={styles.text}>Find your printers</Text>
</TouchableOpacity>
</View>
</>
);
const _renderOther = () => (
<>
<Text>Select printer: </Text>
<Picker
selectedValue={selectedPrinter}
onValueChange={setSelectedPrinter}>
{devices !== undefined &&
devices?.length > 0 &&
devices?.map((item: any, index) => (
<Picker.Item
label={item.device_name}
value={item}
key={`printer-item-${index}`}
/>
))}
</Picker>
</>
);
return (
<View style={styles.container}>
{/* Printers option */}
<View style={styles.section}>
<Text style={styles.title}>Select printer type: </Text>
<Picker
selectedValue={selectedValue}
mode="dropdown"
onValueChange={handleChangePrinterType}>
{Object.keys(printerList).map((item, index) => (
<Picker.Item
label={item.toUpperCase()}
value={item}
key={`printer-type-item-${index}`}
/>
))}
</Picker>
</View>
{/* Printers List */}
<View style={styles.section}>
{selectedValue === 'net' ? _renderNet() : _renderOther()}
{/* Buttons Connect */}
<View
style={[
styles.buttonContainer,
{
marginTop: 50,
},
]}>
<TouchableOpacity
style={styles.button}
onPress={handleConnectSelectedPrinter}>
<AntIcon name={'disconnect'} color={'white'} size={18} />
<Text style={styles.text}>Connect</Text>
</TouchableOpacity>
</View>
{/* Button Print sample */}
<View style={styles.buttonContainer}>
<TouchableOpacity
style={[styles.button, {backgroundColor: 'blue'}]}
onPress={handlePrint}>
<AntIcon name={'printer'} color={'white'} size={18} />
<Text style={styles.text}>Print sample</Text>
</TouchableOpacity>
</View>
{/* Button Print bill */}
<View style={styles.buttonContainer}>
<TouchableOpacity
style={[styles.button, {backgroundColor: 'blue'}]}
onPress={handlePrintBill}>
<AntIcon name={'profile'} color={'white'} size={18} />
<Text style={styles.text}>Print bill</Text>
</TouchableOpacity>
</View>
{/* Button Print bill With Image */}
<View style={styles.buttonContainer}>
<TouchableOpacity
style={[styles.button, {backgroundColor: 'blue'}]}
onPress={handlePrintBillWithImage}>
<AntIcon name={'profile'} color={'white'} size={18} />
<Text style={styles.text}>Print bill With Image</Text>
</TouchableOpacity>
</View>
<View style={styles.qr}>
<QRCode value="hey" getRef={(el: any) => (QrRef = el)} />
</View>
</View>
<Loading loading={loading} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
section: {},
rowDirection: {
flexDirection: 'row',
},
buttonContainer: {
marginTop: 10,
},
button: {
flexDirection: 'row',
height: 40,
width: deviceWidth / 1.5,
alignSelf: 'center',
backgroundColor: 'green',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 5,
},
text: {
color: 'white',
fontSize: 17,
fontWeight: 'bold',
marginLeft: 5,
},
title: {
color: 'black',
fontSize: 15,
fontWeight: 'bold',
marginLeft: 5,
},
qr: {
alignItems: 'center',
justifyContent: 'center',
marginTop: 20,
},
});