Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to get my class XML screen but with no success,
Until now I was able to create activity, and use startActivity(activity.class)
but now there is a problem.
At the main Java file of my app i call FTDI class :
public void onFTDIClick(View view){
startActivity(new Intent(this,FTDI.class));
}
The FTDI class:
package com.application.i;
import java.util.ArrayList;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
public class FTDI extends Fragment{
static Context DeviceUARTContext;
D2xxManager ftdid2xx;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
EditText writeText;
Spinner baudSpinner;;
Spinner stopSpinner;
Spinner dataSpinner;
Spinner paritySpinner;
Spinner flowSpinner;
Spinner portSpinner;
ArrayAdapter<CharSequence> portAdapter;
Button configButton;
Button openButton;
Button readEnButton;
Button writeButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
ArrayList<CharSequence> portNumberList;
public static final int readLength = 512;
public int readcount = 0;
public int iavailable = 0;
byte[] readData;
char[] readDataToText;
public boolean bReadThreadGoing = false;
public readThread read_thread;
boolean uart_configured = false;
// Empty Constructor
public FTDI()
{
}
/* Constructor */
public FTDI(Context parentContext , D2xxManager ftdid2xxContext)
{
DeviceUARTContext = parentContext;
ftdid2xx = ftdid2xxContext;
}
public int getShownIndex() {
return getArguments().getInt("index", 5);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.ftdisub, container, false);
readData = new byte[readLength];
readDataToText = new char[readLength];
readText = (EditText) view.findViewById(R.id.ReadValues);
readText.setInputType(0);
/* by default it is 9600 */
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
createDeviceList();
}
#Override
public void onStop()
{
disconnectFunction();
super.onStop();
}
public void notifyUSBDeviceAttach()
{
createDeviceList();
}
public void notifyUSBDeviceDetach()
{
disconnectFunction();
}
public void createDeviceList()
{
int tempDevCount = ftdid2xx.createDeviceInfoList(DeviceUARTContext);
if (tempDevCount > 0)
{
if( DevCount != tempDevCount )
{
DevCount = tempDevCount;
updatePortNumberSelector();
}
}
else
{
DevCount = -1;
currentIndex = -1;
}
}
public void disconnectFunction()
{
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if(ftDev != null)
{
synchronized(ftDev)
{
if( true == ftDev.isOpen())
{
ftDev.close();
}
}
}
}
public void connectFunction()
{
int tmpProtNumber = openIndex + 1;
if( currentIndex != openIndex )
{
if(null == ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
else
{
synchronized(ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
}
uart_configured = false;
}
else
{
Toast.makeText(DeviceUARTContext,"Device port " + tmpProtNumber + " is already opened",Toast.LENGTH_LONG).show();
return;
}
if(ftDev == null)
{
Toast.makeText(DeviceUARTContext,"open device port("+tmpProtNumber+") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen())
{
currentIndex = openIndex;
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if(false == bReadThreadGoing)
{
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
}
else
{
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
//Toast.makeText(DeviceUARTContext, "Need to get permission!", Toast.LENGTH_SHORT).show();
}
}
public void updatePortNumberSelector()
{
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl)
{
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
// configure our port
// reset to UART mode for 232 devices
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
switch (dataBits) {
case 7:
dataBits = D2xxManager.FT_DATA_BITS_7;
break;
case 8:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
default:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
}
switch (stopBits) {
case 1:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
case 2:
stopBits = D2xxManager.FT_STOP_BITS_2;
break;
default:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
}
switch (parity) {
case 0:
parity = D2xxManager.FT_PARITY_NONE;
break;
case 1:
parity = D2xxManager.FT_PARITY_ODD;
break;
case 2:
parity = D2xxManager.FT_PARITY_EVEN;
break;
case 3:
parity = D2xxManager.FT_PARITY_MARK;
break;
case 4:
parity = D2xxManager.FT_PARITY_SPACE;
break;
default:
parity = D2xxManager.FT_PARITY_NONE;
break;
}
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
short flowCtrlSetting;
switch (flowControl) {
case 0:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
case 1:
flowCtrlSetting = D2xxManager.FT_FLOW_RTS_CTS;
break;
case 2:
flowCtrlSetting = D2xxManager.FT_FLOW_DTR_DSR;
break;
case 3:
flowCtrlSetting = D2xxManager.FT_FLOW_XON_XOFF;
break;
default:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
}
// TODO : flow ctrl: XOFF/XOM
// TODO : flow ctrl: XOFF/XOM
ftDev.setFlowControl(flowCtrlSetting, (byte) 0x0b, (byte) 0x0d);
uart_configured = true;
Toast.makeText(DeviceUARTContext, "Config done", Toast.LENGTH_SHORT).show();
}
public void EnableRead (){
iEnableReadFlag = (iEnableReadFlag + 1)%2;
if(iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
}
else{
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
}
}
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(iavailable > 0)
{
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread
{
Handler mHandler;
readThread(Handler h){
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run()
{
int i;
while(true == bReadThreadGoing)
{
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
synchronized(ftDev)
{
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if(iavailable > readLength){
iavailable = readLength;
}
ftDev.read(readData, iavailable);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if(DevCount > 0)
{
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
The XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="#+id/PITCHING"
android:textSize="15sp" />
<TextView android:text = "Read Bytes"
android:textStyle="bold"
android:gravity="center"
android:id="#+id/ReadBytes"
android:layout_height="fill_parent"
android:layout_width="0dp"
android:layout_weight="1"
/>
<EditText
android:id="#+id/ReadValues"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:layout_weight="4"
android:background="#708070"
android:focusableInTouchMode="false"
android:gravity="left|center_vertical"
/>
<Button android:id="#+id/readEnButton"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_margin="10dp"
android:gravity="center"
android:scaleType="centerInside"
android:layout_weight="1"
android:text="Read Enabled"
/>
</LinearLayout>
At the manifest file:
<activity
android:name=".FTDI"
android:label="Reading Circuit Data"
android:theme="#android:style/Theme.Holo" >
</activity>
Until now i used , before working with Frgment:
package com.application.i;
import android.app.Activity;
import android.os.Bundle;
public class FTDI extends Activity
{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.ftdisub);
}
}
As i press the button on my main screen it stuck, the hole application finished with error.
Edit:
My problem is that I need a UI to check this class and then to put it as a Service, I know how to Service it, without user interface.
I changed the code to be an activity and it looks :
package com.application.i;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
public class FTDI extends Activity{
static Context DeviceUARTContext;
D2xxManager ftdid2xx;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
EditText writeText;
Spinner baudSpinner;;
Spinner stopSpinner;
Spinner dataSpinner;
Spinner paritySpinner;
Spinner flowSpinner;
Spinner portSpinner;
ArrayAdapter<CharSequence> portAdapter;
Button configButton;
Button openButton;
Button readEnButton;
Button writeButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
ArrayList<CharSequence> portNumberList;
public static final int readLength = 512;
public int readcount = 0;
public int iavailable = 0;
byte[] readData;
char[] readDataToText;
public boolean bReadThreadGoing = false;
public readThread read_thread;
boolean uart_configured = false;
// Empty Constructor
public FTDI()
{
}
/* Constructor */
public FTDI(Context parentContext , D2xxManager ftdid2xxContext)
{
DeviceUARTContext = parentContext;
ftdid2xx = ftdid2xxContext;
}
// public int getShownIndex() {
// return getArguments().getInt("index", 5);
// }
// #Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// if (container == null) {
// return null;
// }
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.ftdisub);
// View view = inflater.inflate(R.layout.ftdisub, container, false);
readData = new byte[readLength];
readDataToText = new char[readLength];
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
/* by default it is 9600 */
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
}
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
//
// }
#Override
public void onStart() {
super.onStart();
createDeviceList();
}
#Override
public void onStop()
{
disconnectFunction();
super.onStop();
}
public void notifyUSBDeviceAttach()
{
createDeviceList();
}
public void notifyUSBDeviceDetach()
{
disconnectFunction();
}
public void createDeviceList()
{
int tempDevCount = ftdid2xx.createDeviceInfoList(DeviceUARTContext);
if (tempDevCount > 0)
{
if( DevCount != tempDevCount )
{
DevCount = tempDevCount;
updatePortNumberSelector();
}
}
else
{
DevCount = -1;
currentIndex = -1;
}
}
public void disconnectFunction()
{
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if(ftDev != null)
{
synchronized(ftDev)
{
if( true == ftDev.isOpen())
{
ftDev.close();
}
}
}
}
public void connectFunction()
{
int tmpProtNumber = openIndex + 1;
if( currentIndex != openIndex )
{
if(null == ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
else
{
synchronized(ftDev)
{
ftDev = ftdid2xx.openByIndex(DeviceUARTContext, openIndex);
}
}
uart_configured = false;
}
else
{
Toast.makeText(DeviceUARTContext,"Device port " + tmpProtNumber + " is already opened",Toast.LENGTH_LONG).show();
return;
}
if(ftDev == null)
{
Toast.makeText(DeviceUARTContext,"open device port("+tmpProtNumber+") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen())
{
currentIndex = openIndex;
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if(false == bReadThreadGoing)
{
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
}
else
{
Toast.makeText(DeviceUARTContext, "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
//Toast.makeText(DeviceUARTContext, "Need to get permission!", Toast.LENGTH_SHORT).show();
}
}
public void updatePortNumberSelector()
{
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl)
{
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
// configure our port
// reset to UART mode for 232 devices
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
switch (dataBits) {
case 7:
dataBits = D2xxManager.FT_DATA_BITS_7;
break;
case 8:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
default:
dataBits = D2xxManager.FT_DATA_BITS_8;
break;
}
switch (stopBits) {
case 1:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
case 2:
stopBits = D2xxManager.FT_STOP_BITS_2;
break;
default:
stopBits = D2xxManager.FT_STOP_BITS_1;
break;
}
switch (parity) {
case 0:
parity = D2xxManager.FT_PARITY_NONE;
break;
case 1:
parity = D2xxManager.FT_PARITY_ODD;
break;
case 2:
parity = D2xxManager.FT_PARITY_EVEN;
break;
case 3:
parity = D2xxManager.FT_PARITY_MARK;
break;
case 4:
parity = D2xxManager.FT_PARITY_SPACE;
break;
default:
parity = D2xxManager.FT_PARITY_NONE;
break;
}
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
short flowCtrlSetting;
switch (flowControl) {
case 0:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
case 1:
flowCtrlSetting = D2xxManager.FT_FLOW_RTS_CTS;
break;
case 2:
flowCtrlSetting = D2xxManager.FT_FLOW_DTR_DSR;
break;
case 3:
flowCtrlSetting = D2xxManager.FT_FLOW_XON_XOFF;
break;
default:
flowCtrlSetting = D2xxManager.FT_FLOW_NONE;
break;
}
// TODO : flow ctrl: XOFF/XOM
// TODO : flow ctrl: XOFF/XOM
ftDev.setFlowControl(flowCtrlSetting, (byte) 0x0b, (byte) 0x0d);
uart_configured = true;
Toast.makeText(DeviceUARTContext, "Config done", Toast.LENGTH_SHORT).show();
}
public void EnableRead (){
iEnableReadFlag = (iEnableReadFlag + 1)%2;
if(iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
}
else{
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
}
}
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(iavailable > 0)
{
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread
{
Handler mHandler;
readThread(Handler h){
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run()
{
int i;
while(true == bReadThreadGoing)
{
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
synchronized(ftDev)
{
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if(iavailable > readLength){
iavailable = readLength;
}
ftDev.read(readData, iavailable);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if(DevCount > 0)
{
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
Any suggestions?
To attach a fragment to an Activity you have two ways:
1) Declare the fragment inside the activity's layout file.
2) Programmatically add the fragment to an existing ViewGroup.
In my opinion you can use the second way, so basically you need a ViewGroup in the activity where to put the Fragment; something like a Layout can be good for that.
When you have the place where to insert the Fragment you can insert it using the LayoutInfleter.
Fragment fragment = new YourFragment();
getLayoutInflater.inflate(R.id.youLayoutContainer, fragment, false);
Take a look at the page below for more informations:
http://developer.android.com/guide/components/fragments.html
Related
I have tried using plugins available:
flutter_android
This includes:
Sensor
SensorEvent
SensorEventListener
SensorManager
usb_serial
So i need to talk to usb devices however the plugin usb_serial
does not meet my needs since i need to use more than the package provides.
Basically i either need to create my own plugin or i need to find a way to expose the native android.hardware.usb to flutter.
Need help i don't know what is best or how to do either.
This was a long time ago but will try to help as best as possible
Since I was not able to find anything that met my needs I needed to create my own plugin using these
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
My MainActivity look like this
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String TAG = "D2XX";
private static final String CHANNEL = "bridge";
private static final String EVENT_CHANNEL = "event";
private static final String INPUT_EVENT_CHANNEL = "input";
private D2xxManager m_deviceManager = null;
private FT_Device m_connectedDevice;
private CONTROLLER_ENUMS m_CONTROLLER_STATUS = CONTROLLER_ENUMS.Closed;
private int m_iDeviceCount = 0;
private List<D2xxManager.FtDeviceInfoListNode> mDeviceInfoListNode;
private CountDownTimer m_updateTimer;
private final String m_initialBitMask = "00111100";
private boolean m_input1State = false;
private boolean m_input2State = false;
private boolean m_output1State = false;
private boolean m_output2State = false;
private static boolean bRegisterBroadcast = true;
private long timeLeftInMilliseconds;
private boolean m_MountedState = false;
boolean isRunning = false;
private enum CONTROLLER_ENUMS {
OK,
Opened,
Closed,
Failed,
}
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler((call, result) -> {
String strCallName = call.method.toUpperCase();
switch (strCallName) {
case "INITIALIZE": {
m_CONTROLLER_STATUS = CONTROLLER_ENUMS.OK;
boolean bConnected = Initialise();
result.success(bConnected);
}
break;
case "GETDEVICE": {
JSONObject retVal = GetDeviceList();
if (retVal != null) {
result.success(retVal.toString());
}
}
break;
case "CONNECTDEVICE": {
try {
String strSerialNumber = call.argument("SerialNumber");
if (m_connectedDevice == null) {
boolean bConnected = ConnectToDevice(strSerialNumber);
result.success(bConnected);
} else {
result.success(true);
}
} catch (Exception e) {
Log.e(TAG, "CONNECT TO DEVICE ANDROID EXC: ", e);
}
}
break;
case "SETOUTPUT": {
int output = (int) call.argument("outputNumber");
boolean state = (boolean) call.argument("state");
SetOutputs(output, state);
}
break;
case "GETINPUT": {
JSONObject retVal = CheckDeviceInputs();
if (retVal != null) {
result.success(retVal.toString());
}
}
break;
default:
break;
}
});
new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), EVENT_CHANNEL).setStreamHandler(
new EventChannel.StreamHandler() {
private BroadcastReceiver usbStateChangeReceiver;
#Override
public void onListen(Object arguments, EventChannel.EventSink events) {
usbStateChangeReceiver = createUSBStateChangeReceiver(events);
IntentFilter filter = new IntentFilter();
filter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED");
filter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
registerReceiver(
usbStateChangeReceiver, filter);
}
#Override
public void onCancel(Object arguments) {
unregisterReceiver(usbStateChangeReceiver);
usbStateChangeReceiver = null;
}
}
);
new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), INPUT_EVENT_CHANNEL).setStreamHandler(
new EventChannel.StreamHandler() {
#Override
public void onListen(Object arguments, EventChannel.EventSink events) {
timeLeftInMilliseconds = 30000;
//timer is started when device is connected so tha android knows when to tell flutter button has
//been pressed
m_updateTimer = new CountDownTimer(timeLeftInMilliseconds, 100) {
public void onTick(long millisUntilFinished) {
isRunning = true;
JSONObject retVal = CheckDeviceInputs();
if (retVal != null) {
events.success(retVal.toString());
} else {
events.success(null);
}
}
public void onFinish() {
isRunning = false;
m_updateTimer.start();
}
}.start();
}
#Override
public void onCancel(Object arguments) {
//when event channel is closed we stop the timer then remove the method
if (m_updateTimer != null) {
isRunning = false;
m_updateTimer.cancel();
}
Log.w(TAG, "cancelling listener");
}
}
);
}
private BroadcastReceiver createUSBStateChangeReceiver(EventChannel.EventSink events) {
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//watches if the usb has been plugged in or not
String action = intent.getAction();
if ("android.hardware.usb.action.USB_DEVICE_DETACHED".equals(action)) {
Log.i(TAG, "Detached: ");
Toast.makeText(context, "Device detached",
Toast.LENGTH_LONG).show();
//if device usb plugs out cancel timer
m_connectedDevice = null;
events.success(false);
} else if ("android.hardware.usb.action.USB_DEVICE_ATTACHED".equals(action)) {
Log.i(TAG, "Attached:");
Toast.makeText(context, "Device attached",
Toast.LENGTH_LONG).show();
if (m_updateTimer != null) {
Log.e(TAG, "START THE TIMER: ");
m_updateTimer.start();
}
events.success(true);
}
}
};
}
// INITIALISE
private boolean Initialise() {
try {
m_deviceManager = D2xxManager.getInstance(this);
return m_deviceManager != null;
} catch (D2xxManager.D2xxException exc) {
Log.e(TAG, "Initialise: Failed to get instance");
return false;
}
}
// GET ALL CONNECTED DEVICES
private JSONObject GetDeviceList() {
// first check if the list is empty, then create the list based on what is plugged in
// for now only the first device will be connect
try {
m_iDeviceCount = m_deviceManager.createDeviceInfoList(this);
if (m_iDeviceCount == 0)
return null;
D2xxManager.FtDeviceInfoListNode firstItem = m_deviceManager.getDeviceInfoListDetail(0);
JSONObject returnData = new JSONObject();
try {
//create connected device info object to send to flutter
returnData.put("ID", firstItem.id);
returnData.put("Description", firstItem.description);
returnData.put("BCDDevice", firstItem.bcdDevice);
returnData.put("LineStatus", firstItem.lineStatus);
returnData.put("ModemStatus", firstItem.modemStatus);
returnData.put("Type", firstItem.type);
returnData.put("SerialNumber", firstItem.serialNumber);
return returnData;
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "GetDeviceList: Failed" + e);
return null;
}
} catch (Exception exc) {
Log.e(TAG, "GetDeviceList: Failed" + exc);
return null;
}
}
// CONNECT THE DEVICE
private boolean ConnectToDevice(String strSerialNumber) {
try {
m_connectedDevice = m_deviceManager.openBySerialNumber(this, strSerialNumber);
//m_initialBitMask
if (m_connectedDevice != null && m_connectedDevice.isOpen()) {
//printing the device details
Log.i(TAG, "ConnectToDevice: IsOpen : ");
Log.i(TAG, "ConnectToDevice: IsOpen : " + m_connectedDevice.getDeviceInfo().serialNumber);
Log.i(TAG, "ConnectToDevice: description : " + m_connectedDevice.getDeviceInfo().description);
Log.i(TAG, "ConnectToDevice: serialNumber : " + m_connectedDevice.getDeviceInfo().serialNumber);
Log.i(TAG, "ConnectToDevice: bcdDevice : " + String.valueOf(m_connectedDevice.getDeviceInfo().bcdDevice));
//setting bit mode
m_connectedDevice.setBitMode(Byte.parseByte(m_initialBitMask, 2), D2xxManager.FT_BITMODE_CBUS_BITBANG);
return true;
} else {
m_CONTROLLER_STATUS = CONTROLLER_ENUMS.Closed;
return false;
}
} catch (Exception exc) {
m_CONTROLLER_STATUS = CONTROLLER_ENUMS.Failed;
Log.e(TAG, "ConnectToDevice: Failed" + exc);
Log.i(TAG, "ConnectToDevice: IsNotOpen");
return false;
}
}
// SET OUTPUTS TO DEVICE
private void SetOutputs(int outputNumber, boolean bState) {
//if device is connected you can use this to activate relays
if (m_connectedDevice != null && m_connectedDevice.isOpen()) {
byte lByteMask = m_connectedDevice.getBitMode();
switch (outputNumber) {
//relay 1
case 1: {
if (bState) {
lByteMask |= 1;
} else {
lByteMask &= 0xFE;
}
}
break;
//relay 2
case 2: {
if (bState) {
lByteMask |= 2;
} else {
lByteMask &= 0xFD;
}
}
break;
}
//fire with new values
m_connectedDevice.setBitMode(lByteMask, D2xxManager.FT_BITMODE_CBUS_BITBANG);
}
}
// READ INTERRUPTS - Timer based
private JSONObject CheckDeviceInputs() {
JSONObject returnData = new JSONObject();
try {
if (m_connectedDevice != null && m_connectedDevice.isOpen()) {
byte inputBytes = m_connectedDevice.getBitMode();
boolean input1 = (inputBytes & 0x04) != 0x04;
boolean input2 = (inputBytes & 0x08) != 0x08;
if (input1) {
m_input1State = true;
}
if (input2) {
m_input2State = true;
}
//if input is true global will be set above then below if the local is
//not true anymore it will activate and deactivate the relays
if (!input1 && m_input1State) {
SetOutputs(2, true);
try {
//delay so relay light is seen
Thread.sleep(200);
SetOutputs(2, false);
} catch (InterruptedException ex) {
Log.e(TAG, "Set time out: ", ex);
}
m_input1State = false;
}
if (!input2 && m_input2State) {
SetOutputs(1, true);
try {
//delay so relay light is seen
Thread.sleep(200);
SetOutputs(1, false);
} catch (InterruptedException ex) {
Log.e(TAG, "Set time out: ", ex);
}
m_input2State = false;
}
returnData.put("Input1State", input1);
returnData.put("Input2State", input2);
return returnData;
} else {
return null;
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Failed to get DeviceStatus: Failed" + e);
return null;
}
}
}
On my flutter side I create a banner that listens to the I/O
import 'dart:convert';
import 'package:covidqa/Controllers/DeviceController.dart';
import 'package:covidqa/Models/IRelayDevice.dart';
import 'package:covidqa/Models/Inputs.dart';
import 'package:covidqa/StateHandler/globals.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:provider/provider.dart';
class BannerView extends StatefulWidget {
final Function(Inputs) returningInputs;
final Function(bool) connected;
BannerView(this.returningInputs, this.connected);
#override
BannerViewState createState() {
return BannerViewState();
}
}
class BannerViewState extends State<BannerView> {
DeviceController deviceController = new DeviceController();
EventChannel eventChannel = const EventChannel('event');
EventChannel inputEventChannel = const EventChannel('input');
bool init;
IRelayDevice device;
Inputs inputs;
String error;
bool hasDevice = false;
Globals globals;
bool connected = false;
bool inputState1 = false;
bool inputState2 = false;
bool outputState1 = false;
bool outputState2 = false;
_init() {
deviceController.init().then((value) {
if (value == true) {
getDevice();
}
});
}
Future<void> getDevice() async {
if (!mounted) {
return;
}
deviceController.getDevice().then((data) => setState(() {
device = data;
connectDevice();
}));
}
Future connectDevice() async {
if (!mounted) {
return;
}
if (device != null) {
deviceController.connectDevice(device).then((data) => setState(() {
widget.connected(data);
connected = data;
if (data) {
inputEventChannel
.receiveBroadcastStream()
.listen(_onInput, onError: deviceController.onError);
}
}));
} else {
getDevice();
}
}
#override
void initState() {
super.initState();
_init();
eventChannel
.receiveBroadcastStream()
.listen(_onEvent, onError: deviceController.onError);
}
void _onEvent(Object event) {
if (!mounted) {
widget.connected(false);
device = null;
connected = false;
return;
}
setState(() {
hasDevice = event;
if (!hasDevice) {
device = null;
connected = false;
widget.connected(false);
} else {
connectDevice();
}
});
}
void _onInput(Object event) {
try {
if (!mounted) {
return;
}
if (event == null) {
print("Result is null");
return;
}
Map bodyResult = jsonDecode(event);
inputs = Inputs.fromJson(bodyResult);
widget.returningInputs(inputs);
} on PlatformException catch (e) {
print("exception" + e.toString());
}
}
#override
Widget build(BuildContext context) {
globals = Provider.of<Globals>(context);
return Container(
color: connected ? Colors.green : Colors.red,
height: MediaQuery.of(context).size.height * 0.01,
);
}
}
Again this was long ago and cant remember much and the code is not the most tidy but this is the just of it good luck
I am using magtek card reader audio uDynamo device and i am integrating sdk with my android application. But when i am trying to open device through openDevice() method. Application unfortunately stopped. Why its doing like this ?
This is what i am doing
m_SCRA.setConnectionType(MTConnectionType.Audio);
m_SCRA.setAddress(m_deviceAddress);
m_connectionState = MTConnectionState.Connected;
// here its stopping
m_SCRA.openDevice();
Full source code
public class MainActivity extends AppCompatActivity {
private MTSCRA m_SCRA;
private Button btn;
private TextView txt;
private TextView txt1;
private TextView msg;
private TextView msg2;
private boolean m_startTransactionActionPending;
private boolean m_turnOffLEDPending;
private EditText Edit;
private AudioManager m_audioManager;
private int m_audioVolume;
private String m_deviceAddress;
private MTConnectionType m_connectionType;
private MTConnectionState m_connectionState = MTConnectionState.Disconnected;
private Handler m_scraHandler = new Handler(new SCRAHandlerCallback());
private class SCRAHandlerCallback implements Handler.Callback {
public boolean handleMessage(Message msg)
{
try
{
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert Switch");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
switch (msg.what)
{
case MTSCRAEvent.OnDeviceConnectionStateChanged:
OnDeviceStateChanged((MTConnectionState) msg.obj);
break;
case MTSCRAEvent.OnCardDataStateChanged:
OnCardDataStateChanged((MTCardDataState) msg.obj);
break;
case MTSCRAEvent.OnDataReceived:
OnCardDataReceived((IMTCardData) msg.obj);
break;
case MTSCRAEvent.OnDeviceResponse:
OnDeviceResponse((String) msg.obj);
break;
case MTEMVEvent.OnTransactionStatus:
OnTransactionStatus((byte[]) msg.obj);
break;
case MTEMVEvent.OnDisplayMessageRequest:
OnDisplayMessageRequest((byte[]) msg.obj);
break;
case MTEMVEvent.OnUserSelectionRequest:
OnUserSelectionRequest((byte[]) msg.obj);
break;
case MTEMVEvent.OnARQCReceived:
OnARQCReceived((byte[]) msg.obj);
break;
case MTEMVEvent.OnTransactionResult:
OnTransactionResult((byte[]) msg.obj);
break;
case MTEMVEvent.OnEMVCommandResult:
OnEMVCommandResult((byte[]) msg.obj);
break;
case MTEMVEvent.OnDeviceExtendedResponse:
OnDeviceExtendedResponse((String) msg.obj);
break;
}
}
catch (Exception ex)
{
}
return true;
}
}
public void OnCardDataReceived(IMTCardData cardData)
{
txt.setText(m_SCRA.getCardLast4());
}
protected void OnDeviceStateChanged(MTConnectionState deviceState)
{
setState(deviceState);
updateDisplay();
invalidateOptionsMenu();
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert ondevice state");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
switch (deviceState)
{
case Disconnected:
if (m_connectionType == MTConnectionType.Audio)
{
restoreVolume();
}
break;
case Connected:
if (m_connectionType == MTConnectionType.Audio)
{
setVolumeToMax();
}
clearMessage();
clearMessage2();
break;
case Error:
sendToDisplay("[Device State Error]");
break;
case Connecting:
break;
case Disconnecting:
break;
}
}
protected void OnCardDataStateChanged(MTCardDataState cardDataState)
{
switch (cardDataState)
{
case DataNotReady:
sendToDisplay("[Card Data Not Ready]");
break;
case DataReady:
sendToDisplay("[Card Data Ready]");
break;
case DataError:
sendToDisplay("[Card Data Error]");
break;
}
}
protected void OnDeviceResponse(String data)
{
sendToDisplay("[Device Response]");
sendToDisplay(data);
if (m_startTransactionActionPending)
{
m_startTransactionActionPending = false;
startTransaction();
}
}
protected void OnTransactionStatus(byte[] data)
{
sendToDisplay("[Transaction Status]");
//sendToDisplay(TLVParser.getHexString(data));
}
protected void OnDisplayMessageRequest(byte[] data)
{
sendToDisplay("[Display Message Request]");
//String message = TLVParser.getTextString(data, 0);
//sendToDisplay(message);
//displayMessage(message);
}
protected void OnEMVCommandResult(byte[] data)
{
sendToDisplay("[EMV Command Result]");
//sendToDisplay(TLVParser.getHexString(data));
if (m_turnOffLEDPending)
{
m_turnOffLEDPending = false;
setLED(false);
}
}
protected void OnDeviceExtendedResponse(String data)
{
sendToDisplay("[Device Extended Response]");
sendToDisplay(data);
}
protected void OnUserSelectionRequest(byte[] data)
{
sendToDisplay("[User Selection Request]");
//sendToDisplay(TLVParser.getHexString(data));
//processSelectionRequest(data);
}
protected void OnARQCReceived(byte[] data)
{
sendToDisplay("[ARQC Received]");
/*sendToDisplay(TLVParser.getHexString(data));
List<HashMap<String, String>> parsedTLVList = TLVParser.parseEMVData(data, true, "");
if (parsedTLVList != null)
{
String deviceSNString = TLVParser.getTagValue(parsedTLVList, "DFDF25");
byte[] deviceSN = TLVParser.getByteArrayFromHexString(deviceSNString);
sendToDisplay("SN Bytes=" + deviceSNString);
sendToDisplay("SN String=" + TLVParser.getTextString(deviceSN, 2));
boolean approved = true;
if (mMainMenu != null)
{
approved = mMainMenu.findItem(R.id.menu_emv_approved).isChecked();
}
byte[] response = buildAcquirerResponse(deviceSN, approved);
setAcquirerResponse(response);
}*/
}
protected void OnTransactionResult(byte[] data)
{
sendToDisplay("[Transaction Result]");
//sendToDisplay(TLVParser.getHexString(data));
/*if (data != null)
{
if (data.length > 0)
{
boolean signatureRequired = (data[0] != 0);
int lenBatchData = data.length - 3;
if (lenBatchData > 0)
{
byte[] batchData = new byte[lenBatchData];
System.arraycopy(data, 3, batchData, 0, lenBatchData);
sendToDisplay("(Parsed Batch Data)");
List<HashMap<String, String>> parsedTLVList = TLVParser.parseEMVData(batchData, false, "");
displayParsedTLV(parsedTLVList);
String cidString = TLVParser.getTagValue(parsedTLVList, "9F27");
byte[] cidValue = TLVParser.getByteArrayFromHexString(cidString);
boolean approved = false;
if (cidValue != null)
{
if (cidValue.length > 0)
{
if ((cidValue[0] & (byte) 0x40) != 0)
{
approved = true;
}
}
}
if (approved)
{
if (signatureRequired)
{
displayMessage2("( Signature Required )");
}
else
{
displayMessage2("( No Signature Required )");
}
}
}
}
}
setLED(false);*/
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = ( Button) findViewById(R.id.btn);
txt = (TextView) findViewById(R.id.txt1);
txt1 = (TextView) findViewById(R.id.txt2);
msg = (TextView) findViewById(R.id.msgtext1);
msg2 = (TextView) findViewById(R.id.msgtext2);
Edit = (EditText) findViewById(R.id.editText);
//m_SCRA.setConnectionType(MTConnectionType.Audio);
//if (! m_SCRA.isDeviceConnected())
//{
// m_SCRA.openDevice();
//}
m_audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
m_SCRA = new MTSCRA(this, m_scraHandler);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
m_connectionType = MTConnectionType.Audio;
m_SCRA.setConnectionType(MTConnectionType.Audio);
m_SCRA.setAddress(m_deviceAddress);
m_connectionState = MTConnectionState.Connected;
m_SCRA.openDevice();
}
});
}
private void sendToDisplay(final String data)
{
if (data != null)
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Edit.append(data + "\n");
}
});
}
}
private void setState(MTConnectionState deviceState)
{
m_connectionState = deviceState;
updateDisplay();
invalidateOptionsMenu();
}
private void updateDisplay()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (m_connectionState == MTConnectionState.Connected)
{
updateConnectionState(R.string.connected);
}
else if (m_connectionState == MTConnectionState.Connecting)
{
updateConnectionState(R.string.connecting);
}
else if (m_connectionState == MTConnectionState.Disconnecting)
{
updateConnectionState(R.string.disconnecting);
}
else if (m_connectionState == MTConnectionState.Disconnected)
{
updateConnectionState(R.string.disconnected);
}
}
});
}
private void updateConnectionState(final int resourceId)
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
txt1.setText(resourceId);
}
});
}
private void restoreVolume()
{
setVolume(m_audioVolume);
}
private void setVolumeToMax()
{
saveVolume();
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert volume max");
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
int volume = m_audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
setVolume(volume);
}
private void setVolume(int volume)
{
m_audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
}
private void saveVolume()
{
m_audioVolume = m_audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
private void clearMessage()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText("");
}
});
}
private void clearMessage2()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg2.setText("");
}
});
}
public void startTransaction()
{
if (m_SCRA != null)
{
byte timeLimit = 0x3C;
//byte cardType = 0x02; // Chip Only
byte cardType = 0x03; // MSR + Chip
byte option = 0x00;
byte[] amount = new byte[] {0x00, 0x00, 0x00, 0x00, 0x15, 0x00};
byte transactionType = 0x00; // Purchase
byte[] cashBack = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
byte[] currencyCode = new byte[] { 0x08, 0x40};
byte reportingOption = 0x02; // All Status Changes
clearMessage();
clearMessage2();
int result = m_SCRA.startTransaction(timeLimit, cardType, option, amount, transactionType, cashBack, currencyCode, reportingOption);
sendToDisplay("[Start Transaction] (Result=" + result + ")");
}
}
public void setLED(boolean on)
{
if (m_SCRA != null)
{
if (on)
{
m_SCRA.sendCommandToDevice(MTDeviceConstants.SCRA_DEVICE_COMMAND_STRING_SET_LED_ON);
}
else
{
m_SCRA.sendCommandToDevice(MTDeviceConstants.SCRA_DEVICE_COMMAND_STRING_SET_LED_OFF);
}
}
} }
I was facing the same issue. It turned out that I forgot audio recording runtime permission.
private void checkRecordPermission() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO},
123);
}
}
In android , i create a application based on RFID Card Reader on mobile. While i tapping Card on RFID Reader it generates same value at many times until the card untapped from the reader.
I want to show only one value per tapping card on RFID reader. Here i place my code and Sample snapshot of my application.
Guide me and tell solution for my problem.
public static MediaPlayer mp;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
Button readEnButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
long wait_sec=3000;
byte[] readData; //similar to data.
public static final int readLength = 1024; // changed length from 512
public int iavailable = 0;
char[] readDataToText;
//char readDataToTextSudha;
public boolean bReadThreadGoing = false;
public readThread read_thread;
public static D2xxManager ftD2xx = null;
boolean uart_configured = false;
// Empty Constructor
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readData = new byte[readLength];
readDataToText = new char[readLength];
//readDataToTextSudha = new char;
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
readEnButton = (Button) findViewById(R.id.readEnButton);
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
try {
ftD2xx = D2xxManager.getInstance(this);
} catch (D2xxManager.D2xxException ex) {
ex.printStackTrace();
}
//Opening Coding
if (DevCount <= 0) {
createDeviceList();
} else {
connectFunction();
}
//Configuration coding
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else {
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
readEnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else if (uart_configured == false) {
Toast.makeText(getApplicationContext(), "UART not configure yet...", Toast.LENGTH_SHORT).show();
return;
} else {
EnableRead();
}
}
});
}
public void EnableRead() {
iEnableReadFlag = (iEnableReadFlag + 1) % 2;
if (iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
Toast.makeText(getApplicationContext(),"Read Enabled",Toast.LENGTH_LONG).show();
} else {
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
Toast.makeText(getApplicationContext(),"Read Disabled",Toast.LENGTH_LONG).show();
}
}
public void createDeviceList() {
int tempDevCount = ftD2xx.createDeviceInfoList(getApplicationContext());
if (tempDevCount > 0) {
if (DevCount != tempDevCount) {
DevCount = tempDevCount;
updatePortNumberSelector();
}
} else {
DevCount = -1;
currentIndex = -1;
}
};
public void disconnectFunction() {
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ftDev != null) {
synchronized (ftDev) {
if (true == ftDev.isOpen()) {
ftDev.close();
}
}
}
}
public void connectFunction() {
int tmpProtNumber = openIndex + 1;
if (currentIndex != openIndex) {
if (null == ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
}
}
uart_configured = false;
} else {
Toast.makeText(getApplicationContext(), "Device port " + tmpProtNumber + " is already opened", Toast.LENGTH_LONG).show();
return;
}
if (ftDev == null) {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen()) {
currentIndex = openIndex;
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if (false == bReadThreadGoing) {
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
} else {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
}
}
public void updatePortNumberSelector() {
if (DevCount == 2) {
Toast.makeText(getApplicationContext(), "2 port device attached", Toast.LENGTH_SHORT).show();
} else if (DevCount == 4) {
Toast.makeText(getApplicationContext(), "4 port device attached", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "1 port device attached", Toast.LENGTH_SHORT).show();
}
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl) {
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
uart_configured = true;
Toast.makeText(getApplicationContext(), "Config done", Toast.LENGTH_SHORT).show();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (iavailable > 0) {
mp = MediaPlayer.create(MainActivity.this, R.raw.beep);
mp.start();
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread {
Handler mHandler;
readThread(Handler h) {
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run() {
int i;
while (true == bReadThreadGoing) {
try {
Thread.sleep(1000); //changed
} catch (InterruptedException e) {
}
synchronized (ftDev) {
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if (iavailable > readLength) {
iavailable = readLength;
}
ftDev.read(readData, iavailable,wait_sec);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if (DevCount > 0) {
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
My problem would snapped here
Getting Value continuously from Reader
I want this type of value when i tap the card
If i tap some other cards, old card value replaces from the new one.
Guide me.
Thanks in Advance
I got the answer by using of Threads. When the card tapping it get some values after sleep of one or two seconds only the next value have to get from the reader.
public void run() {
int i;
while (true == bReadThreadGoing) { // Means Make sure , getting value from Reader
try {
Thread.sleep(1000); // Wait for a second to get another value.
clearText(); //clear the old value and get new value.
} catch (InterruptedException e) {
}
And clearing the edittext by using this command.
public void clearText() {
runOnUiThread(new Runnable() {
public void run() {
readText.setText("");
}
});
}
I am sending some data to an android application over UDP. Therefore i created the following UDPReceiver-Class:
package com.example.urowatch;
import java.net.*;
import java.nio.ByteBuffer;
import java.io.*;
public class UDPReceiver extends Thread
{
private DatagramSocket m_Socket;
private int m_BufferSize;
private Boolean m_End = false;
private int m_TotalLength;
private int m_Received;
private byte[] m_Buffer;
private byte[] m_Result;
private Boolean m_IsNewResult = false;
private float m_Progress;
private int m_ImageCount = 0;
private int m_FrameErrors = 0;
public UDPReceiver(String name, int port, int bufferSize) throws IOException
{
super(name);
m_Socket = new DatagramSocket(port);
m_BufferSize = bufferSize;
m_Socket.setBroadcast(true);
m_Socket.setReceiveBufferSize(m_BufferSize);
}
public void run()
{
while(!m_End)
{
try
{
byte[] buf = new byte[m_BufferSize];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
m_Socket.receive(packet);
ProcessData(packet);
}
catch (IOException e)
{
if (!m_Socket.isClosed())
e.printStackTrace();
}
}
}
private void ProcessData(DatagramPacket packet)
{
if (packet.getLength() == 4)
{
ByteBuffer bb = ByteBuffer.wrap(packet.getData());
m_TotalLength = bb.getInt();
if (m_Received != 0)
m_FrameErrors++;
m_Received = 0;
m_Buffer = new byte[m_TotalLength];
}
else if (m_Buffer != null && m_Received != m_TotalLength)
{
int length = packet.getLength();
System.arraycopy(packet.getData(), 0, m_Buffer, m_Received, length);
m_Received += length;
m_Progress = 100 * (float)m_Received/(float)m_TotalLength;
if (m_Received == m_TotalLength)
{
m_Result = new byte[m_TotalLength];
System.arraycopy(m_Buffer, 0, m_Result, 0, m_TotalLength);
m_IsNewResult = true;
m_ImageCount++;
m_Received = 0;
}
}
}
public Boolean IsNewResult()
{
return m_IsNewResult;
}
public byte[] GetResult()
{
m_IsNewResult = false;
return m_Result;
}
public float GetProgress()
{
return m_Progress;
}
public float GetRatio()
{
return 100 * (float)m_ImageCount / (float)m_FrameErrors;
}
public void stopServer()
{
m_End = true;
if (m_Socket != null)
m_Socket.close();
}
}
And i am using this class like this:
package com.example.urowatch;
import java.io.IOException;
import java.text.DecimalFormat;
import android.os.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Build;
public class LiveActivity extends Activity {
private static ImageView m_ImageView1;
private static TextView m_TextView1;
private static DecimalFormat m_DF;
private static Context m_Context;
private UDPReceiver m_Receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
// Show the Up button in the action bar.
setupActionBar();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
m_ImageView1 = (ImageView)findViewById(R.id.imageView1);
m_TextView1 = (TextView)findViewById(R.id.textView1);
m_Context = this;
m_DF = new DecimalFormat("00.00");
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.live, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private static Handler MyHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == 100)
{
float[] infos = (float[])msg.obj;
m_TextView1.setText("Empfange Bild: " + m_DF.format(infos[0]) + "% (FrameErrors: " + m_DF.format(infos[1]) + "%)");
}
else if (msg.what == 101)
{
byte[] b = (byte[])msg.obj;
m_TextView1.setText("Empfange Bild: 100,00%");
m_ImageView1.setImageBitmap(BitmapFactory.decodeByteArray(b, 0, b.length));
}
else if (msg.what == 102)
{
AlertDialog.Builder b = new AlertDialog.Builder(m_Context);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + (Exception)msg.obj);
b.setNeutralButton("OK", null);
b.show();
}
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
if (m_Receiver != null)
m_Receiver.stopServer();
finish();
}
#Override
public void onPause()
{
m_Receiver.stopServer();
super.onPause();
}
#Override
protected void onResume()
{
try {
m_Receiver = new UDPReceiver("UDPReceiver", 5678, 1024);
m_Receiver.start();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Fehler");
b.setMessage("Es ist folgende Exception aufgetreten:\n" + e1);
b.setNeutralButton("OK", null);
b.show();
}
// Thread thread = new Thread()
// {
// #Override
// public void run()
// {
// while(true)
// {
// try {
//sleep(250);
Toast.makeText(getBaseContext(), "Runing Thread", Toast.LENGTH_SHORT).show();
Update();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// MyHandler.sendMessage(MyHandler.obtainMessage(102, e));
// }
// }
// }
// };
// thread.start();
super.onResume();
}
public void buttonClick(View v)
{
Update();
}
private void Update()
{
if (m_Receiver != null)
{
if (m_Receiver.IsNewResult())
{
byte[] b = m_Receiver.GetResult();
MyHandler.sendMessage(MyHandler.obtainMessage(101, b));
}
else
{
float[] infos = new float[2];
infos[0] = m_Receiver.GetProgress();
infos[1] = m_Receiver.GetRatio();
MyHandler.sendMessage(MyHandler.obtainMessage(100, infos));
}
}
}
}
As you see i want to check the status of the UDPReceiver-Object (Is there a new complete byte[] ready?) by a thread. To update the GUI, the thread has to send a Message to MyHandler which will update the GUI.
In the moment i have to to click a button to raise the buttonClick-Event. Later on i want to do this in the commented thread-structure.
Now, here's my problem:
I start the Activity and everything works fine. Then i am starting to send ONE packet manually with my UDP-Sender (which works, i validated it with a C#-UDP-Receiver). The first packet get received fine. Then i send the second packet which get received, too. But from now on, my breakpoint at m_Socket.receive(packet); wont get hit anymore!
I have NO idea what this behaviour causes and it is very important for me to make this application work.
Please, if you have ANY Idea or just a guess, please let me know.
I have closely followed this tutorial: http://assets.en.oreilly.com/1/event/68/Building%20Android%20Accessories%20using%20the%20Open%20Accessory%20Development%20Kit%20and%20Arduino%20Presentation%201.pdf
However, I have made a few modifications so that I send ASCII values each time my text is updated. I still am unable to connect my Android devices (yes, I have multiple, from versions 2.2.3 to 2.2.7). I keep receiving the error in the onscreen Log that the Outputstreams are null. Any help would be greatly appreciated!
OpenAccessoryTest.java
package org.simonmonk.duinodroid;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;
public class OpenAccessoryTest extends Activity implements Runnable {
private EditText mByteField;
private EditText mResponseField;
private Button mSendButton;
private static final String ACTION_USB_PERMISSION = "com.google.android.DemoKit.action.USB_PERMISSION";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
private boolean mPermissionRequestPending;
private UsbAccessory mAccessory;
private ParcelFileDescriptor mFileDescriptor;
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mByteField = (EditText) findViewById(R.id.streamingTextView1);
mResponseField = (EditText) findViewById(R.id.arduinoresponse);
mSendButton = (Button) findViewById(R.id.sendButton);
// String valueStr = mByteField.getText().toString();
mSendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToArduino();
}
});
setupAccessory();
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
log("Resuming");
super.onResume();
if (mInputStream != null && mOutputStream != null) {
log("Resuming: streams were not null");
return;
}
log("Resuming: streams were null");
UsbAccessory[] accessories = mUsbManager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (mUsbManager.hasPermission(accessory)) {
openAccessory(accessory);
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
mUsbManager.requestPermission(accessory,
mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
log("onResume:mAccessory is null");
}
}
#Override
public void onPause() {
log("Pausing");
super.onPause();
}
#Override
public void onDestroy() {
log("Destroying");
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
ValueMsg t = (ValueMsg) msg.obj;
log("Arduino sent: " + t.getFlag() + " " + t.getReading());
}
};
private void log(String string) {
String contents = mResponseField.getText().toString();
mResponseField.setText(contents + "\n" + string);
}
private void setupAccessory() {
log("In setupAccessory");
mUsbManager = UsbManager.getInstance(this);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver, filter);
if (getLastNonConfigurationInstance() != null) {
mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
openAccessory(mAccessory);
}
}
private void openAccessory(UsbAccessory accessory) {
log("In openAccessory");
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null, this, "OpenAccessoryTest");
thread.start();
alert("openAccessory: Accessory openned");
log("Attached");
} else {
log("openAccessory: accessory open failed");
}
}
private void closeAccessory() {
log("In closeAccessory");
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
private int composeInt(byte hi, byte lo) {
int val = hi & 0xff;
val *= 256;
val += lo & 0xff;
return val;
}
#Override
public void run() {
int ret = 0;
byte[] buffer = new byte[16384];
int i;
while (true) { // keep reading messages forever. There are prob lots of
// messages in the buffer, each 4 bytes
try {
ret = mInputStream.read(buffer);
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
int len = ret - i;
if (len >= 2) {
Message m = Message.obtain(mHandler);
int value = composeInt(buffer[i], buffer[i + 1]);
m.obj = new ValueMsg('a', value);
mHandler.sendMessage(m);
}
i += 2;
}
}
}
public void sendMessageToArduino() {
String valueStr = mByteField.getText().toString();
try {
for (int x = 0; x < valueStr.length(); x++) {
sendCommand((byte) valueStr.charAt(x));
log("Sending to Arduino: " + (byte) valueStr.charAt(x));
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
alert("The Byte should be a number between 0 and 255");
}
}
public void sendCommand(byte value) {
log("Sent: " + value);
byte[] buffer = new byte[1];
buffer[0] = value;
if (mOutputStream != null) {
try {
mOutputStream.write(buffer);
} catch (IOException e) {
log("Send failed: " + e.getMessage());
}
} else {
log("Send failed: mOutStream was null");
}
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
openAccessory(accessory);
} else {
log("USB permission denied");
}
}
} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (accessory != null && accessory.equals(mAccessory)) {
log("Detached");
closeAccessory();
}
}
}
};
public void alert(String message) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
}`
StreamingTextView.java
package org.simonmonk.duinodroid;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
public class StreamingTextView extends EditText {
public StreamingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public StreamingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StreamingTextView(Context context) {
super(context);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
((OpenAccessoryTest) super.getContext()).sendCommand(toAscii(event));
return super.onKeyDown(keyCode, event);
}
private byte toAscii(KeyEvent event) {
byte ch = (byte) event.getUnicodeChar();
if (ch == 0) {
switch(event.getKeyCode()){
case KeyEvent.KEYCODE_DEL:
ch = 8;
break;
case KeyEvent.KEYCODE_ENTER:
ch = 10;
break;
}
}
return ch;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Byte 0 (decimal)" />
<org.simonmonk.duinodroid.StreamingTextView
android:id="#+id/streamingTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StreamingTextView" >
<requestFocus />
</org.simonmonk.duinodroid.StreamingTextView>
<Button
android:id="#+id/sendButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send to Arduino" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Log" />
<EditText
android:id="#+id/arduinoresponse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:lines="10" />
</LinearLayout>
android version must be > to 2.2 . That start working with Google api version 2.3.4 I think