Skip to content

Commit

Permalink
feat: add printing from data source to printing class
Browse files Browse the repository at this point in the history
  • Loading branch information
sergey committed Jul 7, 2021
1 parent 3991f2a commit 151231e
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 152 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ class PrintingCommands {
public static final int COMMAND_ADD_IMAGE_BASE_64 = 5;
public static final int COMMAND_ADD_IMAGE_ASSET = 6;
public static final int COMMAND_ADD_CUT = 7;
public static final int COMMAND_ADD_DATA = 8;
}

@ReactModule(name = EscPosPrinterModule.NAME)
Expand Down Expand Up @@ -116,6 +117,7 @@ public Map<String, Object> getConstants() {
constants.put("COMMAND_ADD_IMAGE_BASE_64", PrintingCommands.COMMAND_ADD_IMAGE_BASE_64);
constants.put("COMMAND_ADD_IMAGE_ASSET", PrintingCommands.COMMAND_ADD_IMAGE_ASSET);
constants.put("COMMAND_ADD_CUT", PrintingCommands.COMMAND_ADD_CUT);
constants.put("COMMAND_ADD_DATA", PrintingCommands.COMMAND_ADD_DATA);
constants.put("EPOS2_ALIGN_LEFT", Printer.ALIGN_LEFT);
constants.put("EPOS2_ALIGN_RIGHT", Printer.ALIGN_RIGHT);
constants.put("EPOS2_ALIGN_CENTER", Printer.ALIGN_CENTER);
Expand Down Expand Up @@ -149,27 +151,6 @@ public void onError(String result) {
this.printerAddress = target;
}

@ReactMethod
public void printBase64(String base64string, Promise promise) {

tasksQueue.submit(new Runnable() {
@Override
public void run() {
printFromBase64(base64string, new MyCallbackInterface() {
@Override
public void onSuccess(String result) {
promise.resolve(result);
}
@Override
public void onError(String result) {
promise.reject(result);
}
});
}
});

}

@ReactMethod
public void getPaperWidth(Promise promise) {

Expand Down Expand Up @@ -269,37 +250,6 @@ private void printData() throws Epos2Exception {

}

private void printFromBase64(String base64String, MyCallbackInterface callback) {
if (mPrinter == null) {
String errorString = EscPosPrinterErrorManager.getEposExceptionText(Epos2Exception.ERR_PARAM);
callback.onError(errorString);
return;
}

byte[] data = Base64.decode(base64String, Base64.DEFAULT);

try {
mPrinter.addCommand(data);
}
catch (Epos2Exception e) {
mPrinter.clearCommandBuffer();
int status = EscPosPrinterErrorManager.getErrorStatus(e);
String errorString = EscPosPrinterErrorManager.getEposExceptionText(status);
callback.onError(errorString);
return;
}

try {
this.printData();
String successString = EscPosPrinterErrorManager.getCodeText(Epos2CallbackCode.CODE_SUCCESS);
callback.onSuccess(successString);
} catch (Epos2Exception e) {
int status = EscPosPrinterErrorManager.getErrorStatus(e);
String errorString = EscPosPrinterErrorManager.getEposExceptionText(status);
callback.onError(errorString);
}
}

@Override
public void onPtrReceive(final Printer printerObj, final int code, final PrinterStatusInfo status, final String printJobId) {
UiThreadUtil.runOnUiThread(new Runnable() {
Expand Down Expand Up @@ -574,6 +524,11 @@ private void handleCommand(int command, ReadableArray params) throws Epos2Except
case PrintingCommands.COMMAND_ADD_CUT:
mPrinter.addCut(Printer.CUT_FEED);
break;
case PrintingCommands.COMMAND_ADD_DATA:
String base64String = params.getString(0);
byte[] data = Base64.decode(base64String, Base64.DEFAULT);
mPrinter.addCommand(data);
break;
default:
throw new IllegalArgumentException("Invalid Printing Command");
}
Expand Down
22 changes: 11 additions & 11 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ export default function App() {
React.useEffect(() => {
console.log(printer);
}, [printer]);

return (
<View style={styles.container}>
<Button
title="discover"
title="Discover"
onPress={() => {
console.log('discovering');
EscPosPrinter.discover({ usbSerialNumber: true })
Expand All @@ -37,7 +38,7 @@ export default function App() {
/>

<Button
title="gett lines per row"
title="Get lines per row"
disabled={!printer}
color={!printer ? 'gray' : 'blue'}
onPress={async () => {
Expand Down Expand Up @@ -102,7 +103,7 @@ export default function App() {
/>

<Button
title="testt"
title="Print from data"
disabled={!printer}
color={!printer ? 'gray' : 'blue'}
onPress={async () => {
Expand All @@ -113,8 +114,7 @@ export default function App() {
.line('The quick brown fox jumps over the lazy dog')
.newline()
.newline()
.newline()
.cut('partial');
.newline();

try {
if (printer) {
Expand All @@ -125,11 +125,11 @@ export default function App() {
});
setInit(true);
}
// const paper = await EscPosPrinter.getPaperWidth();
// console.log(paper);
const status = await EscPosPrinter.printRawData(encoder.encode());
// const pairingSatus = await EscPosPrinter.pairingBluetoothPrinter();
// console.log(pairingSatus);

const printing = new EscPosPrinter.printing();

const status = await printing.data(encoder.encode()).cut().send();

console.log('print', status);
}
} catch (error) {
Expand All @@ -138,7 +138,7 @@ export default function App() {
}}
/>
<Button
title="test print chaining"
title="Test print chaining"
disabled={!printer}
color={!printer ? 'gray' : 'blue'}
onPress={async () => {
Expand Down
63 changes: 13 additions & 50 deletions ios/EscPosPrinter.m
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ - (NSDictionary *)constantsToExport
@"COMMAND_ADD_IMAGE_BASE_64": @(COMMAND_ADD_IMAGE_BASE_64),
@"COMMAND_ADD_IMAGE_ASSET": @(COMMAND_ADD_IMAGE_ASSET),
@"COMMAND_ADD_CUT": @(COMMAND_ADD_CUT),
@"COMMAND_ADD_DATA": @(COMMAND_ADD_DATA),
@"EPOS2_ALIGN_LEFT": @(EPOS2_ALIGN_LEFT),
@"EPOS2_ALIGN_RIGHT": @(EPOS2_ALIGN_RIGHT),
@"EPOS2_ALIGN_CENTER": @(EPOS2_ALIGN_CENTER),
Expand All @@ -78,6 +79,7 @@ - (NSDictionary *)constantsToExport
COMMAND_ADD_IMAGE_BASE_64,
COMMAND_ADD_IMAGE_ASSET,
COMMAND_ADD_CUT,
COMMAND_ADD_DATA
};

+ (BOOL)requiresMainQueueSetup
Expand All @@ -101,19 +103,6 @@ + (BOOL)requiresMainQueueSetup
self.printerAddress = target;
}

RCT_EXPORT_METHOD(printBase64: (NSString *)base64string
withResolver:(RCTPromiseResolveBlock)resolve
withRejecter:(RCTPromiseRejectBlock)reject)
{
[tasksQueue addOperationWithBlock: ^{
[self printFromBase64:base64string onSuccess:^(NSString *result) {
resolve(result);
} onError:^(NSString *error) {
reject(@"event_failure",error, nil);
}];
}];
}

RCT_EXPORT_METHOD(getPaperWidth:(RCTPromiseResolveBlock)resolve
withRejecter:(RCTPromiseRejectBlock)reject)
{
Expand Down Expand Up @@ -316,39 +305,6 @@ - (void)disconnectPrinter
NSLog(@"Disconnected!");
}

- (void)printFromBase64: (NSString*)base64String onSuccess: (void(^)(NSString *))onSuccess onError: (void(^)(NSString *))onError
{

int result = EPOS2_SUCCESS;

if (self->printer == nil) {
NSString *errorString = [ErrorManager getEposErrorText: EPOS2_ERR_PARAM];
onError(errorString);
return;
}

NSData *data = [[NSData alloc] initWithBase64EncodedString: base64String options:0];

result = [self->printer addCommand:data];
if (result != EPOS2_SUCCESS) {
[self->printer clearCommandBuffer];
NSString *errorString = [ErrorManager getEposErrorText: result];
onError(errorString);
return;
}

result = [self printData];
if (result != EPOS2_SUCCESS) {
NSString *errorString = [ErrorManager getEposErrorText: result];
onError(errorString);
return;
}


NSString *successString = [ErrorManager getEposErrorText: EPOS2_SUCCESS];
onSuccess(successString);
}

- (void)getPrinterSettings:(int)type
onSuccess: (void(^)(NSString *))onSuccess
onError: (void(^)(NSString *))onError {
Expand Down Expand Up @@ -545,16 +501,16 @@ - (enum Epos2ErrorStatus)handleCommand: (enum PrintingCommands)command params:(N
break;
case COMMAND_ADD_IMAGE_ASSET : {
UIImage *imageData = [UIImage imageNamed: params[0]];


NSInteger imgHeight = imageData.size.height;
NSInteger imagWidth = imageData.size.width;

NSInteger width = [params[1] intValue];

CGSize size = CGSizeMake(width, imgHeight*width/imagWidth);
UIImage *scaled = [self scaleImage:imageData scaledToFillSize:size];


result = [self->printer addImage:scaled x:0 y:0
width: size.width
Expand All @@ -572,6 +528,13 @@ - (enum Epos2ErrorStatus)handleCommand: (enum PrintingCommands)command params:(N
case COMMAND_ADD_CUT :
result = [self->printer addCut:EPOS2_CUT_FEED];
break;
case COMMAND_ADD_DATA: {
NSData *data = [[NSData alloc] initWithBase64EncodedString: params[0] options:0];

result = [self->printer addCommand:data];
break;
}

}

return result;
Expand Down
2 changes: 2 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const {
COMMAND_ADD_IMAGE_BASE_64,
COMMAND_ADD_IMAGE_ASSET,
COMMAND_ADD_CUT,
COMMAND_ADD_DATA,
EPOS2_ALIGN_LEFT,
EPOS2_ALIGN_RIGHT,
EPOS2_ALIGN_CENTER,
Expand All @@ -51,6 +52,7 @@ export const PRINTING_COMMANDS = {
COMMAND_ADD_IMAGE_BASE_64,
COMMAND_ADD_IMAGE_ASSET,
COMMAND_ADD_CUT,
COMMAND_ADD_DATA,
};

export const EPOS_BOOLEANS = {
Expand Down
39 changes: 0 additions & 39 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
Platform,
} from 'react-native';
import {
BufferHelper,
getPrinterSeriesByName,
requestAndroidPermissions,
enableLocationAccessAndroid10,
Expand Down Expand Up @@ -77,44 +76,6 @@ const _default = {

return Promise.reject('No permissions granted');
},
printRawData(uint8Array: Uint8Array): Promise<IMonitorStatus> {
const buffer = new BufferHelper();
const base64String = buffer.bytesToString(uint8Array, 'base64');

let successListener: EmitterSubscription | null;
let errorListener: EmitterSubscription | null;

function removeListeners() {
successListener?.remove();
errorListener?.remove();

successListener = null;
errorListener = null;
}

return new Promise((res, rej) => {
successListener = printEventEmmiter.addListener(
'onPrintSuccess',
(status) => {
removeListeners();
res(status);
}
);

errorListener = printEventEmmiter.addListener(
'onPrintFailure',
(status) => {
removeListeners();
rej(status);
}
);

EscPosPrinter.printBase64(base64String).catch((e: Error) => {
removeListeners();
rej(e);
});
});
},

getPaperWidth(): Promise<80 | 60 | 58> {
let successListener: EmitterSubscription | null;
Expand Down
15 changes: 15 additions & 0 deletions src/printing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
EPOS_BOOLEANS,
} from './constants';
import type { IMonitorStatus } from './types';
import { BufferHelper } from './utils/BufferHelper';

const { EscPosPrinter } = NativeModules;
const printEventEmmiter = new NativeEventEmitter(EscPosPrinter);
Expand Down Expand Up @@ -304,6 +305,20 @@ class Printing {
return this;
}

/**
* Cut paper
*
* @return {object} Return the object, for easy chaining commands
*
*/
data(uint8Array: Uint8Array) {
const buffer = new BufferHelper();
const base64String = buffer.bytesToString(uint8Array, 'base64');
this._queue([PRINTING_COMMANDS.COMMAND_ADD_DATA, [base64String]]);

return this;
}

send() {
return this._send(this._buffer);
}
Expand Down

0 comments on commit 151231e

Please sign in to comment.