How to update server resource using WebDAV - android

I am writing an Android application in which I am using Jackrabbit WebDAV Library.
With help of this WebDAV library, I can download and upload files from and to server. This works as expected.
Now I want to get a byte array from file with specific offset from the server. For this what I have tried is:
byte buffer[] = null;
Log.d(TAG, "downloadBytes '" + fileUri + "' byteOffset '" + byteOffset + "' byteOffset '" + byteCount);
HttpClient httpClient = new HttpClient();
GetMethod httpMethod = new GetMethod(fileUri);
httpMethod.addRequestHeader("Accept-Ranges", "bytes");
int total = byteOffset + byteCount;
String bytesMessage = "bytes=" + byteOffset + "-" + total;
Log.d(TAG, "bytesMessage " + bytesMessage);
httpMethod.addRequestHeader("Range", bytesMessage);
httpMethod.addRequestHeader("Cache-Control", "no-cache, no-store");
httpClient.executeMethod(httpMethod);
This works as expected.
Similarly, I want to update file on server with byte array by specifying offset, but this doesn't appear to work; the server returns a 400 Bad Request error code.
byte buffer[] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x50};
Log.d(TAG, "downloadBytes '" + fileUri + "' byteOffset '" + byteOffset + "' byteCount '" + byteCount);
HttpClient httpClient = new HttpClient();
PutMethod httpMethod = new PutMethod(fileUri);
httpMethod.addRequestHeader("Accept-Ranges", "bytes");
int total = byteOffset + byteCount;
String bytesMessage = "bytes=" + byteOffset + "-" + total;
Log.d(TAG, "bytesMessage " + bytesMessage);
httpMethod.addRequestHeader("Range", bytesMessage);
httpMethod.addRequestHeader("Cache-Control", "no-cache, no-store");
httpMethod.addRequestHeader("Overwrite", "T");
InputStream is = new ByteArrayInputStream(buffer);
RequestEntity requestEntity = new InputStreamRequestEntity(is, "text/plain");
httpMethod.setRequestEntity(requestEntity);
httpClient.executeMethod(httpMethod);
What am I missing in the request header?

Following are correct headers, using this I am able update webdav server resources with offset and byte length.
HttpClient httpClient = new HttpClient();
PutMethod httpMethod = new PutMethod(fileUri);
httpMethod.addRequestHeader("Accept-Ranges", "bytes");
int total = byteOffset + byteCount;
int range = total-1;
String rangeMessage = "bytes=" + byteOffset +"-" + range;
Log.d(TAG, "rangeMessage " + rangeMessage);
String lengthMessage = Integer.toString(byteCount);
String contentRangeMessage = "bytes " + byteOffset +"-" + range + "/*";
Log.d(TAG, "contentRangeMessage " + contentRangeMessage);
Log.d(TAG, "lengthMessage " + lengthMessage);
httpMethod.addRequestHeader("Content-Length", lengthMessage);
httpMethod.addRequestHeader("Content-Range", contentRangeMessage);
httpMethod.addRequestHeader("Cache-Control", "no-cache, no-store");
httpMethod.addRequestHeader("Overwrite", "T");

Related

Save HTML and read in Android

