I have a little problem. I wrote a program on ESP32 which records some data and save it to SD card then data is read line by line and send to app which put it in postgres database. The problem is, sometimes data is being write to database long and sometimes it took like 0.5 sec, so i get response after 10 sec, sometimes after 5s, etc. Here is problem, on ESP I cant figure out how to wait to get response, my program just give me error but the data is sucessfully sent, it shows in database. So here is my question, how am I supposed to wait for response and then I can run rest of code.
And second question with the same program. As Im using sd card adapter and writing data to files, after i get response = 200 from server I want to clear files. What I did is I just delete both files (Im saving data to 2 files) and when i need to write data again to those files I create them. I suppose it not the most optimal way of doing it but couldnt find any method to clear files content or I just missed it somehow. Any suggestion on how I could do it another way?
if (WiFi.status() == WL_CONNECTED && flag == false){
createFile();
HTTPClient http;
http.begin("http://192.168.xx.xxx/xxxxxxx");
http.addHeader("Content-Type", "application/json");
String h_str = String(h);
if (h < 10)
{
h_str = "0" + String(h);
}
String m_str = String(m);
if (m < 10)
{
m_str = "0" + String(m);
}
String s_str = String(s);
if (s < 10)
{
s_str = "0" + String(s);
}
String totalTime_HMS = h_str + ":" + m_str + ":" + s_str;
//Srial.println(totalTime_HMS)
doc["name"] = "Machine_1";
doc["totalTime_HMS"] = totalTime_HMS;
readLinesSDON(SD, "/dataON.txt");
delay(50);
readLinesSDOFF(SD, "/dataOFF.txt");
String requestBody;
serializeJson(doc, requestBody);
int httpResponseCode = http.POST(requestBody);
flag = true;
if (httpResponseCode > 0)
{
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
deleteFile(SD, "/dataON.txt");
deleteFile(SD, "/dataOFF.txt");
//clearing temp arr - debug only
for (int i = 0; i < numL; i++)
{
timesON[i] = "0";
timesOFF[i] = "0";
}
}
else
{
Serial.printf("Error occurred while sending HTTP POST");
}
}
Related
I am working with http request. suddenly on my request, i was getting response status code as "200" so that my api is working.. but, upon my response body that return is incomplete. by the way, this is my resources used.
String APILink = "http://10.12.50.46:9191";
String compressedString2;
Future<SuccessData> getSession() async {
http.Response response2=await http.post(
Uri.encodeFull(APILink+"/Mobile/StartSession"),
headers:{
"Auth-Key":"InSys-dev-key-001 ",
},body:compressedString2,
);
print("Compressed JSON:"+compressedString2);
print(response2.statusCode);
var dataGather2 = json.decode(response2.body);
print(response2.body);
}
this is my actual responseupon using insomnia (Rest API)
and here is my print data upon my logcat:
if you notice, my return data upon "ResultSet" is not complete.. also the other data do be fetch like status, errormsg,and tag is not viewed.
Print function will not print everything
You can see print() statements in Flutter are truncated in flutter run output
https://github.com/flutter/flutter/issues/22665
Solution 1:
From https://github.com/flutter/flutter/issues/22665#issuecomment-580613192
You can use the following two code snippet
void logLongString(String s) {
if (s == null || s.length <= 0) return;
const int n = 1000;
int startIndex = 0;
int endIndex = n;
while (startIndex < s.length) {
if (endIndex > s.length) endIndex = s.length;
print(s.substring(startIndex, endIndex));
startIndex += n;
endIndex = startIndex + n;
}
}
https://github.com/flutter/flutter/issues/22665#issuecomment-513476234
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
Solution 2:
In Android Studio Debug mode, set break point and copy variable content in Variables window
I am able to initiate asynchronous uploads to S3, however they are somehow not ending up as a file inside my S3 bucket and I see an error 'WithPartETags cannot be empty'. Here is the complete code
InitiateMultipartUploadRequest initRequest =
new InitiateMultipartUploadRequest()
.WithBucketName(existingBucketName)
.WithKey(Path.Combine(S3Path + "/", finfo.Name));
InitiateMultipartUploadResponse initResponse =
s3Client.InitiateMultipartUpload(initRequest);
// 2. Upload Parts.
long contentLength = finfo.Length;
long partSize = 15728640;//52428800-50MB 104857600- 100 MB - 5242880 - 5 MB
try
{
long filePosition = 0;
for (int i = 1; filePosition < contentLength; i++)
{
// Create request to upload a part.
UploadPartRequest uploadRequest = new UploadPartRequest()
.WithBucketName(existingBucketName)
.WithKey(Path.Combine(S3Path + "/", finfo.Name))
.WithUploadId(initResponse.UploadId)
.WithPartNumber(i)
.WithPartSize(partSize)
.WithFilePosition(filePosition)
.WithFilePath(finfo.FullName);
// Upload part and add response to our list.
//uploadResponses.Add(s3Client.UploadPart(uploadRequest));
IAsyncResult ar = s3Client.BeginUploadPart(uploadRequest, null, null);
ListObj.Add(new ThreadList() { _iasyncResult = ar });
filePosition += partSize;
Console.WriteLine("Length Written - " + filePosition + " .Content Length - " + contentLength);
}
bool uploadsComplete = false;
while (!uploadsComplete)
{
bool individualuploadscomplete = true;
foreach (var obj in ListObj)
{
if (!obj._iasyncResult.IsCompleted)
{
individualuploadscomplete = false;
break;
}
}
if (individualuploadscomplete)
{
uploadsComplete = true;
}
}
foreach (var obj in ListObj)
{
s3Client.EndUploadPart(obj._iasyncResult);
}
//// Step 3: complete.
CompleteMultipartUploadRequest compRequest =
new CompleteMultipartUploadRequest()
.WithBucketName(existingBucketName)
.WithKey(Path.Combine(S3Path + "/", finfo.Name))
.WithUploadId(initResponse.UploadId);
//.WithPartETags(uploadResponses);
CompleteMultipartUploadResponse completeUploadResponse =
s3Client.CompleteMultipartUpload(compRequest);
Not sure why you have the setting of the PartETags commented out for the complete multipart upload call but you need to add that code back in. Also when you are calling the EndUploadPart method you need to capture that UploadResponse that comes back from that.
You also might want to look into the TransferUtility found in the Amazon.S3.Transfer namespace. Its upload methods are designed to handle what you are attempting to accomplish for large objects, see Using the High-Level .NET API for Multipart Upload for details and example snippets.
Below code specifies that we we can make http connection in blackberry and how to store html page as a string?
I am doing this but I am able to get that http request but when I get response i.e http_ok it is not correct so that I can save text oh html as a string and I can further store that into sqlite.
LabelField title = new LabelField("SQLite Create Database Sample",
LabelField.ELLIPSIS |
LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Creating a database."));
argURL="https://www.google.com:80";
try {
connDesc = connFact.getConnection(argURL);
if (connDesc != null) {
httpConn = (HttpConnection) connDesc.getConnection();
// //Send Data on this connection
// httpConn.setRequestMethod(HttpConnection.GET);
// //Server Response
StringBuffer strBuffer = new StringBuffer();
inStream = httpConn.openInputStream();
int chr;
int retResponseCode = httpConn.getResponseCode();
if (retResponseCode == HttpConnection.HTTP_OK) {
if (inStream != null) {
while ((chr = inStream.read()) != -1) {
strBuffer.append((char) chr);
}
serverResponceStr = strBuffer.toString();
// appLe.alertForms.get_userWaitAlertForm().append("\n"+serverResponceStr);
//returnCode = gprsConstants.retCodeSuccess;
}
} else {
//returnCode = gprsConstants.retCodeNOK;
}
}
} catch (Exception excp) {
//returnCode = gprsConstants.retCodeDisconn;
excp.printStackTrace();
} `enter code here`
The code does not perform any database functionality, however I tested and it does successfully perform an HttpRequest to an external URL. The data that comes back is based on the response of the server you are making the request to.
The code I used can be found here:
http://snipt.org/vrl7
The only modifications is to keep a running summary of various events, and the response is displayed in the RichTextField. Basically, this looks to be working as intended, and the resulting String should be able to be saved however you see fit; though you may need to be cautious of encoding when saving to a database so that special characters are not lost or misinterpreted.
Hey guys I'm having a huge problem when Encrypting a message in an older phone in comparison with the newer ones.
I've compiled the code to run on older hardware (CLDC1.0, MIDP2.0), and for some reason, when I do a TEA Encryption in a Nokia N70 I end up having one ruined character when it goes from plain-text to TEA. (yes I know, from a lot of chars only that one little char gets ruined...)
When I run exactly the same app on the N8 and other more recent phones however I get it encrypting correctly.
before I post the code however here's a small explanation on what it does:
basically it receives a String and a boolean inputs, the boolean states if it's for encryption or decryption purposes, whilst the string is what I want to encode or decode.
from there, I basically strip the String into a byte array, treat it accordingly (if for encrypt or decrypt) and later turn it into a String, which I then return (decrypt) or I encode in Base64 (encrypt).
The reason to encapsulate in Base64 is so it can be sent by sms, since this encoding uses non-special characters it keeps the sms limit up to 160 characters, which is desirable for the app.
now for the code:
private String HandleTEA(String input, boolean aIsEncryption) throws UnsupportedEncodingException
{
System.out.println(input);
String returnable = "";
try
{
TEAEngine e = new TEAEngine();
if (aIsEncryption)
{
e.init(true, TEAkey);
}
else
{
if(getDebug())
{
input = input.substring(1);
}
input = base64.decodeString(input);
e.init(false, TEAkey);
}
byte[] aData = input.getBytes("ISO-8859-1");
byte[] textToUse = aData;
int len = ((textToUse.length + 16 - 1) / 16) * 16;
byte[] secondUse = new byte[len];
for(int i = 0; i < textToUse.length; i++)
{
secondUse[i] = textToUse[i];
}
for(int i = textToUse.length; i < secondUse.length; i++)
{
secondUse[i] = 0;
}
int blockSize = e.getBlockSize();
byte[] outBytes = new byte[secondUse.length];
for (int chunkPosition = 0; chunkPosition < secondUse.length; chunkPosition += blockSize)
{
int chunkSize = Math.min(blockSize, (textToUse.length - (chunkPosition * blockSize)));
e.processBlock(secondUse, chunkPosition, outBytes, chunkPosition);
}
if(aIsEncryption)
{
Baseless = new String(outBytes, "ISO-8859-1");
String encodedString = base64.encodeString(Baseless);
char[] theChars = new char[encodedString.length()+1];
for(int i = 0; i < theChars.length; i++)
{
if(i == 0)
{
theChars[i] = '1';
}
else
{
theChars[i] = encodedString.charAt(i-1);
}
}
byte[] treating = new byte[theChars.length];
for(int i = 0; i < theChars.length; i++)
{
treating[i] = (byte)theChars[i];
}
returnable = new String(treating, "ISO-8859-1");
}
else
{
char[] theChars = new String(outBytes, "ISO-8859-1").toCharArray();
String fixed ="";
for(int i = 0; i < theChars.length; i++)
{
char c = theChars[i];
if (c > 0) fixed = fixed + c;
}
returnable = fixed;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return returnable;
}
Anyone have any idea on what might be happening?
for comparison this is what I'm getting from the N70:
e+TgV/fU5RUOYocMRfG7vqpQT+jKlujU6eIzZfEjGhXdFwNB46wYNSiUj5H/tWbta26No6wjQylgTexhS6uqyw==
and from the N8:
e+TgV/fU5RUOYocMRfG7vqpQT+jKlujU6eIzZfEjgBXdFwNB46wYNSiUj5H/tWbta26No6wjQylgTexhS6uqyw==
as you can see everything looks similar, but in the middle of the code what gets encoded as Gh on the N70 shows up as gB on the N8...
when decrypting the data encrypted by the N70 we get some really weird chars:
will add this here tomorrow since I don't have the saved output with me
both are using the same key (in real-life tho they'll be using a key that's randomly generated on startup)
here's the key used:
0b1b5e0167aaee06
Hope you can help me out with this and Thanks for your interest and assistance!
your code is hard to understand, but Baseless = new String(outBytes, "ISO-8859-1"); and any similar constructs are almost certainly incorrect. Why do you want to make a String out of cipher? Just base64 encode outBytes directly.
I have a piece of code that opens a HTTP connection to read the data contained on a webpage.
HttpConnection h = new HttpConnection();
InputStream input = h.openInputStream();
int len = (int) h.httpConn.getLength();
StringBuffer raw = new StringBuffer();
if(len > 0)
{
byte[] data = new byte[len];
while( -1 != (len = input.read(data)))
{
raw.append(new String(data, 0, len));
}
}
response = raw.toString();
input.close();
h.httpConn.close();
//System.out.println("Response -----> " + response);
return response;
This code works absolutely fine, but on certain punctuation marks its not reading properly. For example >> ' << an apostrophe comes out as >> รข <<.
I'm guessing it might be something to do with encoding but I have tried UTF-8, UTF-16 and ASCII and this didn't fix the problem.
I've had this work for me when I was getting odd characters in place of punctuation:
public String getContents(InputStream stream) {
String contents = null;
try{
contents = new String(IOUtilities.streamToBytes(stream), "UTF-8");
}
catch(Exception e) {
//encoding error
}
return contents;
}
Instead of this:
raw.append(new String(data, 0, len));
you can use
raw.append(new String(data, 0, len, "UTF-8"));
passing in the name of a character enconding, in this case UTF-8.