I am currently testing a piece of code using arduinojson6. My goal is to store multiple ssid's and passwords to the esp32 SPIFF.
The uneddited question contained a piece of code that would append to the file rather than reading doc, deleting /SSID.json, adding to doc serialization and saving the file again like I have now, is also not the solution.
the desired json file would be:
{"information":[{ "SSID":"variable blaat1", "PASS1":"variable Abc1", "NUMBER": "1" },{ "SSID":"variable blaat2", "PASS2":"variable Abc2", "NUMBER": "2" },{ "SSID":"variable blaat3", "PASS3":"variable Abc3", "NUMBER": "3" },{ "SSID":"variable blaat4", "PASS4":"variable Abc4", "NUMBER": "4" },{ "SSID":"variable blaat5", "PASS5":"variable Abc5", "NUMBER": "5" }]}
Instead, when more then 1 value is serialized and appended it will read like this:
{
"information": {},
"test": [
"mooiman\n",
"mooiweer\n"
],
"number": [
1,
2
]
}
Maybe some of you know how to serialize it properly.
The code I test with:
#include <Arduino.h>
#include <WiFi.h>
//#include <time.h>
//#include <ESP32Ping.h>
#include "FS.h"
#include "SPIFFS.h"
//#include <HTTPClient.h>
#include <ArduinoJson.h>
int numberofInputs = 1;
String ssid = "YourSSID";
String passwords = "YourPassword";
String readString;
char FileReadBuff[1024];
DynamicJsonDocument doc(1024);
void readFile(fs::FS &fs, const char * path){
if (SPIFFS.exists("/SSID.json") == false)
{
File file = SPIFFS.open("/SSID.json", FILE_WRITE);
if (!file) {
Serial.println("There was an error opening the file for writing");
return;
}
if (file.print("SSID")) {
Serial.println("File was written");
} else {
Serial.println("File write failed");
}
file.close();
}
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return;
}
uint16_t i = 0;
Serial.println("reading");
while (file.available()) {
FileReadBuff[i] = file.read();
i++;
}
file.close();
}
void CleanFile(fs::FS &fs, const char * path, const char * message) {
for( int i = 0; i < sizeof(FileReadBuff); ++i ){
FileReadBuff[i] = (char)0;
}
File file = SPIFFS.open(path, FILE_WRITE);
if (fs.remove(path)) {
Serial.println("\r\n- file cleaned");
} else {
Serial.println("\r\n- Cleaning failed");
}
file.print(path);
}
void appendFile(fs::FS &fs, const char * path, const char * message){
if (SPIFFS.exists("/SSID.json") == false)
{
File file = SPIFFS.open("/SSID.json", FILE_WRITE);
if (!file) {
Serial.println("There was an error opening the file for writing");
return;
}
if (file.print("SSID")) {
Serial.println("File was written");
} else {
Serial.println("File write failed");
}
file.close();
}
Serial.printf("Appending to file: %s\r\n", path);
File file = fs.open(path, FILE_APPEND);
if(!file){
Serial.println("- failed to open file for appending");
return;
}
if(file.println(message)){
Serial.println("- message appended");
} else {
Serial.println("- append failed");
}
file.close();
}
void Deserialization(){
for( int i = 0; i < sizeof(FileReadBuff); ++i ){
FileReadBuff[i] = (char)0;
}
readFile(SPIFFS, "/SSID.json"); //read everything from ssid.json file
const char * JsonFF = FileReadBuff; // put everything in to const char
Serial.print("Json From File:"); Serial.println(JsonFF);
DeserializationError error = deserializeJson(doc, JsonFF);
if(error){
Serial.print(F("deserializeJson() failed: ")); Serial.println(error.f_str()); // if not legit print error
}
if(!error){
String information = doc["information"];
Serial.println(information);
information = "";
}
}
void testjson(){
readString = "";
while(readString.length() < 1) {
while (Serial.available()) {
delay(10); //small delay to allow input buffer to fill
if (Serial.available() > 0) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == ',') {
break;
} //breaks out of capture loop to print readstring
readString += c;
} //makes the string readString
}
if (readString.length() > 0) {
Serial.println(readString); //prints string to serial port out
if (readString.indexOf("READ") >= 0) {
Serial.println("reading file");
readFile(SPIFFS, "/SSID.json");
Serial.println(FileReadBuff);
for( int i = 0; i < sizeof(FileReadBuff); ++i ){
FileReadBuff[i] = (char)0;
}
}
if (readString.indexOf("DES") >= 0) { //DEZ deserialize will result in an error because json file is currently not valid
Serial.println("reading deserialized json");
Deserialization();
}
if (readString.indexOf("CLEAN") >= 0) { //CLEAN cleans the SSID.json file
Serial.println("reading deserialized json");
CleanFile(SPIFFS, "/SSID.json", "");
}
if (readString.indexOf("WRANDOM") >= 0){ //WRANDOM writes a random string to the SSID.json file
readString = "";
Serial.println("Going to write the following input:"); //waiting for user input
while(readString.length() < 1) {
while (Serial.available()) {
delay(10); //small delay to allow input buffer to fill
if (Serial.available() > 0) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == ',') {
break;
} //breaks out of capture loop to print readstring
readString += c;
} //makes the string readString
}
if (readString.length() > 0) {
Serial.println(readString); //prints string to serial port out
`here is the part we're talking about`
CleanFile(SPIFFS, "/SSID.json", "");
JsonObject information = doc.createNestedObject("information");
String SerializedJson = "";
doc["test"].add(readString);
doc["number"].add(numberofInputs);
serializeJsonPretty(doc, SerializedJson);
appendFile(SPIFFS, "/SSID.json", SerializedJson.c_str());
SerializedJson = "";
numberofInputs ++;
return;
}
}
}
}
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
if (!SPIFFS.begin(true)) {
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
if (SPIFFS.exists("/SSID.json") == false)
{
File file = SPIFFS.open("/SSID.json", FILE_WRITE);
if (!file) {
Serial.println("There was an error opening the file for writing");
return;
}
if (file.print("SSID")) {
Serial.println("File was written");
} else {
Serial.println("File write failed");
}
file.close();
}
WiFi.mode(WIFI_MODE_STA);
WiFi.begin(ssid.c_str(), passwords.c_str());
while (WiFi.status() != WL_CONNECTED) { //Check for the connection
delay(1000);
Serial.print(".");
}
Serial.println("Connected");
}
void loop() {
// put your main code here, to run repeatedly:
readString = ""; //clears variable for new input
Serial.println("Ready for new input: ");
testjson();
}
So when you serial write WRANDOM you'll get promted to put in something.
When that is recieved it will store that in json.
Do that another time.
Next when you serial write READ it will show you the saved /SSID.json.
Thanks in advance.
Note that the DynamicJsonDocument startsof empty.
PS. I know littlefs is the new spiff but lets first try to make this work (or I need to make sepperate files for every ssid+password)
Here is a test sketch you can implement to your project.
I did not had the time to write more detailed sketch than this.
Let me know if you have any question about this
#include <Arduino.h>
#include "FS.h"
#include <LittleFS.h>
#include <ArduinoJson.h>
#define DOC_SIZE 5000
/*
Example JSON :
{
"information":[
{ "SSID":"variable blaat1", "PASS1":"variable Abc1", "NUMBER": "1" },
{ "SSID":"variable blaat2", "PASS2":"variable Abc2", "NUMBER": "2" },
{ "SSID":"variable blaat3", "PASS3":"variable Abc3", "NUMBER": "3" },
{ "SSID":"variable blaat4", "PASS4":"variable Abc4", "NUMBER": "4" },
{ "SSID":"variable blaat5", "PASS5":"variable Abc5", "NUMBER": "5" }
]
}
*/
/*
When you create a JSON array, you don't need to push the index of the object, since you can later
ask for the array size, therefor you know the indexes. Also you don't need to separate the passwords
like PASS1 or PASS2 since every cred is a separate object.
*/
void addCredentials( const char* SSID, const char* PW ){
// Create a static JSON document.
StaticJsonDocument fileDoc(DOC_SIZE);
// Open the file containing the credentials
File credFile = LittleFS.open(FILE_PATH,FILE_READ);
// Check if it opened.
if( !credFile ){ Serial.println("Failed to open file"); return; }
// Deserialize the file
DeserializationError error = deserializeJson(fileDoc, credFile );
// Check if the deserialization has any errors.
if( error ){ Serial.printf("Error on deserialization: %s\n", error.c_str() );
// Get the info array from the JSON.
JsonArray infoArr = fileDoc["information"].as<JsonArray>();
// Create a new object inside the array.
JsonObject newCred = infoArr.createNestedObject();
// Add credentials to the object.
newCred["SSID"] = SSID;
newCred["PASS"] = PW;
// Serialize everythig back to the file.
serializeJson(fileDoc, credFile);
// Close the file.
credFile.close();
}
// Open the file and put the pretty json into the serial directly.
void printFileContent(){
File credFile = LittleFS.open(FILE_PATH,FILE_READ);
if( !credFile ){ Serial.println("Failed to open file"); return; }
serializeJsonPretty(Serial, credFile);
credFile.close();
}
void clearFile(){
if( !LittleFS.exists(FILE_PATH) ){ Serial.println("Credentials file does not exists yet!"); return; }
File credFile = LittleFS.open(FILE_PATH,FILE_READ);
credFile.remove();
}
void getUserInput(){
if( !Serial.available() ){ return; }
// Get the credentials or whatever from the serial
// and call the **addCredentials( const char* SSID, const char* PW );** function.
}
void setup() {
Serial.begin(115200);
}
void loop() {
getUserInput();
}
I got it figured out with help from Dr.Random. It wasn't the full answer but it helped getting the json format and apend to that file correctly. The following code is a working example.
#include <Arduino.h>
#include <WiFi.h>
#include "FS.h"
#include "LittleFS.h"
#include <ArduinoJson.h>
#define FORMAT_LITTLEFS_IF_FAILED true
#define DOC_SIZE 5000
#define FILE_PATH "/SSID.json"
String ssid = "yourssid";
String passwords = "yourpass";
String readString;
char FileReadBuff[1024];
void readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return;
}
Serial.println("- read from file:");
while(file.available()){
Serial.write(file.read());
}
file.close();
}
void Showone(int wichone){
DynamicJsonDocument doc(DOC_SIZE);
File credFile = LittleFS.open(FILE_PATH, FILE_READ);// open file for reading
DeserializationError error = deserializeJson(doc, credFile);// deserialize json
if( !credFile ){ Serial.println("Failed to open file"); return; }// if file doesn't exist, return
const char* SSID = doc[wichone]["SSID"]; //
const char* PASS = doc[wichone]["PASS"]; //
Serial.print("SSID and PASS = "); Serial.print(SSID); Serial.print(PASS); Serial.print(" "); Serial.println(" ");
credFile.close();
}
void addCredentials(const char * input){
DynamicJsonDocument doc(DOC_SIZE);// create json doc
String Serialized; // create string to store serialized json
File credFile = LittleFS.open(FILE_PATH, FILE_READ);// open file for reading
if( !credFile ){ Serial.println("Failed to open file"); return; }// if file doesn't exist, return
DeserializationError error = deserializeJson(doc, credFile);// deserialize json
if( error ){ Serial.printf("Error on deserialization: %s\n", error.c_str() );} //error when spiff is empty or not formatted correctly
JsonArray inforArr = doc["information"].as<JsonArray>();// get array from json
JsonObject newCred = doc.createNestedObject();// create new object in json
newCred["SSID"] = input;
newCred["PASS"] = input;
serializeJsonPretty(doc, Serialized);
Serial.print("input = "); Serial.println(input);
Serial.print("Serialized: "); Serial.println(Serialized);
File credFile2 = LittleFS.open(FILE_PATH, FILE_WRITE);// open file for writing
credFile2.print(Serialized);
credFile2.close();
credFile.close();
Serialized = "";
}
void testjson(){
readString = "";
while(readString.length() < 1) {
while (Serial.available()) {
delay(10); //small delay to allow input buffer to fill
if (Serial.available() > 0) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == ',') {
break;
} //breaks out of capture loop to print readstring
readString += c;
} //makes the string readString
}
if (readString.length() > 0) {
Serial.println(readString); //prints string to serial port out
if (readString.indexOf("READ") >= 0) {
Serial.println("reading file");
readFile(LittleFS, "/SSID.json");
Serial.println(FileReadBuff);
for( int i = 0; i < sizeof(FileReadBuff); ++i ){
FileReadBuff[i] = (char)0;
}
}
if (readString.indexOf("SHOW") >= 0) {
readString = "";
Serial.println("Showing the following input(number): "); //waiting for user input
while(readString.length() < 1) {
while (Serial.available()) {
delay(10); //small delay to allow input buffer to fill
if (Serial.available() > 0) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == ',') {
break;
} //breaks out of capture loop to print readstring
readString += c;
} //makes the string readString
}
if (readString.length() > 0) {
Serial.println(readString); //prints string to serial port out
Showone(readString.toInt());
}
}
}
if (readString.indexOf("CLEAN") >= 0) { //CLEAN cleans the SSID.json file
Serial.println("reading deserialized json");
File credFile = LittleFS.open(FILE_PATH, FILE_WRITE);// open file for writing
credFile.print("");
credFile.close();
}
if (readString.indexOf("WRANDOM") >= 0){ //WRANDOM writes a random string to the SSID.json file
readString = "";
Serial.println("Going to write the following input:"); //waiting for user input
while(readString.length() < 1) {
while (Serial.available()) {
delay(10); //small delay to allow input buffer to fill
if (Serial.available() > 0) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == ',') {
break;
} //breaks out of capture loop to print readstring
readString += c;
} //makes the string readString
}
if (readString.length() > 0) {
Serial.println(readString); //prints string to serial port out
addCredentials(readString.c_str());
}
}
}
}
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
if(!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)){
Serial.println("LittleFS Mount Failed");
return;
}
//if /ssid.json doesn't exist, create it littlefs
if(!LittleFS.exists(FILE_PATH)){
Serial.println("File doesn't exist, creating it");
File credFile = LittleFS.open(FILE_PATH, FILE_WRITE);
if(!credFile){
Serial.println("Failed to create file");
return;
}
credFile.close();
}
WiFi.mode(WIFI_MODE_STA);
WiFi.begin(ssid.c_str(), passwords.c_str());
while (WiFi.status() != WL_CONNECTED) { //Check for the connection
delay(1000);
Serial.print(".");
}
Serial.println("Connected");
}
void loop() {
// put your main code here, to run repeatedly:
readString = ""; //clears variable for new input
Serial.println("Ready for new input: ");
testjson();
}
Any improvements are still desirable.
I want to connect my NODEMCU wifi module to live server and then comunicate with rest API. While I was calling simple GET method with plain-text content then everything works fine, problem arises while calling POST and JSON data. Though my server API seems to work fine on ARC(Rest API testing Application).
Working With
Windows 10
Arduino IDE 1.8.12
Linux Live Server (hosted on BIGROCK)
Secure Domain (https://)
API directory permission is 755
LIVE SERVER
<?php
if (strtoupper($_SERVER['REQUEST_METHOD']) != 'POST') {
throw new Exception('Only POST requests are allowed');
}
$content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
if (stripos($content_type, 'application/json') === false) {
throw new Exception('Content-Type must be application/json');
}
$body = file_get_contents("php://input");
$object = json_decode($body, true);
if (!is_array($object)) {
throw new Exception('Failed to decode JSON object');
}
print_r($object);
?>
Arduino IDE
#include <ESP8266WiFi.h>
const char* ssid = "**********";
const char* password = "**********";
const char* host = "www.ameyakrishi.com";
void setup()
{
Serial.begin(115200);
delay(2000);
Serial.print("[Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");delay(500);
}
Serial.println(" Connected]");delay(1000);
}
void loop()
{
WiFiClient client;
Serial.print("[Connecting to "); Serial.print(host);delay(500);
if (client.connect(host, 80))
{
Serial.println(" Connected]");delay(1000);
String postData = "{\"key\":\"papa\",\"val\":999}";
client.print(String("POST /automation/app.php") + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/json \r\n" +
"Content-Length: " + postData.length() + "\r\n" +
"Connection: close\r\n" +
"\r\n"
);
while (client.connected() || client.available())
{
if (client.available())
{
String line = client.readStringUntil('\n');
Serial.println(line);
}
}
client.stop();
Serial.println("\n[Disconnected]");delay(1000);
}
else
{
Serial.println("connection failed!]");delay(1000);
client.stop();
}
delay(30000);
}
Serial Monitor Output
All connections are succeed and then print the 500 Internal Server Error response in format.
Our project has two servers if one server is closed then it should connect to the another one. But I'm getting this error while doing so. It is not connecting either.
WARN:oejw.WebAppContext:Thread-5113: Failed startup of context o.e.j.w.WebAppContext#1b14e897{/,file:///cots/ENet/webserver/webapps/cgiAdapter/,UNAVAILABLE}+
java.lang.NullPointerException+
at org.eclipse.jetty.webapp.MetaInfConfiguration.scanJars(MetaInfConfiguration.java:143)+
at org.eclipse.jetty.webapp.MetaInfConfiguration.preConfigure(MetaInfConfiguration.java:102)+
at org.eclipse.jetty.webapp.WebAppContext.preConfigure(WebAppContext.java:506)+
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:544)+
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)+
at geh.appserver.webserver.WebServerManager.systemInfoChanged(WebServerManager.java:681)+
at geh.appserver.AppServerController.sendSystemInformation(AppServerController.java:12344)+
at geh.appserver.AppServerBrokerImpl.sendSystemInformation(AppServerBrokerImpl.java:966)+
at geh.agent.XaDynamicDataManager$48.run(cd ME:13666)
java.lang.IllegalStateException: STARTED
Here's the code:
public void systemInfoChanged(boolean inStandbyMode) {
logger.log(Logger.INFO, "systemInfoChanged - inStandbyMode = " + inStandbyMode);
for (Iterator i = connectorList.iterator(); i.hasNext();) {
WebServerConnector wsc = (WebServerConnector) i.next();
if (inStandbyMode) {
logger.log(Logger.DEBUG, "SHUTDOWN SISO CONTEXTS FOR ADDRESS [ " + wsc.getAddress() + " ] PORT [ "
+ wsc.getPort() + " ]");
if (sisoContexts != null)
{
for (int c = 0; c < sisoContexts.getHandlers().length; c++) {
try {
sisoContexts.getHandlers()[c].stop();
} catch (Exception e) {
logger.log(Logger.ERROR, "Error occurred while stopping handler");
e.printStackTrace();
}
allContexts.removeHandler(sisoContexts.getHandlers()[c]);
}
sisoContexts = new ContextHandlerCollection();
sisoContexts.setHandlers(new Handler[] {}); //empty handler collection
sisoUp = false;
}
} else {
logger.log(Logger.DEBUG, "STARTUP SISO CONTEXTS FOR ADDRESS [ " + wsc.getAddress() + " ] PORT [ "
+ wsc.getPort() + " ]");
WebAppContext cgiContext = new WebAppContext();
cgiContext.setDescriptor(root + fileSeparator + "webapps" + fileSeparator + "cgiAdapter" + "/WEB-INF/web.xml");
cgiContext.setResourceBase(root + fileSeparator + "webapps" + fileSeparator + "cgiAdapter");
cgiContext.setAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
if (!sisoUp) {
try {
cgiContext.start(); // start handler before adding back
// to the server
allContexts.addHandler(cgiContext);
sisoContexts.addHandler(cgiContext);
sisoUp = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
I'm quite new to messing up with esp's, i've managed - USING ARDUINO IDE- to create a local page with buttons on it, one directs me to my local server and the other is the subject of my question, I need it to redirect me to a URI that is constantly changing, the URI is acquired from an arduino through serial connection any help would be much appreciated, thanks in advance
this is my code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* ssid = "SSID";
const char* password = "PASSWORD";
ESP8266WebServer server(80);
//Check if header is present and correct
bool is_authentified(){
Serial.println("Enter is_authentified");
if (server.hasHeader("Cookie")){
Serial.print("Found cookie: ");
String cookie = server.header("Cookie");
Serial.println(cookie);
if (cookie.indexOf("ESPSESSIONID=1") != -1) {
Serial.println("Authentification Successful");
return true;
}
}
Serial.println("Authentification Failed");
return false;
}
//login page, also called for disconnect
void handleLogin(){
String msg;
if (server.hasHeader("Cookie")){
Serial.print("Found cookie: ");
String cookie = server.header("Cookie");
Serial.println(cookie);
}
if (server.hasArg("DISCONNECT")){
Serial.println("Disconnection");
server.sendHeader("Location","/login");
server.sendHeader("Cache-Control","no-cache");
server.sendHeader("Set-Cookie","ESPSESSIONID=0");
server.send(301);
return;
}
if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")){
if (server.arg("USERNAME") == "98710" && server.arg("PASSWORD") == "hussein" ){
server.sendHeader("Location","/");
server.sendHeader("Cache-Control","no-cache");
server.sendHeader("Set-Cookie","ESPSESSIONID=1");
server.send(301);
Serial.println("Log in Successful");
return;
}
msg = "invalid username/password please try again";
Serial.println("Log in Failed");
}
String content = "<center><div id=\"ucPageViewer_ctl00_TopHead\"><div id=\"ucPageViewer_ctl00_ctl03_dvBody\" class=\"\"><div id=\"ucPageViewer_ctl00_ctl03_ctl00_containerid\"><img border=\"0\" alt=\"main page\" src=\"http://www.ungift.org/images/knowledgehub/logos/usaid-logo.jpeg\" width=\"930\" height=\"110\"></div></div></div></center>";
content += "<center></center> ";
content += "<center></center>";
content += "<center><html><body><form action='/login' method='POST'>please enter your info to be able to login<br></center>";
content += "<center>Username:<input type='text' name='USERNAME' placeholder='Username'><br></center>";
content += "<center>Password:<input type='password' name='PASSWORD' placeholder='Password'><br></center>";
content += "<center><input type='submit' name='SUBMIT' value='sign in'> </form>" + msg + "<br></center>";
content += "<center>for more info<a href='/inline'>press here</a></body> </html></center>";
server.send(200, "text/html", content);
}
//root page can be accessed only if authentification is ok
void handleRoot(){
Serial.println("Enter handleRoot");
String header;
if (!is_authentified()){
server.sendHeader("Location","/login");
server.sendHeader("Cache-Control","no-cache");
server.send(301);
return;
}
String content = "<center><div id=\"ucPageViewer_ctl00_TopHead\"><div id=\"ucPageViewer_ctl00_ctl03_dvBody\" class=\"\"><div id=\"ucPageViewer_ctl00_ctl03_ctl00_containerid\"><img border=\"0\" alt=\"main page\" src=\"http://www.ungift.org/images/knowledgehub/logos/usaid-logo.jpeg\" width=\"930\" height=\"110\"></div></div></div></center>";
if (server.hasHeader("User-Agent")){
}
content += "<center><img crossorigin=\"anonymous\" src=\"https://upload.wikimedia.org/wikipedia/ar/b/bf/Yarmouk_University_Logo.png \"width=\"168\" height=\"250\"</center>";
content += "<h1><center>hi there</center></h1>";
content += "<center><p><button>go to link from serial </button></p></center>";
content += "<center><p>browse server <button>ON</button></p></center>";
content += "please sign out before leaving sign out</body></html>";
server.send(200, "text/html", content);
}
//no need authentification
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/login", handleLogin);
server.on("/inline", [](){
String MGS = "<h1><center>please enter valid username and password</center></h1>";
MGS += "to go back to login page please press `enter code here`here</body></html>";
server.send(200, "text/html", MGS );
});
server.on("/search", [](){
String T = "";
T = Serial.readString();
Serial.print(T);
server.send(200, "text/html", T );
});
server.onNotFound(handleNotFound);
//here the list of headers to be recorded
const char * headerkeys[] = {"User-Agent","Cookie"} ;
size_t headerkeyssize = sizeof(headerkeys)/sizeof(char*);
//ask server to track these headers
server.collectHeaders(headerkeys, headerkeyssize );
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}
I am writing a windows phone 8 application.
I am seeing the following error:
A first chance exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll
I have zoned the code that causes this error, but i am not able to fix it. Feel free to help me out here
public void getTheWholeChapter(string startbooknum, string startchapter)
{
System.Uri uri = new Uri("http://api.seek-first.com/v1/BibleSearch.php?type=lookup&appid=seekfirst&startbooknum=" + startbooknum + "&startchapter=" + startchapter + "&startverse=1&endbooknum=" + startbooknum + "&endchapter=" + startchapter + "&endverse=5000000&version=KJV");
WebClient client = new WebClient();
OpenReadCompletedEventHandler orceh = new OpenReadCompletedEventHandler(GetTheData);
client.OpenReadCompleted += orceh;
client.OpenReadAsync(uri);
}
private void GetTheData(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
StreamReader reader = new StreamReader(e.Result);
string stringXML = reader.ReadToEnd().ToString();
ListBox tb = new ListBox();
//tb.IsGroupingEnabled = true;
//tb.HideEmptyGroups = true;
//tb.LayoutMode = LongListSelectorLayoutMode.List;
tb.FontSize = 25;
List<TextBlock> listOfVerses = new List<TextBlock>();
//get the deatails from the
if (stringXML != "" && stringXML != null)
{
XDocument root = XDocument.Parse("<Document>" + stringXML.Replace("></a>", "/></a>") + "</Document>");
var ResultsX = from Results in root.Descendants("Result")
select Results;
foreach (var Result in ResultsX)
{
listOfVerses.Add(new TextBlock()
{
Text = Result.Element("Chapter").Value + ":" + Result.Element("Verse").Value + " " + Result.Element("Text").Value,
TextWrapping = TextWrapping.Wrap,
});
}
}
tb.ItemsSource = listOfVerses;
((PivotItem)this.chaptersPivot.Items[chaptersPivot.SelectedIndex]).Content = tb;
}
else
{
//handle this
}
//throw new NotImplementedException();
}