I have created a function to generate receipt to save as text in the file.
but when I try to read that file, it shows me with HTML tags.
but when I open the text file from a phone using WPS office that doesn't show me HTML tags
this is when I open text file in phone:
this when I read file:
and this my code-:
File file = new File(Environment.getExternalStorageDirectory().toString());
file.mkdir();
if (file != null) {
Log.d("created", "notnull");
} else {
Log.d("created", "null");
}
File gpxfile = new File(file, "samples.txt");
FileWriter writer = null;
try {
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(gpxfile), Charset.forName("ASCII")));
//writer = new FileWriter(gpxfile);
//writer.write(billHTML());
out.write(billHTML());
//Log.d("writer", "" + billHTML());
//writer.close();
out.close();
**here i read file**
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(gpxfile), "ASCII"));
String sData;
while ((sData = in.readLine()) != null) {
System.out.println(sData);
}
Log.d("files", "" + in);
} catch (IOException e) {
e.printStackTrace();
}
this is genreate bill function.
public String billHTML() {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Calendar c = Calendar.getInstance();
StringBuilder sb = new StringBuilder();
sb.append("<html>"
+ "<body>");
sb.append("<br>");
sb.append("<h1><br><center> Texto mi marca </<center></h1>");
sb.append("<h2><center> Texto mi marca </<center></h2>");
sb.append("<br>");
sb.append("<br>");
sb.append("<center>Fecha:  " + sdf.format(c.getTime()));
sb.append("<br>");
sb.append("<center>Factura:  " + sdf.format(c.getTime()));
sb.append("<br>");
sb.append("<center>Cllente al contado");
sb.append("<br>");
sb.append("<br>");
sb.append("<h2><center>-------------------------------------------</h2>");
sb.append("<br>");
sb.append("<br>");
sb.append("<br>");
sb.append("<br>");
sb.append("<br>");
sb.append("<table width=550>" +
" <tr>" +
" <th width='50%' align='left'> Description</th>" +
" <th width='10%' align='left'>Units</th>" +
" <th width='10%' align='right'>Price</th>" +
" </tr>");
for (int i = 0; i < Util.itemArrayList.size(); i++) {
sb.append("<tr>"
+ "<td>").append(Util.itemArrayList.get(i).description)
.append("</td>"
+ "<td align='left'>")
.append(Util.itemArrayList.get(i).units)
.append("</td>"
+ "<td align='right'>")
.append(Util.itemArrayList.get(i).price + "€")
.append("</td>"
+ "</tr>");
oldpay = Util.itemArrayList.get(i).price;
totalprice = totalprice + oldpay;
}
float basevalue = (float) (totalprice / 1.21);
float ivaValue = totalprice - basevalue;
sb.append("<tr>"
+ "<td>").append("-----------------------")
.append("</td>"
+ "<td align='right'>");
sb.append("<tr>"
+ "<td>")
.append("(Total)Base imponible")
.append("</td>"
+ "<td align='right'>")
.append("</td> "
+ "<td align='right'>")
.append(decimalFormat.format(basevalue) + "€")
.append("</td>"
+ "</tr>");
sb.append("<tr>"
+ "<td>")
.append("IVA (+21%)")
.append("</td>"
+ "<td align='right'>")
.append("</td> "
+ "<td align='right'>")
.append(decimalFormat.format(ivaValue) + "€")
.append("</td>"
+ "</tr>");
sb.append("<tr>" +
"<td>").append("==============================================").append("</td>" +
"<td>==========</td>" +
"<td>===========</td>");
sb.append("<tr>"
+ "<td>").
append("<b>Total </b>")
.append("</td>"
+ "<td align='right'>")
.append("</td> "
+ "<td align='right'>")
.append(decimalFormat.format(totalprice) + "€")
.append("</td>"
+ "</tr>");
sb.append("</table>");
System.out.print(sb.toString());
return sb.toString();
}
If you are using html markup to generate the receipt you probably should name the file something like sample.html instead of sample.txt this way in your computer will be opened by a internet browser instead of the notepad.
Probably WPS Office is smart enough to detect the html tags and display the file with the correct formatting.

Failed to publish message on mqtt broker

