I'm a cocos2dx developer. In this code, server throws error, your data is not a GZIP format. help me on how to convert Gzip Format !
void HelloWorld::requestToserver()
{
string postData ="client side request";
// Setting HTTP Request Header
std::vector<std::string> headers;
vector<string> pHeraders;
pHeraders.push_back("Accept-Encoding:gzip");
pHeraders.push_back("Content-Type:application/json");
pHeraders.push_back("Content-Encoding:gzip");
// Creating a URL
cocos2d::extension::CCHttpRequest * request = new cocos2d::extension::CCHttpRequest();
request->setUrl("http://192.168.1.47:8080/PicL…/PlayerRecordClientInteraction");
// If you want to use GET method, replace kHttpPost to kHttpGet
request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost);
request->setResponseCallback(this, httpresponse_selector(HelloWorld::onHttpRequestCompleted));
request->setRequestData(postData, strlen(postData));
request->setHeaders(headers);
request->setTag("POST Request");
// Execute
cocos2d::extension::CCHttpClient::getInstance()->send(request);
// Release the Connection
request->release();
}
void DailyPuzzle::onHttpRequestCompleted(cocos2d::CCNode * sender, void * data)
{
HttpResponse * response = (HttpResponse *)data;
if (!response)
{
return;
}
if (0 != strlen(response->getHttpRequest()->getTag()))
{
CCLog("%s completed", response->getHttpRequest()->getTag());
}
// Check the HTTP Status Code
int statusCode = response->getResponseCode();
char statusString[64] = {};
sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
CCLog("response code: %d", statusCode);
// A connection failure
if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return;
}
// The data will be placed in the buffer.
std::vector<char> * buffer = response->getResponseData();
char * concatenated = (char *) malloc(buffer->size() + 1);
std::string s2(buffer->begin(), buffer->end());
strcpy(concatenated, s2.c_str());
}
Related
I'm trying to reach an API with AndroidNetworking lib.
Here is how I initalized it:
public class TestLabApp extends Application {
#Override
public void onCreate() {
super.onCreate();
//For logging
RealInterceptor realInterceptor = new RealInterceptor();
realInterceptor.enableLoggingForBody(true);
realInterceptor.enableLoggingForUrl(true);
realInterceptor.enableLoggingForHeaders(true);
realInterceptor.enableLoggingForHttpStatusCodes(true);
realInterceptor.enableLoggingForExecutionTime(false);
//Add logging to okHttpClient
OkHttpClient okHttpClient = new OkHttpClient()
.newBuilder()
.addNetworkInterceptor(realInterceptor)
.build();
//Init AndroidNetworking lib with the okHttpClient (with aloggint interceptor)
AndroidNetworking.initialize(getApplicationContext(), okHttpClient);
}
}
I've added this to the manifest too:
<application
android:name=".TestLabApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:networkSecurityConfig="#xml/network_security_config"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
This is my own interceptor, because the one in the doc's example is simply not part of the lib.
public class RealInterceptor implements Interceptor {
private boolean logUrl = true;
private boolean logBody = true;
private boolean logHeaders = true;
private boolean logHttpStatusCodes = true;
private boolean logExecutionTime = true;
public void enableLoggingForUrl(boolean logUrl) {
this.logUrl = logUrl;
}
public void enableLoggingForHeaders(boolean logHeaders) {
this.logHeaders = logHeaders;
}
public void enableLoggingForBody(boolean logBody) {
this.logBody = logBody;
}
public void enableLoggingForHttpStatusCodes(boolean logHttpStatusCodes) {
this.logHttpStatusCodes = logHttpStatusCodes;
}
public void enableLoggingForExecutionTime(boolean logExecutionTime) {
this.logExecutionTime = logExecutionTime;
}
private void logInfo(Object o) {
Log.i(getClass().getSimpleName(), o.toString());
}
private void logError(Object o) {
Log.e(getClass().getSimpleName(), o.toString());
}
#Override
public Response intercept(Chain chain) throws IOException {
StringBuilder sb = new StringBuilder();
Request request = chain.request();
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
if (logUrl) {
sb.append("\nURL: " + request.url());
}
if (logBody) {
if (hasRequestBody) {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
String bodyParams = buffer.readString(Charset.forName("UTF-8"));
bodyParams = bodyParams.replace("&", "\nParam: ");
sb.append("\nParam: " + bodyParams);
} else {
sb.append("\nParam: <No params>");
}
}
if (logHeaders) {
Headers headers = request.headers();
String headersStr = "";
for (int i = 0, count = headers.size(); i < count; i++) {
headersStr += "\nHeader: " + headers.name(i) + ": " + headers.value(i);
}
sb.append(headersStr);
}
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
throw e;
}
if (logHttpStatusCodes) {
sb.append("\nHTTP Status code: " + response.code());
}
long tookSec = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startNs);
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
if (logExecutionTime) {
if (tookSec > 1) {
sb.append("\nExecution time: " + tookSec + " sec");
} else {
sb.append("\nExecution time: " + tookMs + " ms");
}
}
if (response.code() != 200) {
logError(sb.toString());
} else {
logInfo(sb.toString());
}
return response;
}
}
How I'm trying to use it:
AndroidNetworking.post("http://myurlishere.hu/api/test-result/save")
.addBodyParameter("param_1", "12345")
.addBodyParameter("param_2", "abcdef")
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
// do anything with response
Log.i("RESP___", response.toString());
codeTv.setText(getString(R.string.please_read_the_qr_code));
enableControls(true);
progressBar.setVisibility(View.INVISIBLE);
zBarScannerView.resumeCameraPreview(MainActivity.this);
Toast.makeText(MainActivity.this, "API done", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(ANError error) {
// handle error
codeTv.setText(getString(R.string.please_read_the_qr_code));
enableControls(true);
progressBar.setVisibility(View.INVISIBLE);
zBarScannerView.resumeCameraPreview(MainActivity.this);
DialogHelper.showInfo(MainActivity.this, "Error: Body: "+error.getErrorBody()+", Response: "+error.getResponse()+", Detail: "+error.getErrorDetail()+", Code: "+error.getErrorCode());
}
});
The problem is:
I don't see ANY logs about what is happening. Why?
Your code looks fine, but I can suggest alternative solution for logging
Firstly it is not necessary to create your own logging, As already package okhttp3.logging Provides HttpLoggingInterceptor which does log all the values which you expected in your RealInterceptor.
Here is an alternative solution :
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
okHttpClientBuilder!!.addInterceptor(logging)
In your case :
//Add logging to okHttpClient
var okHttpClient = OkHttpClient()
.newBuilder()
.addNetworkInterceptor(logging)
.build()
Hope this helps, in case release mode of the application you can disable logging by just adding condition:
var okHttpClientBuilder = OkHttpClient()
.newBuilder()
if (BuildConfig.DEBUG) {
okHttpClientBuilder.addNetworkInterceptor(logging)
}
var okHttpClient = okHttpClientBuilder.build()
Network Interceptors
Able to operate on intermediate responses like redirects and retries.
Not invoked for cached responses that short-circuit the network.
Observe the data just as it will be transmitted over the network.
Access to the Connection that carries the request.
I think your request have a cache and NetworkInterceptor will not working. Try to use addInterceptor instead of addNetworkInterceptor. It will work fine.
I think you might be lacking a no-args constructor, as the new keyword requires it:
public RealInterceptor() {}
Try to add it and it should return an instance. But better switch to Retrofit2 from some obviously abandoned library with roughly 200 open issues; there you can use the same Interceptor.
I did not quite understood as to why you are implementing Interceptor and making your own implementation of the Interceptor? Like do you need some custom logging features that is not provided in the library itself?
If all you need is to log headers and/or body of the request/response, the README file mentions that you can do so by simply enabling Logging.
AndroidNetworking.enableLogging(); // simply enable logging
AndroidNetworking.enableLogging(LEVEL.HEADERS); // enabling logging with level
It seems there are different levels that you can provide:
public enum Level {
/**
* No logs.
*/
NONE,
/**
* Logs request and response lines.
* <p>
* <p>Example:
* <pre>{#code
* --> POST /greeting http/1.1 (3-byte body)
*
* <-- 200 OK (22ms, 6-byte body)
* }</pre>
*/
BASIC,
/**
* Logs request and response lines and their respective headers.
* <p>
* <p>Example:
* <pre>{#code
* --> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
* --> END POST
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
* <-- END HTTP
* }</pre>
*/
HEADERS,
/**
* Logs request and response lines and their respective headers and bodies (if present).
* <p>
* <p>Example:
* <pre>{#code
* --> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
*
* Hi?
* --> END POST
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
*
* Hello!
* <-- END HTTP
* }</pre>
*/
BODY
}
Let me know if this works for you. Have a nice one :)
I'm trying to get data from the API which needs to handle aws-authentication, my question is how can I generate Authorization and X-Amz-Date?
I have to pass 3 parameter as header: Content-Type, Authorization and X-Amz-Date.
As you can find in image:
here is the function that generate Authorization String:
public static String gerateOAuthAWS(Context co) throws Exception {
JodaTimeAndroid.init(co);
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").withLocale(Locale.US);
String ZONE = "GMT";
DateTime dt = new DateTime();
DateTime dtLondon = dt.withZone(DateTimeZone.forID(ZONE)).plusHours(1);
String formattedDate = dtLondon.toString(fmt);
String oauth = "AWS4-HMAC-SHA256 Credential="+ ACCESS_KEY+"/us-east-1/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature="+
getSignatureKey(SECRET_KEY,formattedDate,"us-east-1","execute-api");
return oauth;
}
static byte[] HmacSHA256(String data, byte[] key) throws Exception {
String algorithm="HmacSHA256";
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
return mac.doFinal(data.getBytes("UTF8"));
}
static String getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
byte[] kDate = HmacSHA256(dateStamp, kSecret);
byte[] kRegion = HmacSHA256(regionName, kDate);
byte[] kService = HmacSHA256(serviceName, kRegion);
byte[] kSigning = HmacSHA256("aws4_request", kService);
return Base64.encodeToString(kSigning,Base64.DEFAULT).replaceAll("\n", "");
}
Content-Type is "application/x-www-form-urlencoded"
and generate X-Amz-Date something as: "201805138T120046Z"
then pass them through retrofit methods:
#GET("prod/video")
Call<ArrayList<Video>> getAllVideos(#Header("Content-Type")String content_type,
#Header("X-Amz-Date")String amz_date,
#Header("Authorization")String auth);
the result returns null and I'm sure the issue is related the authorization since it worked before well.
thanks for your helps :)
i always said to my friends why do you use retrofit or valley , if it's seems complicated to you !
instead you can use JSOUP or OKHTTP it's much easier and I realy love JSOUP
an example that you can connect and send you data:
private void fcmIdentity(final String fcmKey) {
new Thread(new Runnable() {
#Override
public void run() {
try {
SSLHelper.enableSSLSocket();
Connection.Response response = Jsoup
.connect(Urls.identity)
.header("Accept", "application/json")
.header("KEY_2", "VALUE_2")
.method(Connection.Method.POST)
.ignoreContentType(true)
.ignoreHttpErrors(true)
.validateTLSCertificates(true)
.followRedirects(true)
.data("fcm", "" + fcmKey)
.data("identity", preferences.getString("FCM_ID", ""))
.execute();
Log.i("fcmIdentity", response.statusCode() + "");
Log.i("fcmIdentity", response.toString());
Log.d("fcmIdentity", response.headers().toString());
Log.i("fcmIdentity", response.body());
} catch (Exception e) {
e.printStackTrace();
if (e instanceof IOException) {
G.toast(getString(R.string.connection_error), true);
}
}
}
}).start();
}
about SSLHelper it help to connect to HTTPS
for more info check my topic https://answers.uncox.com/android/question/13003
I wonder if it's possible to send push notifications to android mobile devices whenever Firebase gets added a new child on specific entity.
For example, let's say there's an entity on Firebase called Tasks. Whenever a new task is added to that firebase collection the "child_added" event is fired and then, in some way, a push notification is sent to a mobile client.
The trigger is the child_added event. However, I'm not sure if is feasible sending push notification right from Firebase events.
You can make a very simple node.js server or a java servlet (based on your language preferences) then using firebase server sdk you can add childEventListener. When value changes you can use FCM to send push notifications using http protocol. I am using this in my app and it is very feasable and reliable.
Note: If you are using this flow for an android app then using java server sdk will be beneficial as it is almost similar to what you have on android.
EDIT: After getting some spotlight on this answer I thought to share some more info regarding same.
//example node.js server as seen on this official firebase blog
var firebase = require('firebase');
var request = require('request');
var API_KEY = "..."; // Your Firebase Cloud Server API key
firebase.initializeApp({
serviceAccount: ".json",
databaseURL: "https://.firebaseio.com/"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child('notificationRequests');
ref.on('child_added', function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
request.ref().remove();
}
);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/user_'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
//example test java servlet which I made just to demonstrate this use case
#WebServlet("/TestServlet")
public class MainServlet extends HttpServlet {
* #see HttpServlet#HttpServlet()
*/
public MainServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get context and then relative path to saved json config file from
// firebase
ServletContext context = getServletContext();
String fullPath = context.getRealPath(FILE_PATH_FOR_JSON_SERVER_AUTH);
// Check if we actually got a file from above path
if (fullPath != null) {
} else {
}
// Setup connection to firebase database here
FirebaseOptions options = new FirebaseOptions.Builder().setServiceAccount(new FileInputStream(fullPath))
.setDatabaseUrl(FIREBASE_DATABSE_URL).build();
// Check to make sure we don't initialize firebase app each time webpage
// is refreshed
if (!exists) {
// If firebase app doesn't exist then initialize it here and set
// exists to true
FirebaseApp.initializeApp(options);
exists = true;
}
// Call this to begin listening *notify* node in firebase database for notifications
addNotificationListener(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Build apache httpclient POST request
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(ENDPOINT_URL);
//Get the required id stored in lastMsgId tree map here
if (!(chatLogs.getLastMsgIdTreeMap().isEmpty())) {
sendToID = chatLogs.getLastMsgIdTreeMap().firstKey();
lstmsg = chatLogs.getLastMsgIdTreeMap().get(sendToID);
}
//Set up a unique id with concatenating sendToID and lstmsg
uniqueID = sendToID + lstmsg;
//Set up a previous id to check with unique id. To avoid instant duplicate notifications
previousID = fcmHelper.getPreviousid();
// Check uniqueId and PreviousID beforeSending
if (!(uniqueID.equals(previousID))) {
fcmHelper.setPreviousid(uniqueID);
//Check if device token and user Id hashmap is not null
if (!(userLogs.getUserIdAndFcmTokenHashMap().isEmpty())) {
//Get the device token of sendTo Id here
deviceToken = userLogs.getUserIdAndFcmTokenHashMap().get(sendToID);
// Create JSON object for downstream data/notification
JSONObject mainNotificationJsonObj = new JSONObject();
JSONObject outerBaseJsonObj = new JSONObject();
try {
// Notification payload has 'title' and 'body' key
mainNotificationJsonObj.put(TITLE, NEW_MESSAGE_RECEIVED);
mainNotificationJsonObj.put(BODY, lstmsg);
mainNotificationJsonObj.put(NOTIFICATION_SOUND, NOTIFICATION_SOUND_TYPE_DEFAULT);
//mainNotificationJsonObj.put(TAG, fcmHelper.getFcmTagId());
System.out.println("This is sentBy id =" + fcmHelper.getFcmTagId());
// This will be used in case of both 'notification' or 'data' payload
outerBaseJsonObj.put(TO, deviceToken);
// Set priority of notification. For instant chat setting
// high will
// wake device from idle state - HIGH BATTERY DRAIN
outerBaseJsonObj.put(PRIORITY_KEY, PRIORITY_HIGH);
// Specify required payload key here either 'data' or
// 'notification'. We can even use both payloads in single
// message
outerBaseJsonObj.put(NOTIFICATION, mainNotificationJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
// Setup http entity with json data and 'Content-Type' header
StringEntity requestEntity = new StringEntity(outerBaseJsonObj.toString(),
ContentType.APPLICATION_JSON);
// Setup required Authorization header
post.setHeader(AUTHORIZATION, FIREBASE_SERVER_KEY);
// Pass setup entity to post request here
post.setEntity(requestEntity);
// Execute apache http client post response
HttpResponse fcmResponse = client.execute(post);
// Get status code from FCM server to debug error and success
System.out.println(RESPONSE_CODE + fcmResponse.getStatusLine().getStatusCode());
// Get response entity from FCM server and read throw lines
BufferedReader rd = new BufferedReader(new InputStreamReader(fcmResponse.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
if (response != null) {
// Print out the response to webpage
PrintWriter out;
out = response.getWriter();
out.println(result);
System.out.println("This is Result - " + result);
}
} else {
//Abort this process if conditions not met
post.abort();
System.out.println(THIS_MSG_ALREADY_SENT);
}
}
}
/*
* This is the main method to be called to setup notifications listener on server startup
*/
private void addNotificationListener(HttpServletRequest request, HttpServletResponse response) {
//Initialize Value event listener
lastMsgListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot arg0) {
// Clear idLastMessagerecivedhash map if not null
if (lastMsgIdTreeMap != null) {
lastMsgIdTreeMap.clear();
}
//Get lastmsg to be sent as notification here
lstmsg = (String) arg0.child(LAST_MESSAGE).getValue();
//Get sendToID here
String sendToID = (String) arg0.child(SEND_TO).getValue();
//Get Sent by ID here
sentBy = (String) arg0.child(SENT_BY).getValue();
//Set fcmTag ID here
fcmHelper.setFcmTagId(sentBy);
//Check if lstmsg is not null
if (lstmsg != null) {
// Create lastmsgTimestampHashMap here
lastMsgIdTreeMap.put(sendToID, lstmsg);
}
//Check for null again
if (lastMsgIdTreeMap != null) {
chatLogs.setLastMsgIdTreeMap(lastMsgIdTreeMap);
}
try {
doPost(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError arg0) {
}
};
//Set up database reference to notify node here
messageRef = FirebaseDatabase.getInstance().getReference().child(NOTIFY);
//Add value listener to database reference here
messageRef.addValueEventListener(lastMsgListener);
}
"Java servlet is just a personal test. Some parts have been edited or removed to only give an idea about it's setup this is in no way production ready servlet please don't just copy - paste. I encourage you to understand and build your own."
Edit: you should take a look at Firebase Cloud Functions, which let you do that without having to create a Node.js server
This is the first time ever I am using multi part request to upload data on the server.I am using ion for service hit can you please let me know how can I post my data on the server?
This is my request parameter
jSON Request:
{s_id
note_name
file_name
tag_name
set_date
mark_as_done
clear_reminder
Description
media_name1
media_name2
media_name3
Count = 3 }
Along with it, I have to upload file media1, media2, media2 on same api**. Any help would be greatly appreciated.Thanks
You can't do a JSON body and a Multipart body in one HTTP request.
you can send your json as a parameter :)
// first create your json object
JsonObject object = new JsonObject();
object.addProperty("note_name", "your value goes here");
object.addProperty("description", "your description goes here");
// add other stuffs here
//create list of files to upload
List<Part> files = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
files.add(new FilePart("file" + i, new File("path of file like: storage/image/....")));
}
Ion.with(context)
.load("POST","http://example.com")
.uploadProgress(new ProgressCallback() {
#Override
public void onProgress(long downloaded, long total) {
int percent = (int) (downloaded * 100 / total);
// update your progressbar with this percent if needed
}
})
.addMultipartParts(files)
.setMultipartParameter("json", object.toString()) // your json is here
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
if (e != null) {
// error: log the message here
return;
}
if (result != null) {
// result is the response of your server
}
}
});
Hope this help you :)
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial esp8266(8,9);
void setup()
{
Serial.begin(9600);
esp8266.begin(9600);
pinMode(11,OUTPUT);
digitalWrite(11,LOW);
pinMode(12,OUTPUT);
digitalWrite(12,LOW);
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
pinMode(10,OUTPUT);
digitalWrite(10,LOW);
sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
sendCommand("AT+CWJAP=\"SSID\",\"PASSWD\"\r\n",3000,DEBUG);
delay(10000);
sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
Serial.println("Server Ready");
}
void loop()
{
if(esp8266.available()) // check if the esp is sending a message
{
if(esp8266.find("+IPD,"))
{
delay(1000);
int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
// the ASCII decimal value and 0 (the first decimal number) starts at 48
esp8266.find("pin=");
int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
int secondNumber = (esp8266.read()-48);
if(secondNumber>=0 && secondNumber<=9)
{
pinNumber*=10;
pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
}
if((pinNumber==12)&&(pinNumber!=11))
{digitalWrite(12, HIGH);
digitalWrite(11,LOW);}
if((pinNumber==11)&&(pinNumber!=12))
{digitalWrite(12, LOW);
digitalWrite(11,HIGH);}
// build string that is send back to device that is requesting pin toggle
String content;
content = "Pin ";
content += pinNumber;
content += " is ";
if(digitalRead(pinNumber))
{
content += "ON";
}
else
{
content += "OFF";
}
sendHTTPResponse(connectionId,content);
// make close command
// String closeCommand = "AT+CIPCLOSE=";
// closeCommand+=connectionId; // append connection id
// closeCommand+="\r\n";
// sendCommand(closeCommand,1000,DEBUG); // close connection
}
}
}
/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
int dataSize = command.length();
char data[dataSize];
command.toCharArray(data,dataSize);
esp8266.write(data,dataSize); // send the read character to the esp8266
if(debug)
{
Serial.println("\r\n====== HTTP Response From Arduino ======");
Serial.write(data,dataSize);
Serial.println("\r\n========================================");
}
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{
// build HTTP response
String httpResponse;
String httpHeader;
// HTTP Header
httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
httpHeader += "Content-Length: ";
httpHeader += content.length();
httpHeader += "\r\n";
httpHeader +="Connection: close\r\n\r\n";
httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
sendCIPData(connectionId,httpResponse);
}
/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend +=data.length();
cipSend +="\r\n";
sendCommand(cipSend,1000,DEBUG);
sendData(data,1000,DEBUG);
}
/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command); // send the read character to the esp8266
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
hi i have this code the esp will connect to the internet so that i can turn on or turn off led from a mobile appl i want to change it . i want the esp8266 01 ti be an access point .. i don't want to use the internet i want the phone to connect directly to the esp8266
what changes do i have to do and how can i configure esp8266 as access point
When you initialized the ESP, you configured it in Station Mode
sendCommand("AT+CWMODE=1\r\n",1000,DEBUG);
sendCommand("AT+CWJAP=\"SSID\",\"PASSWD\"\r\n",3000,DEBUG);
In order to configure in AP mode you should replace this with :
sendCommand("AT+CWMODE=2\r\n",1000,DEBUG);
See CWMODE documentation
mode:
1 means Station mode
2 means AP mode
3 means AP + Station mode