data says it has been sent and is seen on the apache log but the actual data is not posted. I can post data via browser using the php script i wrote so i know the php script "project0" works. in a separate script that i wrote the data is actually posted to the server during the void setup period but only once. i have also configured mysql to allow remote users access to phpmyadmin.
apache log info from esp32: 192.168.1.10 - - [21/Mar/2021:03:03:37 -0400] "GET /stringcode/project0.php?names=Jonathon Allen" 400 325 "-" "-"
apache log info from successful data post from browser: ::1 - - [20/Mar/2021:23:01:37 -0400] "GET /stringcode/project0.php?names=jonathon allen HTTP/1.1" 200 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
#include <SPI.h>
#include <MFRC522.h>
#include <WiFi.h>
#define RST_PIN 13
#define SS_PIN 23
#define WIFI_SSID "NETGEAR04"
#define WIFI_PASSWORD "huskylotus321"
MFRC522 mfrc522(SS_PIN,RST_PIN);
WiFiClient client;
String USERNAME = "";
void setup() {
Serial.begin(9600);
while(!Serial);
SPI.begin();
mfrc522.PCD_Init();
mfrc522.PCD_DumpVersionToSerial();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while(WiFi.status() != WL_CONNECTED){
Serial.println(" Trying to connect to wifi.. ");
delay(100);
}
Serial.println("connected to wifi...");
Serial.println(WiFi.localIP());
Serial.println("Ready to scan...");
}
void loop() {
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
Serial.println("UID tag is : ");
String content = "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++) // to populate content with the
string characters read from MFRC522
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX); // print what contents value is on
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.println("Message : ");
content.toUpperCase();
if(content.substring(1) == "37 07 04 D9" ){
Serial.println(" Jonathon Allen ");
USERNAME = "Jonathon Allen";
Sending_to_MYSQL();
}
if(content.substring(1) == "57 01 A2 C8" ){
Serial.println("Elijah Anies");
USERNAME = "Elijah Anies";
Sending_to_MYSQL();
}
delay(100);
}
void Sending_to_MYSQL(){
int HTTP_PORT = 80;
String HTTP_METHOD = "GET"; // or "POST"
char HOST_NAME[] = "192.168.1.11"; // hostname of web server:
String PATH_NAME = "/stringcode/project0.php?names=";
if(client.connect(HOST_NAME,HTTP_PORT)){
Serial.println("connected to server but may have not successfully sent data ");
client.println(HTTP_METHOD + " " + PATH_NAME + USERNAME + " HTTP/1.1");
client.println("Host: " + String(HOST_NAME));
client.println();
} else{
Serial.println("Did not connect to server ");
}
if(client.connected())
client.stop();
delay(500);
}
Related
Hi im currently doing Servo NodeMCU controlling. my plan is to create an Input Box where i can type, then whatever number i type will be use as servo angle using Webserver or 194.168.4.1 or so on. (ex: i type 90, servo angle will be 90) the problem i si do not know how to get it. here is the code:
#include<Servo.h>
Servo ServoPin;
int angle = 0;
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#define ServoPin 34; // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED
// Set these to your desired credentials.
const char *ssid = "XXXXXX";
const char *password = "XXXXXX";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
pinMode(ServoPin,OUTPUT);
// You can remove the password parameter if you want the AP to be open.
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("<!DOCTYPE html>");
client.print("<html>");
client.print("<body>");
client.print("<p>Change the text of the text field, and then click the button below.</p>"); //
client.print("INPUT NUMBER: <input type='number' id='servo'>"); //in this area, I WILL TYPE number 0-255.
client.print("<button type='button' '>Go</button>");
ServoPin.attach(number); //the area where i will assign the servo to the angle i type.
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
So as you can see in client.print"INPUT NUMBER.... so on line, that is the place where my code will design an input box. the problem is it is inside a " " or double quotation mark. i wonder what should i do to get the 'number' input then use it on ServoPin.attach(number);
im very beginner on HTML(zero actually) because i dont have knowledge here yet. this code is mostly taken from internet w3school website then i modify it a bit to Servo controlling. so im really hoping that someone can tell me how to do it....
Board: Node32
actual Board: NodeMCU ESP 32
Here is web server code that parses two variables from a GET response of a HTML form, I suppose it should be no problem to adopt it for your needs: http://playground.arduino.cc/Code/WebServerST
Hey so this is the how I do this, I've made a form in your html that would take the input and send a get request to the server and can be dealt with there. this is the process:
input put into form, sent to server in get request.
the get request is send stored char by char in header variable.
if statement checks if the parameter is in the header. The string is searched for the value and the value is saved into a string.
good luck this should work.
#include<Servo.h>
Servo ServoPin;
int angle = 0;
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#define ServoPin 34; // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED
// Set these to your desired credentials.
const char *ssid = "XXXXXX";
const char *password = "";
WiFiServer server(80);
String header;
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
pinMode(ServoPin,OUTPUT);
// You can remove the password parameter if you want the AP to be open.
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read();// read a byte, then
header += c; //write request to the header
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
if (header.indexOf("input1=") >= 0) { //if input1 is in the header then...
Serial.println(header);
String input_string = "";
int reqEnd = header.indexOf(" HTTP/1.1");
for (int n = 16; n < reqEnd; ++n) { //put the input value from the header to the variable
input_string += header[n];
}
Serial.println(input_string);
}
// the content of the HTTP response follows the header:
client.print("<!DOCTYPE html>");
client.print("<html>");
client.print("<body>");
client.print("<form action=\"/get\">"); //added a form to take a text input and send a get request.
client.print("input1: <input type=\"text\" name=\"input1\">");
client.print("<input type=\"submit\" value=\"Submit\">");
client.print("</form><br>");
ServoPin.attach(number); //the area where i will assign the servo to the angle i type.
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPass";
AsyncWebServer server(80);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
int paramsNr = request->params();
Serial.println(paramsNr);
for(int i=0;i<paramsNr;i++){
AsyncWebParameter* p = request->getParam(i);
Serial.print("Param name: ");
Serial.println(p->name());
Serial.print("Param value: ");
Serial.println(p->value());
Serial.println("------");
}
request->send(200, "text/plain", "message received");
});
server.begin();
}
void loop()
{}
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.
im trying to connect mysql and nodemcu with php(laravel), but when im running arduino script it come with error that i don't know. can someone help me?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include<DHT.h> DHT dht(14, DHT11);
//#define TRIGGER_PIN 5 //D1
//#define ECHO_PIN 4 //D2
const char* ssid = "PS-E3";
const char* password = "Pesona30";
const char* host = "192.168.1.19";
WiFiClient client;
const int httpPort = 80;
String url; long duration, distance;
float kelembaban, suhu;
unsigned long timeout;
void setup() {
Serial.begin(9600);
dht.begin();
delay(10);
// pinMode(TRIGGER_PIN, OUTPUT);
// pinMode(ECHO_PIN, INPUT);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void baca_suhu(){
kelembaban = dht.readHumidity();
suhu = dht.readTemperature();
Serial.print("kelembaban : ");
Serial.println(kelembaban);
Serial.print("Suhu : ");
Serial.println(suhu);
}
void loop() {
// Serial.print("baca jarak ");
// baca_jarak(); baca_suhu();
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
//return;
}
// We now create a URI for the request
url = "localhost:8000/cuaca/tampil/save/";
url += suhu;
url += "/";
url += kelembaban;
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
Serial.println();
delay(5000);
}
on that host ip already with the ip of my computer.
and the http port already same with the xampp, i dont understand why it come error
anyway this is my script in laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers;
class SimpanController extends Controller
{
public function index(){
$cuaca = DB::table('tb_cuaca')->orderBy('Kode','ASC')->paginate(10);
//passing data ke view
return view('tampilcuaca',['cuaca' => $cuaca]);
}
public function save($suhu, $kelembaban)
{
$date = date("Y-m-d");
// insert data ke table sekolah
DB::table('tb_cuaca')->insert([
'Suhu' => $suhu,
'Kelembaban' => $kelembaban,
'Tanggal' => $date
]);
// alihkan halaman ke halaman tampilsekolah
echo "berhasil";
return redirect('/tampildata');
}
public function tampildata(){
}
// public function store(Request $request)
// {
// // insert data ke table sekolah
// DB::table('tb_prestasi')->insert([
// 'Nama_Sekolah' => $request->nama,
// 'Prestasi' => $request->prestasi
// ]);
// // alihkan halaman ke halaman tampilsekolah
// return redirect('/prestasi');
// }
}
the error come like this
Connecting to PS-E3
scandone
.....scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 7
cnt
connected with PS-E3, channel 5
dhcp client start...
....ip:192.168.1.5,mask:255.255.255.0,gw:192.168.1.1
.
WiFi connected
IP address: 192.168.1.5
kelembaban : 79.00
Suhu : 29.10
connecting to 192.168.1.19
Requesting URL: localhost:8000/cuaca/tampil/save/29.10/79.00
HTTP/1.1 400 Bad Request
Date: Thu, 16 Jan 2020 05:41:33 GMT
Server: Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.9
Vary: accept-language,accept-charset
Accept-Ranges: bytes
Connection: close
Content-Type: text/html; charset=utf-8
Content-Language: en
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Bad request!</title>
<link rev="made" href="mailto:postmaster#localhost" />
<style type="text/css"><!--/*--><![CDATA[/*><!--*/
body { color: #000000; background-color: #FFFFFF; }
a:link { color: #0000CC; }
p, address {margin-left: 3em;}
span {font-size: smaller;}
/*]]>*/--></style>
</head>
<body>
<h1>Bad request!</h1>
<p>
Your browser (or proxy) sent a request that
this server could not understand.
</p>
<p>
If you think this is a server error, please contact
the webmaster.
</p>
<h2>Error 400</h2>
<address>
192.168.1.19<br />
<span>Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.9</span>
</address>
</body>
</html>
closing connection
help me
i already know what the problem is. you only need declared port 8000 only in host variable. it's get bad request because i'm using url with :8000 (because that way to use laravel with localhost). it's work and the data can record in mysql.
I've made a simple web browser using winsock2 and I have it cout the response from the server but it sends sum 21000 bytes and I need to be able to copy and paste the html, javascript, css, etc for testing the gui I made. It always fills up the terminal and I can't see where it starts I just end up in the middle of a lot of javascript. I want it to be like in the cmd where it stops and ask if you want to continue.
#include <windows.h>
#include <winsock2.h>
#include <conio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define SCK_VERSION2 0x0202
#define DEFAULT_BUFLEN 21000
#define DEFAULT_PORT 27015
namespace Globals{
string input = "";
char recvbuf[DEFAULT_BUFLEN];
const char* carf = recvbuf;
}
using namespace Globals;
HWND staticText2 = CreateWindowEx(WS_EX_PALETTEWINDOW, TEXT("Static"), TEXT("Email"), /* email */
WS_CHILD | WS_VISIBLE, 122, 80, 44, 20,
/*hwnd*/NULL, NULL, NULL, NULL);
int sck() {
//----------------------
// Declare and initialize variables.
WSADATA wsaData;
int iResult;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
char name[500] = "";
char ipADDRESS[500] = "";
char sPORT[500] = "";
sockaddr_in sName;
int sNameSize = sizeof(sName);
char const* sendbuf = "GET /?gws_rd=ssl HTTP/1.1\r\n"
"Host: www.google.com:80\r\n"
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: en-us,en;q=0.5\r\n"
//"Accept-Encoding: gzip,deflate\r\n"
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
"Keep-Alive: 300\r\n"
"Connection: keep-alive\r\n"
"Pragma: no-cache\r\n"
"DNT: 1"
"Cookie:
"Cookie:
"Cache-Control: no-cache\r\n\r\n";
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN; //23.214.132.132 GoDaddy.com
int WSAERROR = WSAGetLastError(); //190.93.243.15
//system("color 04"); //172.16.100.114 Mrs.Hall
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %i\n", WSAGetLastError() );
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
printf("IP ADDRESS: 74.125.196.191 is Google 216.58.208.37 is mail.google.com 129.66.24.10 is iNow\n");
cin >> ipADDRESS;
printf("PORT: \n");
cin >> sPORT;
//system("color 04");
u_short PORT = strtoul(sPORT, NULL, 0);
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr(ipADDRESS); //74.125.196.191
clientService.sin_port = htons(PORT); //135: msrpc, 445: microsoft-ds, 554: rtsp, 1025: NFS-or-IIS, 1026: LSA-or-nterm
//1027: IIS, 1028: uknown, 1029: ms-lsa, 139: weird behavior
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if ( iResult == SOCKET_ERROR) {
closesocket (ConnectSocket);
printf("Unable to connect to server: %i\n", WSAGetLastError());
WSACleanup();
return 1;
}
//----------------------
//Get local host name
iResult = gethostname(name, sizeof(name));
if (iResult == NO_ERROR) {
printf("Host Name: %s\n", name);
}
else if (iResult == SOCKET_ERROR) {
printf("Could not resolve host name: %i", WSAGetLastError());
}
//------------------------
//Get peer name
iResult = getpeername(ConnectSocket, (struct sockaddr*)&sName, &sNameSize);
if (iResult == NO_ERROR)
printf("Peer Name: %s\n", inet_ntoa(sName.sin_addr));
else if (iResult == SOCKET_ERROR)
printf("Could not get peer name: %i\n", WSAGetLastError());
//-------------------------
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
else
printf("Bytes Sent: %i\n", iResult);
//-----------------------------
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 ) {
printf("Bytes received: %d\n", iResult);
cout << "From Server" << recvbuf << endl;//printf("From server: %s\n", recvbuf);
}
else if ( iResult == 0 )
printf("Connection closed\n");
else if (WSAERROR == WSAETIMEDOUT)
printf("recv failed: WSAETIMEDOUT\n");
} while( iResult > 0 );
// cleanup
closesocket(ConnectSocket);
WSACleanup();
system("PAUSE");
return 0;
}
int main() {
sck();
MessageBox(NULL, "Successful", "Result:", MB_OK);
}
That's my code
Just realized all I have to do is go to the webpage and change the cookie to what I made it in my program using the EditThisCookie plugin, then copy the source. XD
I am trying to upload data from an Aurdino to Xively. I can connect to Xively and even get the PUT request showing up on the Xively Request Log.
But i get the error 400 Bad Request
{"title":"JSON Parser Error","errors":"The feed is empty"}
I think the problem may be here
data = data + "\n" + "{\"version\":\"1.0.0\",\"datastreams\" : [ {\"id\" : \"Reading\",\"current_value\" : \"" + String(reading) + "\"}]}";
Any tips would be much appreciated.
Cheers and thanks
///////////////////////
// Saving to Xively ///
///////////////////////
int savetoxively(String reading, char* feedID) {
//getting the IP address for the xively website.
ip = 0;
Serial.print(WEBSITE); Serial.print(F(" -> "));
while (ip == 0) {
if (! cc3000.getHostByName(WEBSITE, &ip)) {
Serial.println(F("Couldn't resolve!"));
}
delay(500);
}
cc3000.printIPdotsRev(ip);
// formatting the data for the xively website.
int length = 0;
String data = ""; //the problem might be here, the serial monitor says the length is 0. should have something ing it.
data = data + "\n" + "{\"version\":\"1.0.0\",\"datastreams\" : [ {\"id\" : \"Reading\",\"current_value\" : \"" + String(reading) + "\"}]}";
length = data.length();
Serial.print("Data length");
Serial.println(length);
Serial.println();
// Print request for debug purposes
Serial.print("PUT /v2/feeds/");
Serial.print(feedID); //serial monitor shows the correct feedID here
Serial.println(".json HTTP/1.1");
Serial.println("Host: api.xively.com");
Serial.print("X-ApiKey: ");
Serial.println(API_key); //serial monitor shows the correct API key
Serial.print("Content-Length: ");
Serial.println(length, DEC);
Serial.print("Connection: close");
Serial.println();
Serial.print("Reading: ");
Serial.println(reading); //serial monitor shows the correct reading
Serial.println();
// connecting with the xively server
Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
if (client.connected()) {
Serial.println("Connected!");
Serial.print("feedID: ");
Serial.println(feedID);
client.print("PUT /v2/feeds/");
client.print(feedID);
client.println(".json HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");
client.println(API_key);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(length);
client.print("Connection: close");
client.println();
client.print(data);
client.println();
Serial.println("data sent");
}
while (client.connected()) { //printing connection status
while (client.available()) { //HTTP/1.1 400 Bad Request
char c = client.read(); //Date: Sat, 15 Mar 2014 19:33:38 GMT
Serial.print(c); //Content-Type: application/json; charset=utf-8
//Content-Length: 58
//Connection: close
//X-Request-Id: f48494a26daa2a5f0979dc4460264d233103f0f5
//{"title":"JSON Parser Error","errors":"The feed is empty"}
}
}
client.close(); // closes the connection with xively
cc3000.disconnect(); //disconnects the Wifi network
return 1;
}