Linkit One crashed after few hours while sending post - arduino

I'm bought a Linkit One last week and I'm trying to send http post (JSON) request to my remote server via sim card from the Linkit One board.
It all seems working fine but after couple hours those request stopped arriving to my server.
this is my code :
#include <LGPRS.h>
#include <LGPRSClient.h>
#include <LGPRSServer.h>
char server[] = "myserver.com";
int port = 80;
String object = "";
String Location = "";
int objSize;
String objLength;
LGPRSClient client;
void setup() {
Serial.begin(115200);
while (!LGPRS.attachGPRS("internet.golantelecom.net.il", "", "")) {
delay(500);
}
}
void loop() {
object = "value=test";
sendHttpRequest(object);
delay(5000);
}
void sendHttpRequest(String object) {
objSize = object.length();
objLength = String(objSize);
int timeOut = 0;
int index = 0;
String response = "";
if (client.connect(server, port)) {
// FOR THE CONSOLE :
Serial.println(F("POST /index.php HTTP/1.1"));
Serial.print(F("Host: "));
Serial.println(server);
Serial.println(F("Content-Type: application/x-www-form-urlencoded"));
Serial.print(F("Content-Length: "));
Serial.println(objLength);
Serial.println();
Serial.println(object);
Serial.println();
// FOR THE SERVER :
client.println(F("POST /index.php HTTP/1.1"));
client.print(F("Host: "));
client.println(server);
client.println(F("Content-Type: application/x-www-form-urlencoded"));
client.print(F("Content-Length: "));
client.println(objLength);
client.println();
client.println(object);
client.println();
}
else Serial.println("connection failed");
while (client.connected()) {
if (client.available() > 0) {
char value = client.read();
if(String(value) == "{" || index) {
response += String(value);
index++;
if(String(value) == "}") index = 0;
}
}
if (!client.connected() || timeOut == 35000) {
Serial.print("Server Response: ");
Serial.println(response);
Serial.println();
client.stop();
}
timeOut++;
}
}
And this is the log from the server :
http://s11.postimg.org/f6oriqj37/image.png
Please help me to figure out what is going on here..
thanks!

A new version of LinkIt ONE SDK v1.1 was released on 2/18/2015. You can try to download the latest version of SDK from this link, and update the firmware on the board accordingly. The companion firmware of LinkIt ONE SDK v2.0 is v1.1.05. Hope this resolves your issue.

Related

HTTP POST request-GSM Arduino

