I want to implement one functionality as my ANDROID colleague did. Below is code snippet and I am having trouble converting that code to objective-c. So please guide me in right direction--- Thanks
Here is the code snippet
public String createControlParams() {
controlParams_ = "";
String expiry = "";
String delayedDelivery = "";
String restricted = "";
String priorityIndicator = "";
String acknowledgement = "";
//Note - PMessage.PRIORITY_INDICATOR_WHITE is defined as Int like 1,2,3
if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_WHITE) {
expiryTimeText_ = "";
restrictBackup = false;
restrictForward_ = false;
readAcknowledgement_ = false;
}
if (expiryTimeText_ != null && expiryTimeText_.length() > 0) {
int exptime = Integer.parseInt(expiryTimeText_);
byte h = (byte) (exptime / 60);
byte m = (byte) (exptime % 60);
expiry = new String(new byte[]{'E', 0, h, m});//??? how to get this thing in objective-c
}
if (delayDelivery) {
long timeDifference;
long deliveryTime;
// Fix
// if (midlet_.getPlatform().equalsIgnoreCase("rim")) {
//// timeDifference = Calendar.getInstance().getTimeZone().getRawOffset();
//// deliveryTime = (dateField_.getTime() - (dateField_.getTime() % (24 * 60 * 60 * 1000))) + (24 * 60 * 60 * 1000) + deliverySetTime_ - timeDifference;//+timeDifference;//(((Integer) timeSpinner.getValue()).longValue() * 1000);
// deliveryTime = (dateField_.getTime() + deliverySetTime_);// - timeDifference;
// } else {
deliveryTime = dateField_.getTime() + deliverySetTime_;// - timeDifference;
// }
if (deliveryTime > (new Date().getTime() + 2000)) { // Added to_ make message as instant delivery as opposed to_ delayed delivery if the delivery time is set in past (Added 2 seconds for message processing time)
delayedDelivery = "D" + deliveryTime;
}
}
if (restrictBackup && restrictForward_) {
restricted = new String(new byte[]{'R', (byte) 3});
} else if (restrictForward_) {
restricted = new String(new byte[]{'R', (byte) 1});
} else if (restrictBackup) {
restricted = new String(new byte[]{'R', (byte) 2});
}
if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_RED) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_RED});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_YELLOW) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_YELLOW});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_GREEN) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_GREEN});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_GRAY) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_GRAY});
} else if (priorityIndicator_ == PMessage.PRIORITY_INDICATOR_WHITE) {
priorityIndicator = new String(new byte[]{'P', (byte) PMessage.PRIORITY_INDICATOR_WHITE});
}
if (readAcknowledgement_) {
acknowledgement = new String(new byte[]{'A', PMessage.ACK_READ});
}
controlParams_ = priorityIndicator;
if (!expiry.equals("") && expiry != null) {
controlParams_ += (byte) (-128) + expiry;
}
if (!delayedDelivery.equalsIgnoreCase("") && delayedDelivery != null) {
controlParams_ += (byte) (-128) + delayedDelivery;
}
if (!restricted.equalsIgnoreCase("") && restricted != null) {
controlParams_ += (byte) (-128) + restricted;
}
if (!acknowledgement.equalsIgnoreCase("") && acknowledgement != null) {
controlParams_ += (byte) (-128) + acknowledgement;
}
return controlParams_;
// System.out.println(controlParams_);
}
private void getDraftControlParms(String controlParams_) {
if (!controlParams_.equals("") && controlParams_ != null) {
String[] sysParams = Helpers.splitUsingStringDelim(controlParams_, String.valueOf((byte) (-128)));
try {
for (int i = 0; i < sysParams.length; i++) {
if (!sysParams[i].equals("") && sysParams[i] != null) {
if (sysParams[i].substring(0, 1).equalsIgnoreCase("P")) {
priorityIndicator_ = (int) sysParams[i].getBytes()[1];
}
if (sysParams[i].substring(0, 1).equalsIgnoreCase("E")) {
int expiryFirstByte_ = sysParams[i].getBytes()[2];
int expirySecondByte_ =sysParams[i].getBytes()[3];
int expiryTime=(expiryFirstByte_ * 60) + (expirySecondByte_);
expiryMinutesField_.setText(expiryTime+"");
expiryTimeText_ = expiryMinutesField_.getText();
}
if (sysParams[i].substring(0, 1).equalsIgnoreCase("R")) {
int restrictedByte_ = (byte) sysParams[i].getBytes()[1];
if(restrictedByte_==1){
restrictForward_ = true;
restrictBackup = false;
}else if(restrictedByte_==2){
restrictForward_ = false;
restrictBackup = true;
}else{
restrictForward_ = true;
restrictBackup = true;
}
}
if (sysParams[i].substring(0, 1).equalsIgnoreCase("A")) {
readAcknowledgement_ = true;
}
}
switch (priorityIndicator_) {
case PMessage.PRIORITY_INDICATOR_RED: {
counter.getStyle().setBgColor(0xfe0002);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_YELLOW: {
counter.getStyle().setBgColor(0xffff00);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_GREEN: {
counter.getStyle().setBgColor(0x80ff00);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_GRAY: {
counter.getStyle().setBgColor(0x919594);
counter.getStyle().setBgTransparency(255);
break;
}
case PMessage.PRIORITY_INDICATOR_WHITE: {
counter.getStyle().setBgColor(0xffffff);
counter.getStyle().setBgTransparency(255);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm not an Objective C guy, but have you tried using char? In C/C++ a char is one byte and should do what you need it to.
You don't need to use bytes. You can use an NSArray of NSStrings.
Bytes, or unsigned char's in C, are more useful when you are concerned about the memory size of some data in a constrained environment.
Related
I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.
I have tried many sample codes to parse APDU response to TLV format.
I am able to parse it properly if the response length is less but facing issue if length is more(how calculate length of a tag without any libraries)
NOTE: I am using predefined tags in Constants
code:
private HashMap<String, String> parseTLV(String apduResponse) {
HashMap<String, String> tagValue = new HashMap<>();
String remainingApdu = apduResponse.replaceAll(" ", "");
if (remainingApdu.endsWith(ResponseTags._SUCCESS_STATUSWORDS)) {
remainingApdu = remainingApdu.substring(0, remainingApdu.length() - 4);
}
while (remainingApdu != null && remainingApdu.length() > 2) {
remainingApdu = addTagValue(tagValue, remainingApdu);
}
return tagValue;
}
addTagValue method
private String addTagValue(HashMap<String, String> tagValue, String apduResponse) {
String tag = "";
String length = "";
String value = "";
int tagLen = 0;
if (tagUtils.isValidTag(apduResponse.substring(0, 2))) {
tagLen = readTagLength(apduResponse.substring(3));
// tagLen = 2;
tag = apduResponse.substring(0, 2);
} else if (tagUtils.isValidTag(apduResponse.substring(0, 4))) {
tagLen = 4;
tag = apduResponse.substring(0, 4);
} else {
return "";
}
Log.e("TAG_LEN","tag: "+tag+"taglen: "+tagLen);
if (tagUtils.shouldCheckValueFor(tag)) {
length = apduResponse.substring(tagLen, tagLen + 2);
int len = tagUtils.hexToDecimal(length);
value = apduResponse.substring(tagLen + 2, (len * 2) + tagLen + 2);
tagValue.put(tag, value);
if (ResponseTags.getRespTagsmap().containsKey(tag)) {
//logData = logData + "\nKEY:" + tag + " TAG:" + ResponseTags.getRespTagsmap().get(tag)/* + " VALUE:" + value + "\n "*/;
}
if (tagUtils.isTemplateTag(tag)) {
// logData = logData + "\n\t-->";
return addTagValue(tagValue, value) + apduResponse.substring(tag.length() + value.length() + length.length());
} else {
return apduResponse.substring(tag.length() + value.length() + length.length());
}
} else {
value = apduResponse.substring(2, 4);
tagValue.put(tag, value);
// logData = logData + "\n\t\tKEY:" + tag + " TAG:" + ResponseTags.getRespTagsmap().get(tag) /*+ " VALUE:" + value + "\n "*/;
return apduResponse.substring(tag.length() + value.length() + length.length());
}
}
readTagLength :
private int readTagLength(String apduResponse) {
int len_bytes = 0;
if (apduResponse.length() > 2) {
len_bytes = (apduResponse.length()) / 2;
}
Log.e("tlv length:", "bytes:" + len_bytes);
if (len_bytes < 128) {
return 2;
} else if (len_bytes > 127 && len_bytes < 255) {
return 4;
} else {
return 6;
}
}
I cannot able to get length properly for few cards(if apdu response is long)
Please help
First be sure the input data is proper before you go into the code. Take the full data and try it on https://www.emvlab.org/tlvutils/ .
Once its confirmed the data is proper, go through in EMV 4.3 Book 3,
Annex B Rules for BER-TLV Data Objects sections B1, B2, B3 - with utmost attention.
If you follow this precisely, then you wouldn't need to store a static list of tags; will save time in future.
Below sample has an assumption that TLV array is ending with special 0x00 tag but for sure you can ignore it.
Pojo class :
public class Tlv {
private short tag;
private byte[] value;
public Tlv(short tag) {
this.tag = tag;
}
public short getTag() {
return tag;
}
public byte[] getValue() {
return value;
}
public void setValue(byte[] valueBytes) {
this.value = valueBytes;
}
}
Utility method :
public static Map<Byte, Tlv> parse(ByteBuffer bb) throws TlvException {
Map<Byte, Tlv> tlvs = null;
tlvs = new HashMap<Byte, Tlv>();
try {
while (bb.remaining() > 0) {
byte tag = bb.get();
if(tag == 0x00)
continue;
int length = bb.get();
byte[] value = new byte[length];
bb.get(value, 0, length);
Tlv tlv = new Tlv(tag);
tlv.setValue(value);
tlvs.put(tag, tlv);
}
} catch (IndexOutOfBoundsException e) {
throw new TlvException("Malformed TLV part: " + bb.toString() + ".", e);
}
return tlvs;
}
Basically I'm helping a friend of mine out,
There's a disconnection error with his game (runescape private server) and there's an error that keeps being thrown, which is
DataInputStream.readFully(Unknown Source)
at Client.streamLoaderForName(Client.java:7343)
I read some things up on using while(in.available() > 0), but I don't know where it'd be placed.
This is the method where the error occurs
private CacheArchive streamLoaderForName(int i, String s, String s1, int j, int k)
{
byte abyte0[] = null;
int l = 5;
try
{
if(cacheIndices[0] != null)
abyte0 = cacheIndices[0].get(i);
}
catch(Exception _ex) { }
if(abyte0 != null)
{
CacheArchive streamLoader = new CacheArchive(abyte0);
return streamLoader;
}
int j1 = 0;
while(abyte0 == null)
{
String s2 = "Unknown error";
setLoadingText(k, "Requesting " + s);
Object obj = null;
try
{
int k1 = 0;
DataInputStream datainputstream = jaggrabRequest(s1 + j);
byte[] abyte1 = new byte[6];
datainputstream.readFully(abyte1, 0, 6);
Stream stream = new Stream(abyte1);
stream.currentOffset = 3;
int i2 = stream.read3Bytes() + 6;
int j2 = 6;
abyte0 = new byte[i2];
System.arraycopy(abyte1, 0, abyte0, 0, 6);
while(j2 < i2)
{
int l2 = i2 - j2;
if(l2 > 1000)
l2 = 1000;
int j3 = datainputstream.read(abyte0, j2, l2);
if(j3 < 0)
{
s2 = "Length error: " + j2 + "/" + i2;
throw new IOException("EOF");
}
j2 += j3;
int k3 = (j2 * 100) / i2;
k1 = k3;
}
datainputstream.close();
try
{
if(cacheIndices[0] != null)
cacheIndices[0].put(abyte0.length, abyte0, i);
}
catch(Exception _ex)
{
cacheIndices[0] = null;
}
}
catch(IOException ioexception)
{
ioexception.printStackTrace();
if(s2.equals("Unknown error"))
s2 = "Connection error";
abyte0 = null;
}
catch(NullPointerException _ex)
{
s2 = "Null error";
abyte0 = null;
}
catch(ArrayIndexOutOfBoundsException _ex)
{
s2 = "Bounds error";
abyte0 = null;
}
catch(Exception _ex)
{
s2 = "Unexpected error";
abyte0 = null;
}
if(abyte0 == null)
{
for(int l1 = l; l1 > 0; l1--)
{
if(j1 >= 3)
{
setLoadingText(k, "Game updated - please reload page");
l1 = 10;
} else
{
setLoadingText(k, s2 + " - Retrying in " + l1);
}
try
{
Thread.sleep(1000L);
}
catch(Exception _ex) { }
}
l *= 2;
if(l > 60)
l = 60;
}
}
CacheArchive streamLoader_1 = new CacheArchive(abyte0);
return streamLoader_1;
}
I can't seem to find out where to do any placements or how to fix this error. By the way, the line that's 7343, is
datainputstream.readFully(abyte1, 0, 6);
Also sorry for the poor thread, I don't know how to write it up properly on this.
I have an application in which I connected with a device which is connected by USB when I start to ping this device my application is crashed. This device is a RFID scanner which is connected to the phone by USB. A phone and my application see the connected phone with this scanner.
This is a code :
#Override
public synchronized void run() {
if (context == null || usbDevice == null) {
onStatusChanged(Status.NoContextOrUsbDeviceSpecified);
return;
}
//l("Device -> " + usbDevice);
UsbInterface usbInterface = null;
UsbEndpoint usbEndpointIn = null;
UsbEndpoint usbEndpointOut = null;
for (int i = 0; i < usbDevice.getInterfaceCount(); i++) {
usbInterface = usbDevice.getInterface(i);
//l("Interface[" + i + "] -> " + usbInterface);
if (usbInterface != null) {
for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
UsbEndpoint usbEndpoint = usbInterface.getEndpoint(j);
//l("Endpoint[" + j + "] -> " + usbEndpoint);
if (usbEndpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
l("Found input!");
usbEndpointIn = usbEndpoint;
}
else {
l("Found output!");
usbEndpointOut = usbEndpoint;
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
}
}
if (usbEndpointIn != null && usbEndpointOut != null) {
break;
}
}
else {
//l("Interface was null");
}
}
if (usbEndpointIn == null || usbEndpointOut == null) {
onStatusChanged(Status.NoEndpointsFoundOnUsbDevice);
return;
}
UsbManager usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(usbDevice);
if (usbDeviceConnection == null) {
onStatusChanged(Status.CouldntOpenUsbDeviceConnection);
return;
}
if (!usbDeviceConnection.claimInterface(usbInterface, true)) {
onStatusChanged(Status.CouldntClaimUsbDeviceInterface);
return;
}
onStatusChanged(Status.ScanningInitializing);
currentUsbDeviceConnection = usbDeviceConnection;
currentUsbInterface = usbInterface;
currentUsbEndpointIn = usbEndpointIn;
currentUsbEndpointOut = usbEndpointOut;
// Toast.makeText(context,send(PING) + " wysłane" , Toast.LENGTH_LONG).show();
final String[] a = new String[1];
pingingThread = new Thread(() -> {
onStatusChanged(Status.PingStarted);
String s = "";
for (byte aPING : PING) {
s = s + aPING;
}
Log.e("Ping " , s);
String aa ="";
for (byte aACK : ACK) {
aa = aa + aACK;
}
Log.e("ACK " , aa);
while (shouldPing && !Thread.interrupted()) {
if (send(PING) >= 0) {
onStatusChanged(Status.PingSuccessful);
} else {
onStatusChanged(Status.PingFailed);
}
SystemClock.sleep(PING_RECEIVE_TIMEOUT / 3);
}
onStatusChanged(Status.PingStopped);
scheduleStopReceiving();
});
byte[] bytes = new byte[36];
int result = currentUsbDeviceConnection.bulkTransfer(currentUsbEndpointIn, bytes, bytes.length, RECEIVE_TIMEOUT);
// Toast.makeText(context, "result " + result , Toast.LENGTH_LONG ).show();
receivingThread = new Thread(() -> {
onStatusChanged(Status.ReceivingStarted);
long lastTagTimestamp = 0;
boolean wasInterrupted = false;
while (shouldReceive) {
byte[] received = receive(36);
if (received != null) {
if (received[0] != (byte) 0xab ||
received[1] != (byte) 0xba ||
received[2] != (byte) 0xcd ||
received[3] != (byte) 0xdc) {
onStatusChanged(Status.ReceivedUnknown);
} else if (received[4] == 0x00) {
if (send(ACK) < 0) {
continue;
}
onStatusChanged(Status.ReceivedTag);
lastTagTimestamp = System.currentTimeMillis();
byte[] tag = new byte[8];
int index = 0;
while (index < tag.length) {
tag[index++] = received[8 + index];
}
long longValue = ByteBuffer.wrap(tag).getLong();
String hexValue = Long.toHexString(longValue).toUpperCase();
onScanCompleted(hexValue);
} else if (received[4] == 0x02) {
onStatusChanged(Status.ReceivedPing);
}
}
if (Thread.interrupted()) {
wasInterrupted = true;
}
if (wasInterrupted) {
if (lastTagTimestamp == 0) {
lastTagTimestamp = System.currentTimeMillis();
}
if (lastTagTimestamp + PING_RECEIVE_TIMEOUT < System.currentTimeMillis()) {
break;
}
}
}
onStatusChanged(Status.ReceivingStopped);
close();
});
shouldPing = true;
shouldReceive = true;
pingingThread.start();
receivingThread.start();
}
In this line I have
java.lang.NoSuchMethodError: No direct method
(Ljava/lang/Object;)V in class
Lrest/hello/org/usbdevice/rfid2/-$Lambda$2; or its super classes
(declaration of 'rest.hello.org.usbdevice.rfid2.-$Lambda$2' appears in
/data/app/rest.hello.org.usbdevice-2/base.apk)
pingingThread = new Thread(() -> {
onStatusChanged(Status.PingStarted);
String s = "";
for (byte aPING : PING) {
s = s + aPING;
}
Log.e("Ping " , s);
String aa ="";
for (byte aACK : ACK) {
aa = aa + aACK;
}
Log.e("ACK " , aa);
I was using processing in netbeans to play a movie on an array of ledstrips and I am using OPC.class for ledstrip fadecandy mapping. This code works on the processing sketch, but when I tried to use it on netbeans the loadpixel() in draw() method of OPC.java throws a nullpointer exception.
Stacktrace:
Exception in thread "Animation Thread" java.lang.NullPointerException
at processing.core.PApplet.loadPixels(PApplet.java:10625)
at com.processing.OPC.draw(OPC.java:139)
at com.processing.Video.draw(Video.java:62)
at processing.core.PApplet.handleDraw(PApplet.java:2402)
at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1527)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)
Video.java
public class Video extends PApplet
{
OPC opc;
Movie movie;
public static void main(String args[])
{
PApplet.main(new String[] { "--present", "com.processing.Video" });
}
public void settings()
{
size(600, 240);
}
public void setup()
{
opc = new OPC(this, "192.168.15.10", 7890);
for(int i=0; i<24; i++) {
opc.ledStrip(i * 60, 60,
300, i * 240 / 24 + 240 / 48, 240 / 24, PI, false);
}
movie = new Movie(this, "waffle.mp4");
movie.loop();
}
public void movieEvent(Movie m)
{
m.read();
}
#Override
public void draw()
{
if (movie.available() == true) {
movie.read();
}
image(movie, 0, 0, width, height);
}
}
OPC.java
public class OPC extends PApplet implements Runnable
{
Thread thread;
Socket socket;
OutputStream output, pending;
String host;
int port;
int height = 240;
int width = 600;
int[] pixelLocations;
byte[] packetData;
byte firmwareConfig;
String colorCorrection;
boolean enableShowLocations;
PApplet parent;
OPC(PApplet parent, String host, int port)
{
this.host = host;
this.port = port;
thread = new Thread(this);
thread.start();
this.enableShowLocations = true;
registerMethod("draw", this);
}
public void led(int index, int x, int y){
if (pixelLocations == null) {
pixelLocations = new int[index + 1];
} else if (index >= pixelLocations.length) {
pixelLocations = Arrays.copyOf(pixelLocations, index + 1);
}
pixelLocations[index] = x + 600 * y;
}
public void ledStrip(int index, int count, float x, float y, float spacing, float angle, boolean reversed)
{
float s = sin(angle);
float c = cos(angle);
for (int i = 0; i < count; i++) {
led(reversed ? (index + count - 1 - i) : (index + i),
(int)(x + (i - (count-1)/2.0) * spacing * c + 0.5),
(int)(y + (i - (count-1)/2.0) * spacing * s + 0.5));
}
}
void showLocations(boolean enabled)
{
enableShowLocations = enabled;
}
void setColorCorrection(String s)
{
colorCorrection = s;
sendColorCorrectionPacket();
}
void sendFirmwareConfigPacket()
{
if (pending == null) {
return;
}
byte[] packet = new byte[9];
packet[0] = (byte)0x00; // Channel (reserved)
packet[1] = (byte)0xFF; // Command (System Exclusive)
packet[2] = (byte)0x00; // Length high byte
packet[3] = (byte)0x05; // Length low byte
packet[4] = (byte)0x00; // System ID high byte
packet[5] = (byte)0x01; // System ID low byte
packet[6] = (byte)0x00; // Command ID high byte
packet[7] = (byte)0x02; // Command ID low byte
packet[8] = (byte)firmwareConfig;
try {
pending.write(packet);
} catch (Exception e) {
dispose();
}
}
void sendColorCorrectionPacket()
{
if (colorCorrection == null) {
return;
}
if (pending == null) {
return;
}
byte[] content = colorCorrection.getBytes();
int packetLen = content.length + 4;
byte[] header = new byte[8];
header[0] = (byte)0x00; // Channel (reserved)
header[1] = (byte)0xFF; // Command (System Exclusive)
header[2] = (byte)(packetLen >> 8); // Length high byte
header[3] = (byte)(packetLen & 0xFF); // Length low byte
header[4] = (byte)0x00; // System ID high byte
header[5] = (byte)0x01; // System ID low byte
header[6] = (byte)0x00; // Command ID high byte
header[7] = (byte)0x01; // Command ID low byte
try {
pending.write(header);
pending.write(content);
} catch (Exception e) {
dispose();
}
}
public void draw()
{
if (pixelLocations == null) {
return;
}
if (output == null) {
return;
}
int numPixels = pixelLocations.length;
int ledAddress = 4;
setPixelCount(numPixels);
println("pixel loading");
loadPixels();
println("pixel loaded123");
for (int i = 0; i < numPixels; i++) {
int pixelLocation = pixelLocations[i];
int pixel = pixels[pixelLocation];
packetData[ledAddress] = (byte)(pixel >> 16);
packetData[ledAddress + 1] = (byte)(pixel >> 8);
packetData[ledAddress + 2] = (byte)pixel;
ledAddress += 3;
if (true) {
pixels[pixelLocation] = 0xFFFFFF ^ pixel;
}
}
writePixels();
if (enableShowLocations) {
updatePixels();
print("a");
}
}
void setPixelCount(int numPixels)
{
int numBytes = 3 * numPixels;
int packetLen = 4 + numBytes;
if (packetData == null || packetData.length != packetLen) {
// Set up our packet buffer
packetData = new byte[packetLen];
packetData[0] = (byte)0x00;
packetData[1] = (byte)0x00;
packetData[2] = (byte)(numBytes >> 8);
packetData[3] = (byte)(numBytes & 0xFF);
}
}
void setPixel(int number, int c)
{
println("set");
int offset = 4 + number * 3;
if (packetData == null || packetData.length < offset + 3) {
setPixelCount(number + 1);
}
packetData[offset] = (byte) (c >> 16);
packetData[offset + 1] = (byte) (c >> 8);
packetData[offset + 2] = (byte) c;
}
int getPixel(int number)
{
println("get");
int offset = 4 + number * 3;
if (packetData == null || packetData.length < offset + 3) {
return 0;
}
return (packetData[offset] << 16) | (packetData[offset + 1] << 8) | packetData[offset + 2];
}
void writePixels()
{
println("write");
if (packetData == null || packetData.length == 0) {
return;
}
if (output == null) {
return;
}
try {
output.write(packetData);
} catch (Exception e) {
dispose();
}
}
public void dispose()
{
if (output != null) {
println("Disconnected from OPC server");
}
socket = null;
output = pending = null;
}
public void run()
{
println("?");
if(output == null) { // No OPC connection?
try { // Make one!
socket = new Socket(host, port);
socket.setTcpNoDelay(true);
pending = socket.getOutputStream();
println("Connected to OPC server");
sendColorCorrectionPacket();
sendFirmwareConfigPacket();
output = pending;
} catch (ConnectException e) {
dispose();
} catch (IOException e) {
dispose();
}
}
try {
Thread.sleep(500);
}
catch(InterruptedException e) {
}
}
}
You should only have one class that extends PApplet.
Think of that class as your "main" class. Any other classes that need to use Processing functions will need an instance of that main class in order to access Processing functions. You can pass it in using the this keyword.
In fact, you're already doing that- notice that you pass this into your OPC class, and then store it in the parent parameter. You just never do anything with that parameter.
So step 1 is to remove the extends PApplet from your OBC class:
public class OPC implements Runnable
This will cause some compilation errors. That's okay, we'll fix them later.
Step 2 is to actually store the PApplet parent parameter in a class-level variable.
OPC(PApplet parent, String host, int port){
this.parent = parent;
//rest of constructor
Now that you have that, step 3 is to fix any compilation errors by using the parent variable to access Processing functions.
parent.println("pixel loading");
parent.loadPixels();
More info can be found in the Processing in eclipse tutorial. It's for eclipse, but the same principles apply in netbeans.