Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get serialnumber from usb #3

Merged
merged 4 commits into from
Mar 17, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package com.reactnativeescposprinter;

import android.app.Activity;
import android.content.Intent;

Expand All @@ -25,6 +26,7 @@

import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.Arguments;
Expand All @@ -35,211 +37,220 @@
import android.content.IntentSender;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.common.api.CommonStatusCodes;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;

@ReactModule(name = EscPosPrinterDiscoveryModule.NAME)
public class EscPosPrinterDiscoveryModule extends ReactContextBaseJavaModule implements ActivityEventListener {

private Context mContext;
private ArrayList<DeviceInfo> mPrinterList = null;
private UsbManager mUsbManager = null;
private final ReactApplicationContext reactContext;
private boolean mExtractSerialNumber = false;

public static final String NAME = "EscPosPrinterDiscovery";

interface MyCallbackInterface {
void onDone(String result);
}

}

public EscPosPrinterDiscoveryModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
mContext = reactContext;
mPrinterList = new ArrayList<DeviceInfo>();
reactContext.addActivityEventListener(this);
super(reactContext);
this.reactContext = reactContext;
mContext = reactContext;
mPrinterList = new ArrayList<DeviceInfo>();
mUsbManager = (UsbManager) reactContext.getSystemService(Context.USB_SERVICE);
reactContext.addActivityEventListener(this);
}

@Override
@NonNull
public String getName() {
return NAME;
}
@Override
@NonNull
public String getName() {
return NAME;
}

@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (data != null && resultCode == Activity.RESULT_OK) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("enableLocationSettingSuccess", "Success");
} else {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("enableLocationSettingFailure", "Failure");
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (data != null && resultCode == Activity.RESULT_OK) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("enableLocationSettingSuccess", "Success");
} else {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("enableLocationSettingFailure", "Failure");
}
}

@Override
public void onNewIntent(Intent intent) {
@Override
public void onNewIntent(Intent intent) {

}
}

@ReactMethod
public void enableLocationSetting(Promise promise) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject("Activity doesn't exist");
return;
}

@ReactMethod
public void enableLocationSetting(Promise promise) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
promise.reject("Activity doesn't exist");
return;
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

SettingsClient client = LocationServices.getSettingsClient(reactContext);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
promise.resolve("SUCCESS");
}
});

LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);;

SettingsClient client = LocationServices.getSettingsClient(reactContext);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
promise.resolve("SUCCESS");
}
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {

// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().

ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(currentActivity,
CommonStatusCodes.RESOLUTION_REQUIRED);
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(currentActivity, CommonStatusCodes.RESOLUTION_REQUIRED);

} catch (IntentSender.SendIntentException sendEx) {
promise.reject("ERROR");
}
}
} catch (IntentSender.SendIntentException sendEx) {
promise.reject("ERROR");
}
});
}
}
});
}

private void sendEvent(ReactApplicationContext reactContext,
String eventName,
@Nullable WritableArray params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
private void sendEvent(ReactApplicationContext reactContext, String eventName, @Nullable WritableArray params) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}

private void stopDiscovery() {
while (true) {
try {
Discovery.stop();
break;
}
catch (Epos2Exception e) {
} catch (Epos2Exception e) {
if (e.getErrorStatus() != Epos2Exception.ERR_PROCESSING) {
return;
}
}
}
}

private void startDiscovery(MyCallbackInterface callback) {
this.stopDiscovery();
private void startDiscovery(MyCallbackInterface callback, ReadableMap paramsMap) {
this.stopDiscovery();

FilterOption mFilterOption = new FilterOption();
if (paramsMap != null) {
mExtractSerialNumber = paramsMap.getBoolean("serialNumber");
tr3v3r marked this conversation as resolved.
Show resolved Hide resolved
}

FilterOption mFilterOption = new FilterOption();

mFilterOption.setDeviceType(Discovery.TYPE_PRINTER);
mFilterOption.setDeviceType(Discovery.TYPE_PRINTER);

mPrinterList.clear();
mPrinterList.clear();

try {
Discovery.start(mContext, mFilterOption, mDiscoveryListener);
}
catch (Exception e) {
int status = ((Epos2Exception) e).getErrorStatus();
callback.onDone("discover error! Status: " + String.valueOf(status));
//
}
}
try {
Discovery.start(mContext, mFilterOption, mDiscoveryListener);
} catch (Exception e) {
int status = ((Epos2Exception) e).getErrorStatus();
callback.onDone("discover error! Status: " + String.valueOf(status));
//
}
}

