Waiting inside loop for the method to finish executing - java

I have a For loop in which I call a method to upload images to the server , the problem that i am facing that at a certain limit the server will force stop the opened socket so i have to upload every image at once
for (int i = 0; i < paths.size(); i++) {
transferData(paths.get(i), i);
}
and the transferData Function I am using the transfer Utility aws s3 function
TransferUtility transferUtility =
TransferUtility.builder()
.context(this)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.s3Client(amazonS3Client)
.defaultBucket("name")
.build();
TransferObserver uploadObserver = transferUtility.upload("name", name, new File(path), CannedAccessControlList.PublicRead);
uploadObserver.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
Log.d(TAG, "onStateChanged: " + id + ", " + state);
if (TransferState.COMPLETED == state) {
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100;
int percentage = (int) percentDonef;
Log.d(TAG, "onProgressChanged: " + percentage);
}
#Override
public void onError(int id, Exception ex) {
Log.e(TAG, "Error during upload: " + id, ex);
try {
showToast(ex.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
ex.printStackTrace();
}
});
How to wait for the method to finish execution then continue the loop

to wait loop use this code :
CountDownLatch latch=new CountDownLatch(1);
for (int i = 0; i < paths.size(); i++) {
transferData(paths.get(i), i);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
and put this at the end of your method that finished upload image or failed
latch.countDown();
when your method rich to latch.countDown(); your loop will be continue
notice that you must put your loop in another thread except main thread

Related

Android Things -> Flickering while controlling 8x8 LED matrix by 74hc595 multiplexing

Hi I am stuck while i was trying to control 8x8 led matrix by cascading two 74hc595 shift registers. I had build the circuit and the program, which I am including here. It's actually giving me the right output. But the major problem is visible flickering. Can somebody guide me what can i do to remove the flickering?
public class MainActivity extends Activity {
private static final String SR_SRCLK_PIN = "BCM27"; //clock pins shcp
private static final String SR_RCLK_PIN = "BCM18"; //latch pin stcp
private static final String SR_SDI_PIN = "BCM17"; //data pin
private static final String TAG = "MAT21";
private Gpio mRCLK;
private Gpio mSRCLK;
private Gpio mSDI;
private int charSeq=0;
int data[]=
{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //NULL
0x00,0x00,0x3C,0x42,0x42,0x3C,0x00,0x00, //0
0x00,0x00,0x00,0x44,0x7E,0x40,0x00,0x00, //1
0x00,0x00,0x44,0x62,0x52,0x4C,0x00,0x00, //2
0x00,0x00,0x78,0x14,0x12,0x14,0x78,0x00, //A
0x00,0x00,0x60,0x90,0x90,0xFE,0x00,0x00, //d
0x00,0x00,0x1C,0x2A,0x2A,0x2A,0x24,0x00, //e
0x00,0x00,0x7E,0x12,0x12,0x0C,0x00,0x00, //p
0x00,0x00,0x08,0x7E,0x88,0x40,0x00,0x00, //t
0x3C,0x42,0x95,0xB1,0xB1,0x95,0x42,0x3C, //:)
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PeripheralManagerService pms = new PeripheralManagerService();
try {
mRCLK = pms.openGpio(SR_RCLK_PIN);
mRCLK.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mSRCLK = pms.openGpio(SR_SRCLK_PIN);
mSRCLK.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
mSDI = pms.openGpio(SR_SDI_PIN);
mSDI.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
try {
thread.start();
while (true){
Thread.sleep(2000);
charSeq++;
if(charSeq==10){
charSeq=0;
}
}
} catch (Exception sd) {
}
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
for (int rowNum = 0; rowNum < 8; rowNum++) {
mRCLK.setValue(false);
shiftOut(data[(charSeq * 8) + rowNum],rowNum);
mRCLK.setValue(true);
}
}
}catch (Exception ex){
}
}
});
#Override
protected void onDestroy() {
super.onDestroy();
// Clean all resources
if (mSDI != null) {
try {
mSDI.setValue(false);
mSDI.close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
if (mRCLK != null) {
try {
mRCLK.setValue(false);
mRCLK.close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
if (mSRCLK != null) {
try {
mSRCLK.setValue(false);
mSRCLK.close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
}
void shiftOut(int data, int rowNum) {
try {
for (int i = 7; i >= 0; i--) {
mSRCLK.setValue(false);
mSDI.setValue((((data >> i) & 1) == 0));
mSRCLK.setValue(true);
}
for (int i = 0; i <8; i++) {
mSRCLK.setValue(false);
mSDI.setValue(i==rowNum?true:false);
mSRCLK.setValue(true);
}
} catch (Exception sd) {
}
}
}
Schemetic Diagram
It's not entirely clear from your question what clock frequency you need to achieve to drive your matrix display properly, but regardless it's unlikely you will be able to get there bit-banging the GPIO in this fashion. The flickering you see is probably because the I/O is not toggling fast enough in your code.
I would recommend moving to an external hardware controller for your display (something like the MAX7219, for example) that you can control over a serial port like I2C or SPI.

Issues using android studio to get time of travel between two points

For the last week, I have been using Android Studio to write code that achieves the following goals:
Wait for the user to be within a certain distance of the start waypoint
Once at start waypoint, begin a timer that logs gps data and current time
Stops timer when the end waypoint is crossed
At the moment, I have the start and end waypoints hard coded but I seem to run into an error that I have been trying to trace with the step through function on my IDE but can't seem to find it. Below is the code I have been using:
void StartTimer (View view){
//Location l = null;
boolean hasLoc = false; //are we at the start?
float speed = 0;
float topSpeed = 0;
while(hasLoc == false && cancel == false){
float d = l.distanceTo(t);
if(d < 2.0)
hasLoc = true;
//if(!l.equals(lm.getLastKnownLocation("")))
String msg = "Latitude: " + l.getLatitude() + "\nLongitude: "+ l.getLongitude();
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
hasLoc = false;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
buzzer();
}
}, 10000);
while(l.distanceTo(tf) > 2.0 && cancel == false){
float cSpeed = l.getSpeed();
if(cSpeed>topSpeed)
topSpeed = cSpeed;
String msg = "Current Speed: "+cSpeed+"Top Speed: "+topSpeed;
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
cancel = false;
}
When I run the code, the phone I test it one will run it but it won't respond, which leads me to believe there is an unsatisfied loop that I have not considered.
Any suggestions would be helpful, thank you in advance for advice!
Your while loops are clogging up the CPU's execution which is what is causing it to not respond. Instead you should place your code inside a thread and call Thread.sleep(1000); inside the thread, this way the the while loop is paused for 1 second after every execution of the code inside it.
Something like this:
new Thread(new Runnable() {
#Override
public void run() {
while (hasLoc == false && cancel == false) {
float d = l.distanceTo(t);
if (d < 2.0)
hasLoc = true;
String msg = "Latitude: " + l.getLatitude() + "\nLongitude: " + l.getLongitude();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
hasLoc = false;
new Handler().postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
buzzer();
}
}, 10000);
while (l.distanceTo(tf) > 2.0 && cancel == false) {
float cSpeed = l.getSpeed();
if (cSpeed > topSpeed)
topSpeed = cSpeed;
String msg = "Current Speed: " + cSpeed + "Top Speed: " + topSpeed;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
cancel = false;
}
}).start();

Function not getting called right

I'm trying to call my updateDisplay method through a for loop to set the text for the corresponding index, but in the output only the 5th index code is getting run.
Here is the for loop that I'm calling in my fragment's onCreateView();
private int mIndexofDays;
for(int i =1; i < 6; i++) {
DateTime nextday = mDateTime.plusDays(i);
long time = nextday.getMillis() / 1000;
getForecast(mLattitude, mLongitude, time);
mIndexofDays = i;
}
Here is the getForecast() method:
private void getForecast(double latitude, double longitude, long time)
{
String apiKey = getResources().getString(R.string.api_key);
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude + "," + time;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mWeather = getCurrentDetails(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Running....");
updateDisplay();
}
});
} else {
Log.d(TAG, "Response not successful");
}
} catch (IOException e) {
Log.e(TAG, " IOException caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "JSON exception caught: ", e);
}
}
});
}
And here is the updateDisplay() method:
private void updateDisplay() {
if(mIndexofDays == 1) {
mDayOfWeek1.setText(mDateTime.plusDays(1).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage1.setImageDrawable(drawable);
mHighTemp1.setText(mWeather.getTemperatureMax() + "");
mLowTemp1.setText(mWeather.getTemperatureMin() + "");
}
if(mIndexofDays == 2) {
mDayOfWeek2.setText(mDateTime.plusDays(2).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage2.setImageDrawable(drawable);
mHighTemp2.setText(mWeather.getTemperatureMax() + "");
}
if(mIndexofDays == 3) {
mDayOfWeek3.setText(mDateTime.plusDays(3).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage3.setImageDrawable(drawable);
mHighTemp3.setText(mWeather.getTemperatureMax() + "");
}
if(mIndexofDays == 4) {
mDayOfWeek4.setText(mDateTime.plusDays(4).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage4.setImageDrawable(drawable);
mHighTemp4.setText(mWeather.getTemperatureMax() + "");
}
if(mIndexofDays == 5) {
mDayOfWeek5.setText(mDateTime.plusDays(5).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage5.setImageDrawable(drawable);
mHighTemp5.setText(mWeather.getTemperatureMax() + "");
}
else
{
Log.d(TAG, "Index to high!!!");
}
}
From the logs I can see that "Running" is getting called but updateDisplay never updates for 1-4 indexes only for the 5th index.
I am a very novice programmer, so please tell me on what is wrong with my style and better methods to do what I'm trying to do.
modify updateDisplay and pass a copy of mIndexofDays as a parameter, and this should work. I can provide the actual implementation code but I encourage you to try it first yourself.
hope this helps :)
change your for loop like this
for(int i =1; i < 6; i++) {
mIndexofDays = i;
DateTime nextday = mDateTime.plusDays(i);
long time = nextday.getMillis() / 1000;
getForecast(mLattitude, mLongitude, time, mIndexofDays); // new parameter: mIndexofDays
}
catch the parameter mIndexofDays in getForecast method and pass it through updateDisplay method. Next, use the value of mIndexofDays to compare in your if...else statements. You can use Log method or time delay method to check if it's actually working or not.
Well, the issue is that your updateDisplay() is called only when you receive response in onResponse(). Now, by the time this happens your loop has already ended and the value of mIndexofDays is 5. To fix the issue one of the things you can do is to pass the value of mIndexofDays to your getForecast() method:
private void getForecast(double latitude, double longitude, long time, int indexOfDays) {
...
updateDisplay(numberOfDays);
...
}
You also need to change your updateDisplay() method:
private void updateDisplay(int indexOfDays) {
...
}
Also, get rid of the mIndexOfDays instance variable since you [probably] don't need it anywhere.

Android UI from other thread

I'm creating an application that gets the get the homestatus from a server in json but this happens on another thread. this isn't a problem when i try to set most Items on the ui because i can set them in a static void. but when i try to create a new switch and space i can't call 'this' to create a new.
code for getting the homestatus:
public void loadHomeStatus()
{
if(socket != null) {`enter code here`
if (socket.isConnected()) {
Log.d("BtnUpdate","already connected");
return;
}
}
swAlarm = (Switch) findViewById(R.id.swAlarmState);
tvTemperature = (TextView) findViewById(R.id.tvTemprateur);
tvHumidity = (TextView) findViewById(R.id.tvHumidity);
llDevices = (LinearLayout) findViewById(R.id.llDevices);
new Thread() {
public void run() {
try
{
busyConnecting = true;
Log.d("loadHomeStatus","trying to connect to: " + host + ":" + port);
socket = new Socket(host, port);
uiConnected();
Log.d("loadHomeStatus","Connected");
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
DataInputStream is = new DataInputStream(socket.getInputStream());
os.writeBytes(password);
Log.d("Connect", "send: " + password);
while (socket.isConnected()) {
byte[] data = new byte[500];
int count = is.read(data);
String recieved = new String(data).trim();
Log.d("loadHomeStatus","recieved " + recieved );
if(recieved.toLowerCase() == "failed")
{
Log.d("loadHomeStatus","failed to log in");
}
else
{
try
{
homeStatus = new Gson().fromJson(recieved, HomeStatus.class);
uiLoadStatus();
} catch (Exception e)
{
Log.d("Error", e.toString());
}
}
}//end of while loop
Log.w("loadHomeStatus", "end connection thread ");
//ends thread
Thread.currentThread().interrupt();
return;
}
catch (UnknownHostException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
catch (IOException e)
{
e.printStackTrace();
Log.w("loadHomeStatus", "no Failed to connect: " + host + "-" + 8001);
}
Log.w("loadHomeStatus","Connection ended");
socket = null;
busyConnecting = false;
uiDisconnected();
}
}.start();
}`
Code for setting ui
public static void uiLoadStatus()
{
if (homeStatus != null)
{
try {
tvTemperature.post(new Runnable()
{
public void run()
{
//Log.d("uiLoadStatus to string",homeStatus.toString());
tvTemperature.setText(homeStatus.temperature + "°C");
tvHumidity.setText(homeStatus.humidity + "%");
}
});
}
catch(Exception e)
{
Log.d("uiLoadStatus status fragment", e.toString());
}
try {
swAlarm.post(new Runnable()
{
public void run() {
swAlarm.setChecked(homeStatus.alarmState);
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
try {
llDevices.post(new Runnable()
{
public void run() {
uiLoadDevices(); //this gives and error because it's not static
}
});
}
catch (Exception e)
{
Log.d("uiLoadStatus alarm fragment", e.toString());
}
}
public void uiLoadDevices()
{
for (int i = 0; i < homeStatus.lstDevices.size(); i++) {
String deviceAdd = homeStatus.lstDevices.get(i);
Space mySpace = new Space(this);
Switch mySwitch = new Switch(this);
mySpace.setMinimumHeight(50);
mySwitch.setText(homeStatus.getName(deviceAdd));
mySwitch.setChecked(homeStatus.getState(deviceAdd));
mySwitch.setTextSize(18);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.LEFT;
llDevices.addView(mySpace, lp);
llDevices.addView(mySwitch, lp);
}
}
You should use AsyncTask and put the network interaction part in the doInBackground() method. To update the UI components, implement those logics in the onPostExecute() method
uiLoadStatus is a static method (not sure why or if it has to be without looking at all of your code) and therefore you cannot call non-static methods from within it, such as uiLoadDevices
I would advise taking a look at your code and update your uiLoadStatus to not be static if at all possible. Abusing static can lead to sloppy code.

Android "Only the original thread that created a view hierarchy can touch its views." error in Fragment [duplicate]

This question already has answers here:
Android "Only the original thread that created a view hierarchy can touch its views."
(33 answers)
Closed 5 years ago.
I've got this simple timer in my app which is runs in every 3 seconds.
It works perfectly if it's not in a fragment class.
But here in fragment I always got the error: Only the original thread that created a view hierarchy can touch its views.
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
String timeStamp = new SimpleDateFormat(
"yyyy.MM.dd HH:mm:ss").format(Calendar
.getInstance().getTime());
System.out.println("TimeStamp: " + timeStamp);
// Read And Write Register Sample
port = Integer.parseInt(gConstants.port);
String refe = "0";// HEX Address
ref = Integer.parseInt(refe, 16);// Hex to int
count = 10; // the number Address to read
SlaveAddr = 1;
astr = gConstants.ip; // Modbus Device
InetAddress addr;
try {
addr = InetAddress.getByName(astr);
con = new TCPMasterConnection(addr); // the
// connection
} catch (UnknownHostException e2) {
e2.printStackTrace();
}
// 1.Prepare the request
/************************************/
Rreq = new ReadMultipleRegistersRequest(ref, count);
Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); // set Slave Address
Rres.setUnitID(SlaveAddr); // set Slave Address
// 2. Open the connection
con.setPort(port);
try {
con.connect();
System.out.println("Kapcsolódva!");
} catch (Exception e1) {
e1.printStackTrace();
}
con.setTimeout(2500);
// 3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
try {
trans.execute();
} catch (ModbusIOException e) {
e.printStackTrace();
} catch (ModbusSlaveException e) {
e.printStackTrace();
} catch (ModbusException e) {
e.printStackTrace();
}
/* Print Response */
Rres = (ReadMultipleRegistersResponse) trans
.getResponse();
System.out.println("Connected to= " + astr
+ con.isConnected() + " / Start Register "
+ Integer.toHexString(ref));
count = 10;
for (int k = 0; k < count; k++) {
System.out.println("The value READ: "
+ Rres.getRegisterValue(k) + " "
+ Rres.getUnitID());
ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";
// Adatbázisba írás
ContentValues modbusData = new ContentValues();
modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
// +
// érték
modbusData.put("timeStamp", timeStamp);
try {
gConstants.db.beginTransaction();
gConstants.db
.insert("Modbus", null, modbusData);
gConstants.db.setTransactionSuccessful();
} finally {
gConstants.db.endTransaction();
}
}
kiir.setText(ki_adat);
ki_adat = "";
}//run vége
}, 0, 3000);
This error occurs when trying to access UI elements from any thread that is not the UI thread.
To access/modify elements from a non-UI-thread, use runOnUIThread.
However as you need to change a UI element from within a fragment, runOnUIThread should be invoked onto the fragments owning activity. You can do this through getActivity().runOnUIThread().
EG:
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here...
// When you need to modify a UI element, do so on the UI thread.
// 'getActivity()' is required as this is being ran from a Fragment.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
myTextBox.setText("my text");
}
});
}
}, 0, 3000); // End of your timer code.
For further information see the following documentation:
Android Fragments (specifically, getActivity()).
TimerTask.
Invoking a Runnable on the UI thread.
you need to use the runOnUIThread() function I have an example somwhere that I will post when I find it.
you need to give your timer an instance of MainActivity alternatively see this question I asked Android image timing issues with what sounds like a similar thing to what you were trying to do
public static void updateText(Activity act, resID)
{
loadingText = (TextView) activity.findViewById(R.id.loadingScreenTextView);
act.runOnUiThread(new Runnable()
{
public void run()
{
loadingText.setText(resID);
}
});
}
You are doing UI operation from another thread. I suggest you to use following.
runOnUiThread(new Runnable() {
#Override
public void run() {
kiir.setText(ki_adat);
}
2 solutions :
Use the View.post(Runnable) method
Use the Activity.post(Runnable) method
And put the myTextView.setText(str) call in the run() method of the Runnable object.
Try this:
textView.post(new Runnable() {
#Override
public void run() {
textView.setText("Hello!"); }
});
TRY THIS: put this part of code somewhere but not in activity onCreate method
public void LoadTable(final String u, final String k)
{
// runOnUiThread need to be used or error will appear
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
//method which was problematic and was casing a problem
createTable(u, k);
}
});
} catch (Exception exception) {
createAndShowDialog(exception, "Error");
}
return null;
}
}.execute();
}
Try this
new CountDownTimer(365*24*60*60, 3000) {
public void onTick(long millisUntilFinished) {
String timeStamp = new SimpleDateFormat(
"yyyy.MM.dd HH:mm:ss").format(Calendar
.getInstance().getTime());
System.out.println("TimeStamp: " + timeStamp);
// Read And Write Register Sample
port = Integer.parseInt(gConstants.port);
String refe = "0";// HEX Address
ref = Integer.parseInt(refe, 16);// Hex to int
count = 10; // the number Address to read
SlaveAddr = 1;
astr = gConstants.ip; // Modbus Device
InetAddress addr;
try {
addr = InetAddress.getByName(astr);
con = new TCPMasterConnection(addr); // the
// connection
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// 1.Prepare the request
/************************************/
Rreq = new ReadMultipleRegistersRequest(ref, count);
Rres = new ReadMultipleRegistersResponse();
Rreq.setUnitID(SlaveAddr); // set Slave Address
Rres.setUnitID(SlaveAddr); // set Slave Address
// 2. Open the connection
con.setPort(port);
try {
con.connect();
System.out.println("Kapcsolódva!");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
con.setTimeout(2500);
// 3. Start Transaction
trans = new ModbusTCPTransaction(con);
trans.setRetries(5);
trans.setReconnecting(true);
trans.setRequest(Rreq);
try {
trans.execute();
} catch (ModbusIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ModbusSlaveException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ModbusException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Print Response */
Rres = (ReadMultipleRegistersResponse) trans
.getResponse();
System.out.println("Connected to= " + astr
+ con.isConnected() + " / Start Register "
+ Integer.toHexString(ref));
count = 10;
for (int k = 0; k < count; k++) {
System.out.println("The value READ: "
+ Rres.getRegisterValue(k) + " "
+ Rres.getUnitID());
ki_adat = ki_adat + Rres.getRegisterValue(k) + "\n";
// Adatbázisba írás
ContentValues modbusData = new ContentValues();
modbusData.put("Value", Rres.getRegisterValue(k)); // tábla
// +
// érték
modbusData.put("timeStamp", timeStamp);
try {
gConstants.db.beginTransaction();
gConstants.db
.insert("Modbus", null, modbusData);
gConstants.db.setTransactionSuccessful();
} finally {
gConstants.db.endTransaction();
}
}
kiir.setText(ki_adat);
ki_adat = "";
}
public void onFinish() {}
}.start();

Categories

Resources