I am developing a mobile application that need to implement mqtt. I need to publish the data to the mqtt broker, but it always fail to be published when i try to publish the image data which is the byte array of the image.
It didn't show any error when publish, but it did not published any data on the broker when I try to publish the message. The message can only be published when image data is removed from the payload which is the pichex.
Each data published on the mqtt broker need to be converted into hex ascii code. The byte array of image also need to be converted into hex ascii string code before publish to the broker as it is the requirement of the project.
private void publish(){
String command = "000000";
String reserve = "303030303030303030303030303030303030303030303030";
String tag = "tag";
name = eTname.getText().toString();
price = eTprice.getText().toString();
type = TypeS.getSelectedItem().toString();
desc = eTdesc.getText().toString();
userid = MainActivity.getGetuserid();
String namehex = toHexString(name);
String pricehex = toHexString(price);
String typehex = toHexString(type);
String deschex = toHexString(desc);
String useridhex = toHexString(userid);
Bitmap PicBitmap = ((BitmapDrawable)iVpic.getDrawable()).getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PicBitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] picbyte = bos.toByteArray();
String pichex = bytesToHex(picbyte);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
Date currentTime = Calendar.getInstance().getTime();
String currentTimeString = df.format(currentTime);
String payload = "{command:" + command + ", reserve:" + reserve + ", Client ID:" + serverConnectTo + ", Posted name:" + namehex +
", Posted Price:" + pricehex + ", Posted Type:" + typehex + ", Posted Description:" + deschex
+ ", Posted Picture:" + pichex + ", Date Time Posted:" + currentTimeString + ", User ID:" + useridhex + "}";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes();
MqttMessage message = new MqttMessage(encodedPayload);
message.setQos(qos);
mqttClient.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
public static String toHexString(String input) {
return String.format("%x", new BigInteger(1, input.getBytes()));
}
public static String bytesToHex(byte[] in) {
final StringBuilder builder = new StringBuilder();
for(byte b : in) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
The hex string value of the picture that need to be published is:
89504e470d0a1a0a0000000d49484452000005dc0000046508020000002ce5923a0000000373424954080808dbe14fe00000200049444154789cecbd617723c971b41b91550dcecaf6bde7feff3ff99ed7d60e89ae8cb81fb21a046738eb5dd9d648de7c3ca74d8140a3d16842aa4064046da3699aa6699aa6699aa6699aa6f9fb123ffb009aa6699aa6699aa6699aa669fe8cb428d3344dd3344dd3344dd3344df3136851a6699aa6699aa6699aa6699ae627d0a24cd3344dd3344dd3344dd334cd4fa04599a6699aa6699aa6699aa6699a9f408b324dd3344dd3344dd3344dd3343f8116659aa6699aa6699aa6699aa6697e022dca344dd3344dd3344dd3344dd3fc045a94699aa6699aa6699aa6699aa6f909b428d3344dd3344dd3344dd3344df3136851a6699aa6699aa6699aa6699ae627d0a24cd3344dd3344dd3344dd334cd4fa04599a6699aa6699aa6699aa6699a9f408b324dd3344dd3344dd3344dd3343f8116659aa6699aa6699aa6699aa6697e022dca344dd3344dd3344dd3344dd3fc045a94699aa6699aa6699aa6699aa6f909b428d3344dd3344dd3344dd3344df3136851a6699aa6699aa6699aa6699ae627d0a24cd3344dd3344dd3344dd334cd4fa04599a6699aa6699aa6699aa6699a9f408b324dd3344dd3344dd3344dd3343f8116659aa6699aa6699aa6699aa6697e022dca344dd3344dd3344dd3344dd3fc045a94699aa6699aa6699aa6699aa6f909b428d3344dd3344dd3344dd3344df3136851a6699aa6699aa6699aa6699ae627d0a24cd3344dd3344dd3344dd334cd4fa04599a6699aa6699aa6699aa6699a9f408b324dd3344dd3344dd3344dd3343f8116659aa6699aa6699aa6699aa6697e022dca344dd3344dd3344dd3344dd3fc045a94699aa6699aa6699aa6699aa6f909b428d3344dd3344dd3344dd3344df3136851a6699aa6699aa6699aa6699ae627d0a24cd3344dd3344dd3344dd334cd4fa04599a6699aa6699aa6699aa6699a9f408b324dd3344dd3344dd3344dd3343f8116659aa6699aa6699aa6699aa6697e02f3671f40d3344dd334efd8fef476927fe723699aa6699aa669fea769a74cd3344dd3344dd3344dd334cd4fa04599a6699aa6699aa6699aa6699a9f007f64936e9aa6699ae6bfceffd6ff9eed71aaa6699aa6699aff3aed94699aa6699aa6699aa6699aa6f90974d06fd3344dd3fc0ff2479d323f72a0fcb3386eda41d3344dd3344df3fb69a74cd3344dd3344dd3344dd334cd4fa09d324dd334cd3f0e02e2f76dffd1d00f6eff8d4315003300c00100140d00bcf656de1813340002a0f77fbcb6a2c3fce4fcf0a3b1c6bfcbbff2cd7eb09ff53b0c00e3e36dff2c0699c73bf5d3afa2ffeaf56c80bf7bfb47f967793b9ba6699ae69f9d16659aa6699a7f08840404f8f76d11df8a028f1d95b0f1ad4a221b1f876bc881f7b1a06f17a13f9ac29116be1fd2a1ae95efd3fe4100b157dcdf2cbc251880616094624204692851a7822421844192b4e120609990ec12659c701808d2e400b49f58d8c7493e6b460fa1e71b02248c0fff0000593bfab0ae37c8083fbda8c770d5b75356b46d40833f941e6c5fe7874f0fff5ce7fad178d456b21c00fce15dae03defb34b27efa8342c88feffefb658f6faf493d6d7fdf113d092d3244c477dbf10321f38f427faecbf4745ad3344dd3fcf7d2a24cd3344df30f857edff68faca9fd2e95d87eacea9f7ffee4417e3cf8039f3c84c256165442cfd32373bb60b616f05826bb9ec11fc50e1ab400818265c4a5cb2004386107606400b658af2261264823499a2aed263c002088787f9eefe598ebf4d01f45193e8e09803faceb83012760204a5279fc3ee2c9cb53f7787e033e39cf7efaf947f7fa6fe1f1127eeb78fe30bcb67fece0bfbfaa8bdff4ce3c2ee33ff4547f137c1719bf77de344dd3344df3df468b324dd334cd3f0e7f406a11fcae1becdb1ede930f8e8beb37d7ddf97cf3e507f86e99cb3fb8f265d9771e5acef5033fc82e4f7e1f8b60c0861d0410cfde0463ab29306cc35652a8bb03591a90edeb1cc80049030eda41879d00288204b7c981e5d7783a09fbac6c4bcf77ee0a7d761e9c008cbc5e65c0b1c7a6f6d68008d4d604307ec3b4719d2e3f7efe1b0383b71b259e5ed96ff007aeb73ae1df8b26efc7c9efefffed2e9eee5f7b90afcb8cef27fac329faccb0c2ba3900e2fb2d3fbdfd37f9d64f435c7f5d0e501fb6faee96921da3c59aa6699aa6f95b6851a6699aa6f987803f5842fb7371247e674acab593a79f7fd320f37b77e86fa496bde4f677a2ccb5d6fd60a588e774182cba06a904972d0690418009b0e68a980b166c486599b10540a897a3c7cb34610719b1a36a68925b9121be1365ea883476bacd9553b32d323f3c57ba13a083e425338579e5e3f83a1ebbb4a2271bcea767d2d710d3b61d919fff4f941fb7503d396ef0dff0167f47d997f0b40d50f68f148fff5cf1f19308755dcef9b4c565aafab85b1a105d7a5b001fb6c02004c4c7ed374ffc24a93c5edd472ebd53bf77fba371c2a6699aa6697e9316659aa6699a7f107eb488fdcf1d2b359cb3e76cfce497f96617bf31b8c4672fcdfb7e2ebe5db2fa7dd90c97c5410abc4b3397b1e2c10727821e712c1610e6b96f96390c0b346c7098212060e55bd8b56b695d4f7165a9ec85f17ed5368023af27211911d8f932789c193dfb6554d136212a1c8f8c924fd40d07a859278db1137e38f6e9535624f1f5300134e23de7e69b9dbdcf8925ec876664e71f0c
This is the image that need to publish
The size of the picture is about 100KB.
The message can be published only when the image data is removed from the payload which is the pichex:
String payload = "{command:" + command + ", reserve:" + reserve + ", Client ID:" + serverConnectTo + ", Posted name:" + namehex + ", Posted Price:" + pricehex + ", Posted Type:" + typehex + ", Posted Description:" + deschex + ", Date Time Posted:" + currentTimeString + ", User ID:" + useridhex + "}";
The message can be received by subscriber if pichex is removed:
{command:000000, reserve:303030303030303030303030303030303030303030303030, Client ID:Server, Posted name:627572676572, Posted Price:392e3939, Posted Type:6e6f6f646c65, Posted Description:616a6468, Date Time Posted:2018-10-14 08.09.29, User ID:696b6f6d61}

How to get the results from multiple servers in a function in Android

I'm installing Hybrid Ranking algorithm for Linked Data Extraction & Context on Android. Documents you can search Google for the keywords above.
And now I'm installing semantic similarity between two uri1 and uri2.
Input: two DBpedia URIs
Output: a value representing their similarity
private float similarity(String uri1, String uri2) {
float wikipedia = wikiS(uri1, uri2);
float abtract = abtractS(uri1, uri2);
float google = engineS(uri1, uri2, google);
float yahoo = engineS(uri1, uri2, yahoo);
float bing = engineS(uri1, uri2, bing);
float dilicious = engineS(uri1, uri2, dilicicous);
return wikipedia + abtract + google + yahoo + bing + dilicious;
}
And with each child function, I have to query data using SPARQL dbpedia, google, yahoo, bing, dilicious using provided API. The results obtained will be calculated to the parser and returns the corresponding float value.
Example for abtractS(uri1, uri2) below:
private float abstractS(String uri1, String uri2, final float wikiS){
String url = createUrlAbstractS(uri1, uri2);
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
float abtractS = 0.0f;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray data = jsonObject.getJSONObject("results").getJSONArray("bindings");
if(data.length() == 0){
showLogAndToast("No result");
}else{
JSONObject element = data.getJSONObject(0);
String label1 = element.getJSONObject("label1").getString("value");
String abtract1 = element.getJSONObject("abtract1").getString("value");
String label2 = element.getJSONObject("label2").getString("value");
String abtract2 = element.getJSONObject("abtract2").getString("value");
abtractS = calWordContained(label1, abtract2) + calWordContained(label2, abtract1) + wikiS;
//TODO: RESULT ABTRACTS HERE. How next?
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
return 0.0f;//HERE: no results
}
private float calWordContained(String label, String abtract){
if(label.length() == 0 || abtract.length() == 0){
return 0.0f;
}
List<String> words = Arrays.asList(label.split(" "));
int count = 0;
float length = words.size();
for(int i = 0; i < length; i++){
if(abtract.toLowerCase().contains(words.get(i).toLowerCase())){
count++;
}
}
return (count/length);
}
public String createUrlAbstractS(String uri1, String uri2){
private String BASE_URL_DBPEDIA = "http://dbpedia.org/sparql?default-graph-uri=&query=";
String query = createQueryAbstractS(uri1, uri2);
String url = "";
try {
url = Config.BASE_URL_DBPEDIA + URLEncoder.encode(query, "UTF-8") + Config.RESULT_JSON_TYPE;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
private String createQueryAbstractS(String uri1, String uri2){
String query = Config.PREFIX_DBPEDIA + " \n" +
"prefix dbpedia-owl: <http://dbpedia.org/ontology/>\n" +
"\n" +
"\n" +
"select ?label1, ?label2, ?abtract1, ?abtract2 where\n" +
"{\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri1 + "> rdfs:label ?label1 ;\n" +
" dbpedia-owl:abstract ?abtract1 .\n" +
" FILTER langMatches(lang(?abtract1),'en') . \n" +
" FILTER langMatches(lang(?label1),'en') .\n" +
" }\n" +
" }\n" +
"\n" +
"\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri2 + "> rdfs:label ?label2 ;\n" +
" dbpedia-owl:abstract ?abtract2 .\n" +
" FILTER langMatches(lang(?label2),'en') . \n" +
" FILTER langMatches(lang(?abtract2),'en') .\n" +
" }\n" +
" }\n" +
"}";
return query;
}
but how to do this on, I could not get the results I wanted in the similarity function (uri1, uri2). Therefore it will affect the results in different functions.
So I'm asking is: how can I get all the results of the function Wikis, abtractS, engine (google), engine (bing), engine (yahoo), engine (dilicious) in a simple way Best. I currently do on Android and data load times is very important.
Thank you very much!

SPP Android BT Connection quits after seconds (EEG readings)

I have created an app that receives data from a bt transmitter (Bluegiga). The readings are from EEG signals. The data rate is 1Khz (I have to admit it's high). Anyway, I acquire some data for some seconds and then the Bluetooth acts like there is no incoming data (which is not true). If I try to disconnect the Bluetooth using the app is clear that there is no more communication with the bt module at the EEG board since it doesn't respond to the desconnection (It has a led that indicates when is connected, and it doesn't turn of/on or anything).
If I decrease the data rate to (let's say 500hz) the app works ok, with some occasional 'quits', but tolerable. If I decrease it more the app works with no problems.
Of curse, by design, my app must work at 1Khz data rate so here is where the problem comes.
I have check some other post, trying to hit some kind of sns but nothing match my problem exactly (anyway I have tried to use the information on them but with no success obviously).
Sometimes I get this message, "dm_pm_timer expires", sometimes no (after the bt stops working).
Sadly there is no indication, Exception or message that can tell me what's going on.
Here is my Code for the BT reception Thread
class BluetoothReadThread extends Thread {
private final InputStream iStream;
private final OutputStream mmOutputStream;
private boolean continueReading = true;
public BluetoothReadThread() {
InputStream tmp = null;
OutputStream tmp2 = null;
try {
tmp = btSocket.getInputStream();
tmp2 = btSocket.getOutputStream();
} catch (IOException e) {
}
iStream = tmp;
mmOutputStream = tmp2;
}
#Override
public void run() {
int c;
int waitCount = 0;
while (continueReading) {
try {
if (iStream.available() > 0) {
waitCount = 0;
c = iStream.read();
readBuffer[readBufferPosition++] = c;
if (readBufferPosition == bitsExpected) {
if (bitsExpected == 22) {
ch1 = MultiplicationCombine(readBuffer[4], readBuffer[3]);
ch2 = MultiplicationCombine(readBuffer[6], readBuffer[5]);
ch3 = MultiplicationCombine(readBuffer[8], readBuffer[7]);
ch4 = MultiplicationCombine(readBuffer[10], readBuffer[9]);
ch5 = MultiplicationCombine(readBuffer[12], readBuffer[11]);
ch6 = MultiplicationCombine(readBuffer[14], readBuffer[13]);
ch7 = MultiplicationCombine(readBuffer[16], readBuffer[15]);
ch8 = MultiplicationCombine(readBuffer[18], readBuffer[17]);
} else {
ch1 = (int) filter_3((double)MultiplicationCombine(readBuffer[5], readBuffer[4], readBuffer[3]));
ch2 = (int) filter_4((double)MultiplicationCombine(readBuffer[8], readBuffer[7], readBuffer[6]));
ch3 = (int) filter_2((double)MultiplicationCombine(readBuffer[11], readBuffer[10], readBuffer[9]));
ch4 = (int) filter_2((double)MultiplicationCombine(readBuffer[14], readBuffer[13], readBuffer[12]));
ch5 = (int) filter_2((double)MultiplicationCombine(readBuffer[17], readBuffer[16], readBuffer[15]));
ch6 = (int) filter_2((double)MultiplicationCombine(readBuffer[20], readBuffer[19], readBuffer[18]));
ch7 = (int) filter_2((double)MultiplicationCombine(readBuffer[23], readBuffer[22], readBuffer[21]));
ch8 = (int) filter_2((double)MultiplicationCombine(readBuffer[26], readBuffer[25], readBuffer[24]));
}
Header_int = readBuffer[0];
PK_ID_int = readBuffer[1];
PK_Counter_int = readBuffer[2];
if (downsample++ == downsample_value) {
addEntry(ch1 / scaCh1, ch2 / scaCh2, ch3 / scaCh3, ch4 / scaCh4, ch5 / scaCh5, ch6 / scaCh6, ch7 / scaCh7, ch8 / scaCh8);
downsample = 0;
}
//ProgrNum,PacketType,Ch1,Ch2,Ch3,Ch4,Ch5,Ch6,Ch7,Ch8,MRK
if (write_open) {
osw.write(PK_Counter_int + "," + PK_ID_int + "," + ch1 + "," + ch2 + "," + ch3 + "," + ch4 + "," + ch5 + "," + ch6 + "," + ch7 + "," + ch8 + "," + bolOpenClose + "\n");
//osw.write(PK_Counter_int + "," + PK_ID_int + "," + ch1 + "," + ch2 + "," + ch3 + "," + ch4 + "," + ch5 + "," + ch6 + "," + ch7 + "," + ch8 + "," + "\n");
}
System.out.println(PK_Counter_int + "," + PK_ID_int + "," + ch1 + "," + ch2 + "," + ch3 + "," + ch4 + "," + ch5 + "," + ch6 + "," + ch7 + "," + ch8 + ", AV=" + iStream.available() );
mmOutputStream.write(valueSTR.getBytes());
// if(downsample++==14) { safe_copy(readBuffer); plot=true; downsample=0;}
readBufferPosition = 0;
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
System.out.println(e + "\nError sending data + :" + e);
// Bluetooth error! Stop reading.
//this.stopAndSendIntent();
}
}
}
/*
public void stopAndSendIntent() {
this.cancel();
Intent intent = new Intent();
intent.setAction(BLUETOOTH_ACTION_DONE_READING);
sendBroadcast(intent);
}
*/
public void cancel() {
System.out.println("-----Cancelling readThread!!");
try {
iStream.close();
} catch (IOException e) {
} catch (NullPointerException e) {
}
;
continueReading = false;
}
}
It works like this:
I read a received character (c=iStream.read()).
Then I copy this character to an int array until I reach the length of the packet (it can be 22 or 28 (bitsExpected)).
The following part is just filtering and plotting of the signal.
I have tried many other implementations but I get the same result.
Even if I eliminate the part of the filtering and plotting (just reading data) the problem persists.
If instead of working with array, I work with string, i.e, using append() (which should be the same?) I manage to get an working connection (no quits) but, as soon as I manipulate the program using the array everything is the same.
I'm stuck with this for 1 month already, so I will really appreciate any comments, past experience or suggestions.
Thanks in advance.
I just added this piece of code
if (PK_Counter_int % 100 == 0) mmOutputStream.write(startTring.getBytes());
and it works just fine so far.

networking oneway connection android

my todays problem is the following:
I have a network connection, at which both sides have to send commands (bytes), but my reader blocks my writer, thats how it seems to be. If I "disable" my reader (by deleting the reader from source) the writer works as he should, But when my reader is there, too, my writer just do the half of the work.
Lets say my writer has to send a command with an interval of 15 seconds and stay aware of incoming commands whach has to be answered by a little byte block. The answer block is send, but the command from the interval seems blocked.
Here my source:
protected String doInBackground(URL... params) {
try {
btw1 = (byte) sendbeg;
btw2 = (byte) w2;
btw3 = (byte) w3;
btw4 = (byte) w4;
btw5 = (byte) w5;
if (w5 == 79) {
btw6 = (byte) mins;
btw7 = (byte) seks;
btw8 = (byte) w6;
btw9 = (byte) sendend;
} else {
btw6 = (byte) w6;
btw7 = (byte) sendend;
}
SocketAddress sockaddr = new InetSocketAddress("192.168.0.7", 2001);
sock = new Socket();
int timeout = 1000; // 1000 millis = 1 second
sock.connect(sockaddr, timeout);
sock.setReuseAddress(true);
System.out.println(sock);
DataOutputStream dos = new DataOutputStream(
(OutputStream) sock.getOutputStream());
BufferedWriter wrtr = new BufferedWriter(
new OutputStreamWriter(dos), 300);
DataInputStream dis = new DataInputStream(sock.getInputStream());
BufferedReader rdr = new BufferedReader(new InputStreamReader(dis),
300);
getbyte((byte) btw1, (byte) btw2, (byte) btw3, (byte) btw4,
(byte) btw5, (byte) btw6, (byte) btw7, (byte) btw8,
(byte) btw9, (byte) btw10); //getbyte works fine, too. It's just there for putting the single bytes into an array.
System.out.println(btw.length);
dos.write(btw);
diny1 = (dis).read();
diny2 = (dis).read();
diny3 = (dis).read();
diny4 = (dis).read();
diny5 = (dis).read();
dinymin = (dis).read();
dinysek = (dis).read();
diny6 = (dis).read();
diny7 = (dis).read();
if (diny5 != 79) {
System.out.println("diny" + diny1 + " " + diny2 + " " + diny3
+ " " + diny4 + " " + diny5 + " " + dinymin + " "
+ dinysek);
} else {
if (diny7 != 5) {
diny6 = 0;
diny7 = 0;
}
System.out.println("diny" + diny1 + " " + diny2 + " " + diny3
+ " " + diny4 + " " + diny5 + " " + dinymin + " "
+ dinysek + " " + diny6 + " " + diny7);
}
dos.close();
wrtr.close();
dis.close();
rdr.close();
if (diny5 != 32) {
sendbeg = 3;
w2 = diny3;
w3 = diny2;
w4 = 48;
w5 = 32;
w6 = 11;
sendend = 5;
System.out.println(diny5 + " ^^ ");
doInBackground();
}
System.out.println("case 144-49-000.1" + context);
reccom(context);
sock.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("IO error " + e);
}
return "Done";
}
My intervalsource works fine, because it works, if the reader is inactive, so i think the problem is in this code above. please help.
You can delete the setReuseAddress() call; it's only for server sockets.
AsyncTask is not exactly the right class for your readers and writers if you stay in a loop there all the time; it would be more suitable to use Thread.
It sounds as if you need a seperate reader and writer Thread if one is not allowed to block the other.
You'll probably have to use synchronized along the way if reader and writer act independently

Categories

Resources