private void performDiscovery(MyCallbackInterface callback) {
final Handler handler = new Handler();
private void performDiscovery(MyCallbackInterface callback) {
final Handler handler = new Handler();

final Runnable r = new Runnable() {
public void run() {
stopDiscovery();
callback.onDone("Search completed");
}
};
final Runnable r = new Runnable() {
public void run() {
stopDiscovery();
callback.onDone("Search completed");
}
};

handler.postDelayed(r, 5000);
}
handler.postDelayed(r, 5000);
}

private String getUSBAddress(String target) {
if(target.contains("USB:")) {
private String getUSBAddress(String target) {
if (target.contains("USB:")) {
return target.substring(4, target.length());
} else {
return "";
}
}
}

private DiscoveryListener mDiscoveryListener = new DiscoveryListener() {
@Override
public void onDiscovery(final DeviceInfo deviceInfo) {
private DiscoveryListener mDiscoveryListener = new DiscoveryListener() {
@Override
public void onDiscovery(final DeviceInfo deviceInfo) {

UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public synchronized void run() {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public synchronized void run() {
mPrinterList.add(deviceInfo);
WritableArray stringArray = Arguments.createArray();

for (int counter = 0; counter < mPrinterList.size(); counter++) {

final DeviceInfo info = mPrinterList.get(counter);
WritableMap printerData = Arguments.createMap();

String usbAddress = getUSBAddress(info.getTarget());
if (mExtractSerialNumber && usbAddress != "") {
JesperBadstue marked this conversation as resolved.
Show resolved Hide resolved
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsbDevice device = mUsbManager.getDeviceList().get(usbAddress);
if (device != null) {
String serialNumber = device.getSerialNumber();
printerData.putString("serial", serialNumber);
JesperBadstue marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

printerData.putString("name", info.getDeviceName());
printerData.putString("ip", info.getIpAddress());
printerData.putString("mac", info.getMacAddress());
printerData.putString("target", info.getTarget());
printerData.putString("bt", info.getBdAddress());
printerData.putString("usb", getUSBAddress(info.getTarget()));
printerData.putString("usb", usbAddress);
stringArray.pushMap(printerData);

}

sendEvent(reactContext, "onDiscoveryDone", stringArray);

}
});
}
};

@ReactMethod
private void discover(Promise promise) {
this.startDiscovery(new MyCallbackInterface() {
@Override
public void onDone(String result) {
promise.reject(result);
}
});

this.performDiscovery(new MyCallbackInterface() {
@Override
public void onDone(String result) {
promise.resolve(result);
}
});
}
};

@ReactMethod
private void discover(final ReadableMap paramsMap, Promise promise) {
this.startDiscovery(new MyCallbackInterface() {
@Override
public void onDone(String result) {
promise.reject(result);
}
}, paramsMap);

this.performDiscovery(new MyCallbackInterface() {
@Override
public void onDone(String result) {
promise.resolve(result);
}
});
}
}
5 changes: 3 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import type {
PrinerEvents,
EventListenerCallback,
IDiscoverParams,
IPrinter,
IPrinterInitParams,
PrinterSeriesName,
Expand All @@ -35,7 +36,7 @@ const _default = {
const series = PRINTER_SERIES[seriesName];
return EscPosPrinter.init(target, series);
},
async discover(): Promise<IPrinter[]> {
async discover(params?: IDiscoverParams): Promise<IPrinter[]> {
if (
Platform.OS === 'ios' ||
((await requestAndroidPermissions()) &&
Expand All @@ -55,7 +56,7 @@ const _default = {
}
);

EscPosPrinterDiscovery.discover()
EscPosPrinterDiscovery.discover(params)
.then(() => {
removeListener();
res([]);
Expand Down
Loading