I've MKR GSM 1400 with sim and antenna, I want to send data to the KAA cloud by HTTP POST request.
By using cURL I've succeded to send data to the cloud using thise code
curl --location --request POST 'https://connect.cloud.kaaiot.com:443/kp1/<app-version-name>/dcx/<endpoint-token>/json' \
--data-raw '[
{
"temperature": 23,
"humidity": 48
}
]
Based on this I've written this code so far but I'm not sure what I'm missing for it to work :
#include <ArduinoHttpClient.h>
#include <MKRGSM.h>
#include <ArduinoJson.h>
const char PINNUMBER[] = "";
const char GPRS_APN[] = "";
const char GPRS_LOGIN[] = "";
const char GPRS_PASSWORD[] = "";
const String TOKEN = ""; // Deleted for security purpose
const String APP_VERSION = ""; // Deleted for security purpose
const unsigned long fiveSeconds = 1 * 5 * 1000UL;
static unsigned long lastPublish = 0 - fiveSeconds;
int temp;
GSMClient client;
GPRS gprs;
GSM gsmAccess;
char server[] = "connect.cloud.kaaiot.com";
char path[] = "/";
int port = 443;
HttpClient httpClient = HttpClient(client, server, port);
void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Starting GSM connection...");
// connection state
boolean connected = false;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while (!connected) {
if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
connected = true;
} else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, port)) {
Serial.println("connected");
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop() {
if (client.connect(server, port)) {
unsigned long now = millis();
if (now - lastPublish >= fiveSeconds) {
lastPublish += fiveSeconds;
temp = random(18, 23);
Serial.print("temperature = ");
Serial.println(temp);
String queryString = String(" \"temperature\": ) + String(temp) ");
String topic = "/kp1/" + APP_VERSION + "/dcx/" + TOKEN + "/json";
httpClient.println("POST https://" + String(server) + ":" + String(port) + String(topic) + " HTTP/1.1");
Serial.println("POST https://" + String(server) + ":" + String(port) + String(topic) + " HTTP/1.1");
httpClient.println("Connection: close");
httpClient.println(); // end HTTP header
// send HTTP body
httpClient.print("{ \"temperature\": ");
httpClient.print(temp);
httpClient.print("}");
//httpClient.println(queryString);
}
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
delay(3000); // Wait for 3 seconds to post again
}
On Serial monitor it shows that I've connected to the server.

Problem Reading From Thingspeak from Arduino

I am using this code to retrieve data from a Thingspeak channel in a JSON format. I am using an ESP8266 along with an Arduino Nano 33 BLE. The Nono 33 BLE Arduino board is not compatible with Thingspeak library and it doesn’t support SoftwareSerial. Alternatively, I am using serial1 to communicate with the ESP8266 and REST API method to get the data from Thingspeak as it is shown in the code. However, I cannot get it to work. It is worth noting that Serial1.available() always gives zero even after adding delays.
I have used the same code to send data to the same Thingspeak channel and it works perfectly. I have no clue why it is not reading from the channel. I would really appreciate any help with this problem
Thanks in advance.
String AP ="xxxxxxxxxxx";
String PASS ="xxxxxxxxxxxxxx";
String PORT = "80";
String field = "Id";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
String Data ="";
void setup() {
Serial.begin(9600);
Serial1.begin(115200);
sendCommand("AT",5,"OK",false);
Serial1.println("AT+UART_DEF=9600,8,1,0,0");
delay(1000);
Serial1.end();
Serial1.begin(9600);
ConnectToWifi();
}
void loop() {
String getData="GET https://api.thingspeak.com/channels/1335558/fields/1?api_key=7XFZKXEGOV5HY4TQ";
sendCommand("AT+CIPMUX=1",5,"OK",false);
sendCommand("AT+CIPSTART=4,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK",false);
sendCommand("AT+CIPSEND=4," +String(getData.length()+4),4,">",false);
sendCommand(getData,20,"OK",true);
delay(1500);
countTrueCommand++;
sendCommand("AT+CIPCLOSE=0",5,"OK",false);
}
bool ConnectToWifi(){
for (int a=0; a<15; a++)
{
sendCommand("AT",5,"OK",false);
sendCommand("AT+CWMODE=1",5,"OK",false);
boolean isConnected = sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK",false);
if(isConnected)
{
return true;
}
}
}
bool sendCommand(String command, int maxTime, char readReplay[],boolean isGetData) {
boolean result=false;
//Test Purpose
Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
Serial1.println(command);
if(Serial1.find(readReplay))//ok
{
if(isGetData)
{
if(Serial1.find(readReplay))
{
Serial.println("Success : Request is taken from the server");
}
while(Serial1.available())
{
char character = Serial1.read()
Data.concat(character); /
if (character == '\n')
{
Serial.print("Received: ");
Serial.println(Data);
delay(50);
Data = "";
}
}
}
result = true;
break;
}
countTimeCommand++;
}
if(result == true)
{
Serial.println("Success");
countTrueCommand++;
countTimeCommand = 0;
}
if(result == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}
found = false;
return result;

ESP32 writeStringEEPROM adds unwanted nembers when I use the letter '&'

I am trying to use this code:
https://github.com/jatocode/WifiConnect/blob/master/WifiConnect/WifiConnect.ino with my ESP32.
The problem is that my wifi network name is "y&t" and when I am trying to use it the progrem saves to the EEPROM "y&26t" insted, with other networks names in my area it dosn't have a problem.
I will be greatful if somebady knows how to solve this problem.
Thanks to #Juraj I solved the problem.
I used in this code a decoder from here: https://circuits4you.com/2019/03/21/esp8266-url-encode-decode-example/
/*
Configuration AP example
The example shows a very simple Configuration Access Point.
created in August 2019
by Juraj Andrassy https://github.com/jandrassy
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <Arduino.h>
// #include <String.h>
String urldecode(String str);
unsigned char h2int(char c);
void setup() {
Serial.begin(115200);
delay(500);
// WiFi.disconnect(); // forget the persistent connection to test the Configuration AP
WiFi.persistent(true);
// waiting for connection to remembered Wifi network
Serial.println("Waiting for connection to WiFi");
WiFi.begin(); // use SSID and password stored by SDK
WiFi.waitForConnectResult();
if (WiFi.status() != WL_CONNECTED) {
Serial.println();
Serial.println("Could not connect to WiFi. Starting configuration AP...");
configAP();
} else {
Serial.println("WiFi connected");
}
}
void loop() {
}
void configAP() {
WiFiServer configWebServer(80);
WiFi.mode(WIFI_AP_STA); // starts the default AP (factory default or setup as persistent)
Serial.print("Connect your computer to the WiFi network ");
// Serial.print(WiFi.softAP());
Serial.println();
IPAddress ip = WiFi.softAPIP();
Serial.print("and enter http://");
Serial.print(ip);
Serial.println(" in a Web browser");
configWebServer.begin();
while (true) {
WiFiClient client = configWebServer.available();
if (client) {
char line[64];
int l = client.readBytesUntil('\n', line, sizeof(line));
line[l] = 0;
client.find((char*) "\r\n\r\n");
if (strncmp_P(line, PSTR("POST"), strlen("POST")) == 0) {
l = client.readBytes(line, sizeof(line));
line[l] = 0;
// parse the parameters sent by the html form
const char* delims = "=&";
strtok(line, delims);
const char* ssid = strtok(NULL, delims);
strtok(NULL, delims);
const char* pass = strtok(NULL, delims);
// decoding the ssid and the password for ASCII characters
String ssidS = String(ssid);
String ssidSdecode= urldecode(ssidS);
ssid=const_cast<char*>(ssidSdecode.c_str());
String passS = String(pass);
String passSdecode= urldecode(passS);
pass=const_cast<char*>(passSdecode.c_str());
// send a response before attemting to connect to the WiFi network
// because it will reset the SoftAP and disconnect the client station
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println(F("Refresh: 10")); // send a request after 10 seconds
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>connecting...</body></html>"));
client.stop();
Serial.println();
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
WiFi.waitForConnectResult();
// configuration continues with the next request
} else {
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Connection: close"));
client.println();
client.println(F("<html><body><h3>Configuration AP</h3><br>"));
int status = WiFi.status();
if (status == WL_CONNECTED) {
client.println(F("Connection successful. Ending AP."));
} else {
client.println(F("<form action='/' method='POST'>WiFi connection failed. Enter valid parameters, please.<br><br>"));
client.println(F("SSID:<br><input type='text' name='i'><br>"));
client.println(F("Password:<br><input type='password' name='p'><br><br>"));
client.println(F("<input type='submit' value='Submit'></form>"));
}
client.println(F("</body></html>"));
client.stop();
if (status == WL_CONNECTED) {
delay(1000); // to let the SDK finish the communication
Serial.println("Connection successful. Ending AP.");
configWebServer.stop();
WiFi.mode(WIFI_STA);
}
}
}
}
}
String urldecode(String str) {
String encodedString="";
char c;
char code0;
char code1;
for (int i =0; i < str.length(); i++) {
c=str.charAt(i);
if (c == '+') {
encodedString+=' ';
} else if (c == '%') {
i++;
code0=str.charAt(i);
i++;
code1=str.charAt(i);
c = (h2int(code0) << 4) | h2int(code1);
encodedString+=c;
} else {
encodedString+=c;
}
yield();
}
return encodedString;
}
unsigned char h2int(char c) {
if (c >= '0' && c <='9') {
return((unsigned char)c - '0');
}
if (c >= 'a' && c <='f') {
return((unsigned char)c - 'a' + 10);
}
if (c >= 'A' && c <='F') {
return((unsigned char)c - 'A' + 10);
}
return(0);
}

How to receive JSON response from REST API using ESP8266 Arduino framework

I am trying to use Beyond Verbal RST API to post voice sample data over HTTP post method from ESP8266. The first step for the API communication is to get access token using the POST method. You can check the following codes. With this code I am just getting "failed to Post" response on serial output.
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "xxxxxx";
const char *pass = "xxxxxx";
String token;
HTTPClient https;
WiFiClientSecure client;
String getRecordID(String stoken);
void setup() {
Serial.begin(115200);
Serial.println("connecting to network..");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("conntected to network..");
}
void loop() {
String ret;
token = getAccessToken();
delay(2000);
Serial.println(token);
}
String getAccessToken(){
// client.setInsecure();
const char * host = "token.beyondverbal.com";
const uint16_t port = 443;
const char * path = "/token";
StaticJsonBuffer<1000> jb;
String res;
Serial.println("conntecting to server..");
if (https.begin(client, host, port, path)) {
https.addHeader("Content-Type", "x-www-formurlencoded");
int httpsCode = https.POST("grant_type=client_credentials&apiKey=1d0956a4-3deb-431a-b3e0-45f5c371fe99");
if (httpsCode > 0) {
if (httpsCode == HTTP_CODE_OK) {
JsonObject& obj = jb.parseObject(https.getString());
String token = obj["access_token"];
if (obj.success()) {
res = token;
} else {
res = "failed to parse json";
}
}
} else {
res = "failed to Post";
}
} else {
res = "failed to connect to server";
}
https.end();
return res;
}
Check out the guideline documentation and please read the authentication part. I have followed the steps and tried in several ways, but still no luck.
But my API code and others parameter are ok. I have tried API post method from Mozilla Firefox addon and different platform. From everywhere I got the token successfully. But I am still unable to get the token with my code.
Please check and me a solution regarding the issue.
Use these libraries. ESPAsyncTCP, asyncHTTPrequest
then use below code. Code for sample.
#include <ESPAsyncTCP.h>
#include <asyncHTTPrequest.h>
asyncHTTPrequest client;
asyncHTTPrequest client2;
void onClientStateChange(void * arguments, asyncHTTPrequest * aReq, int readyState) {
Serial.println(readyState);
switch (readyState) {
case 0:
// readyStateUnsent // Client created, open not yet called
break;
case 1:
// readyStateOpened // open() has been called, connected
break;
case 2:
// readyStateHdrsRecvd // send() called, response headers available
break;
case 3:
// readyStateLoading // receiving, partial data available
break;
case 4:
// readyStateDone // Request complete, all data available.
#ifdef SERIAL_DEBUG
Serial.println(aReq->responseHTTPcode());
#endif
if (aReq->responseHTTPcode() != 200) {
#ifdef SERIAL_DEBUG
Serial.println("return");
#endif
return;
}
String response = aReq->responseText();
#ifdef SERIAL_DEBUG
Serial.println(response.c_str());
#endif
break;
}
}
void setupClient() {
String URL = "dummy.restapiexample.com/api/v1/create";
client.setTimeout(5);
client.setDebug(false);
client.onReadyStateChange(onClientStateChange);
client.open("POST", URL.c_str());
client.setReqHeader("Content-Type", "application/json");
client.send("{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}");
String URL2 = "jsonplaceholder.typicode.com/users";
client2.setTimeout(5);
client2.setDebug(false);
client2.onReadyStateChange(onClientStateChange);
client2.open("GET", URL2.c_str());
client2.send();
}
Always connect with async client as it will not block your main execution until you will get a response.

ESP8266 GET request not working

I am trying to send data from an Arduino Uno using ESP8266 to Firebase via PHP. The connection between the Firebase DB and PHP seems to be fine since I can manually send data to it through my browser. However, I am not able to send data from the Arduino to PHP.
Here is the Arduino code:
#include "SoftwareSerial.h"
String ssid ="xxxx";
String password="xxxx";
String server = "firstfirebase.000webhostapp.com"; // www.example.com
String uri = "/firebaseTest.php";// our example is /esppost.php
SoftwareSerial esp(2, 3);// RX, TX
void setup() {
esp.begin(9600);
Serial.begin(9600);
reset();
connectWifi();
}
void reset() {
esp.println("AT+RST");
delay(1000);
if(esp.find("OK"))
Serial.println("Module Reset");
}
void connectWifi() {
String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
esp.println(cmd);
delay(4000);
if(esp.find("OK")) {
Serial.println("Connected!");
} else {
connectWifi();
Serial.println("Cannot connect to wifi");
}
}
void loop() {
httppost();
delay(1000);
}
void httppost () {
esp.println("AT+CIPSTART=\"TCP\",\"firstfirebase.000webhostapp.com\",80");//start a TCP connection.
if( esp.find("OK")) {
Serial.println("TCP connection ready");
}
delay(1000);
String getRequest = "GET firebaseTest.php?arduino_data=56.00 HTTP/1.1\r\nHost: firstfirebase.000webhostapp.com\r\n\r\n";
String sendCmd = "AT+CIPSEND";//determine the number of caracters to be sent.
esp.print(sendCmd);
esp.println(getRequest.length() );
delay(500);
if(esp.find(">")) {
Serial.println("Sending..");
esp.print(getRequest+"\r\n\r\n");
delay(500);
esp.println("AT+CIPSTATUS");
if( esp.find("SEND OK")) {
Serial.println("Packet sent");
while (esp.available()) {
String tmpResp = esp.readString();
Serial.println(tmpResp);
}
// close the connection
esp.println("AT+CIPCLOSE");
}
}
}
Here is a screenshot of the serial monitor:
You are missing a / in front of your path.
It should be:
String getRequest = "GET /firebaseTest.php?arduino_data=56.00 HTTP/1.1\r\nHost: firstfirebase.000webhostapp.com\r\n\r\n";
The user Agent it is very important:
AT+CIPSTART="TCP","somedomain.it",80
AT+CIPSEND=EXACT NUMBER OF GET REQ
GET /Arduino/ciao.php HTTP/1.1\r\n
Host: 192.168.0.111\r\n
User-Agent: wget/1.12\r\n\r\n

Resources