400 BAD REQUEST while sending an HTTP request using wamp localhsot - api

I am a student doing an internship as part of my college course, and I'm having a problem with using WAMP during sending an HTTP request.
I'm working on an RFID project with nodemcu8266 using arduino IDE, and I've to scan the tags and send the ID (ID of the card or the tag that the rfid scans) into my website using WAMP localhost server.
But after compiling the code I receive that problem '400 BAD REQUEST AS IT SHOWN BELOW'
here's my code for Arduino IDE:
//*******************************libraries********************************
//RFID-----------------------------
#include <SPI.h>
#include <MFRC522.h>
//NodeMCU--------------------------
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
//************************************************************************
#define SS_PIN D2 //D2
#define RST_PIN D1 //D1
//************************************************************************
`MFRC522 mfrc522(SS_PIN, RST_PIN);` // Create MFRC522 instance.
//************************************************************************
/* Set these to your desired credentials. */
const char *ssid = "..";
const char *password = "Nsssss*";
const char* device_token = "115f2dbcafdb111d ";
//************************************************************************
String URL = "http://192.168.1.105/rfidattendance/getdata.php"; //computer IP or the server domain
String getData, Link;
String OldCardID = "";
unsigned long previousMillis = 0;
//************************************************************************
void setup() {
delay(1000);
Serial.begin(115200);
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
//---------------------------------------------
connectToWiFi();
}
//************************************************************************
void loop() {
//check if there's a connection to Wi-Fi or not
if(!WiFi.isConnected()){
connectToWiFi(); //Retry to connect to Wi-Fi
}
//---------------------------------------------
if (millis() - previousMillis >= 15000) {
previousMillis = millis();
OldCardID="";
}
delay(50);
//---------------------------------------------
//look for new card
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;//got to start of loop if there is no card present
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;//if read card serial(0) returns 1, the uid struct contians the ID of the read card.
}
String CardID ="";
for (byte i = 0; i < mfrc522.uid.size; i++) {
CardID += mfrc522.uid.uidByte[i];
}
//---------------------------------------------
if( CardID == OldCardID ){
return;
}
else{
OldCardID = CardID;
}
//---------------------------------------------
// Serial.println(CardID);
SendCardID(CardID);
delay(1000);
}
//************send the Card UID to the website*************
void SendCardID( String Card_uid ){
Serial.println("Sending the Card ID");
if(WiFi.isConnected()){
HTTPClient http; //Declare object of class HTTPClient
//GET Data
getData = "?card_uid=" + String(Card_uid) + "&device_token=" + String(device_token); // Add the Card ID to the GET array in order to send it
//GET methode
Link = URL + getData;
http.begin(Link); //initiate HTTP request //Specify content-type header
int httpCode = http.GET(); //Send the request
String payload = http.getString(); //Get the response payload
// Serial.println(Link); //Print HTTP return code
Serial.println(httpCode); //Print HTTP return code
Serial.println(Card_uid); //Print Card ID
Serial.println(payload); //Print request response payload
if (httpCode == 200) {
if (payload.substring(0, 5) == "login") {
String user_name = payload.substring(5);
// Serial.println(user_name);
}
else if (payload.substring(0, 6) == "logout") {
String user_name = payload.substring(6);
// Serial.println(user_name);
}
else if (payload == "succesful") {
}
else if (payload == "available") {
}
delay(100);
http.end(); //Close connection
}
}
}
//********************connect to the WiFi******************
void connectToWiFi(){
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
delay(1000);
}
//=======================================================================
And the OUTPUT is:
16:28:00.789 -> Connecting to ..
16:28:01.398 -> .......
16:28:05.195 -> Connected
16:28:05.195 -> IP address: 192.168.1.103
16:28:08.101 -> Sending the Card ID
16:28:08.101 -> 400
16:28:08.101 -> 511749228
16:28:08.101 -> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
16:28:08.101 -> <html><head>
16:28:08.101 -> <title>400 Bad Request</title>
16:28:08.101 -> </head><body>
16:28:08.101 -> <h1>Bad Request</h1>
16:28:08.101 -> <p>Your browser sent a request that this server could not understand.<br />
16:28:08.101 -> </p>
16:28:08.148 -> <hr>
16:28:08.148 -> <address>Apache/2.4.51 (Win64) PHP/7.4.26 Server at localhost Port 80</address>
16:28:08.148 -> </body></html>
16:28:08.148 ->

Related

Why ESP32 with static IP address can't connect to internet but can ping normally?

I have connected ESP32 to WIFI, but this WIFI must fix IP address, Gateway, Subnet mask, DNS and MAC. So, I assign them and test with two codes. The first one is with a ping library and the 2nd one is with http request to Google.
Ping code
#include <WiFi.h>
#include <ESP32Ping.h>
const char* ssid = "test";
const char* password = "test";
IPAddress staticIP(172, 16, 116, 90);
IPAddress gateway(172, 16, 116, 254);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(172, 17, 10, 1);
void setup(){
Serial.begin(115200);
if (WiFi.config(staticIP, gateway, subnet, dns, dns) == false) {
Serial.println("Configuration failed.");
}
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("Connecting...\n\n");
}
Serial.print("Local IP: ");
Serial.println(WiFi.localIP());
Serial.print("Subnet Mask: ");
Serial.println(WiFi.subnetMask());
Serial.print("Gateway IP: ");
Serial.println(WiFi.gatewayIP());
Serial.print("DNS 1: ");
Serial.println(WiFi.dnsIP(0));
Serial.print("DNS 2: ");
Serial.println(WiFi.dnsIP(1));
bool success = Ping.ping("www.google.com", 3);
if(!success){
Serial.println("\nPing failed");
return;
}
Serial.println("\nPing successful.");
}
void loop(){}
Http request code
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "test";
const char* password = "test";
IPAddress staticIP(172, 16, 116, 90);
IPAddress gateway(172, 16, 116, 254);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(172, 17, 10, 1);
void setup() {
Serial.begin(115200);
if (WiFi.config(staticIP, gateway, subnet, dns, dns) == false) {
Serial.println("Configuration failed.");
}
delay(4000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("MAC address: ");
Serial.println(WiFi.macAddress());
}
void loop() {
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin("www.google.com"); //Specify the URL
int httpCode = http.GET(); //Make the request
if (httpCode > 0) { //Check for the returning code
String payload = http.getString();
Serial.println(httpCode);
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
} else {
Serial.println("WiFi lost");
}
delay(10000);
}
After I tried, output of the first one is working normally. But the 2nd one seems like it can connect to Wi-Fi only one time but can't make request after that it lost connection. I so confused pls help.
It can't connect via mqtt too.
Output 1st code
Output 2nt code

ESP32 Multitask Parameter pass through Spreadsheet

I am working for soil moisture and pressure sensor using the same baud-rate 115200 in ESP32. Plus, I execute both sensor using multitask ESP32 with 2 core. Core 1 and Core 2 for both program.
The parameter can be viewed through serial monitor however it can’t be passed through the spreadsheet. I am using IFTTT platform to connect the ESP32 into Spreadsheet.
Here my code :
#include <WiFi.h>
#include <HTTPClient.h>
TaskHandle_t Task1;
TaskHandle_t Task2;
const char * ssid = "XXXX";
const char * password = "XXXX";
String server = "http://maker.ifttt.com";
String eventName = "soil_pressure";
String IFTTT_Key = "XXXXXXXXXX";
String IFTTTUrl="https://maker.ifttt.com/trigger/soil_pressure/with/key/XXXXX";
int sensorPin = 2;
int sensorValueSoil;
int limit = 300;
int sensorValuePressure;
int value1; // soil
int value2; // pressure
void setup()
{
Serial.begin(115200);
pinMode(2, OUTPUT);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("Internet Connected !!!");
xTaskCreatePinnedToCore(
Task1code, /* Task function. */
"Task1", /* name of task. */
10000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
&Task1, /* Task handle to keep track of created task */
0); /* pin task to core 0 */
delay(500);
xTaskCreatePinnedToCore(
Task2code, /* Task function. */
"Task2", /* name of task. */
10000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
&Task2, /* Task handle to keep track of created task */
1); /* pin task to core 1 */
delay(500);
}
void Task1code( void * pvParameters )
{
Serial.print("Task1 running on core ");
Serial.println(xPortGetCoreID());
for(;;)
{
sensorValueSoil = analogRead(sensorPin);
Serial.println(sensorValueSoil);
if (sensorValueSoil<limit)
{
digitalWrite(2, HIGH);
}
else {
digitalWrite(2, LOW);
}
delay(1000);
}
}
void Task2code( void * pvParameters )
{
Serial.print("Task2 running on core ");
Serial.println(xPortGetCoreID());
for(;;)
{
sensorValuePressure = analogRead(13);
Serial.println(sensorValuePressure);
delay(1000);
}
}
void sendDataToSheet(void)
{
String url = server + "/trigger/" + eventName + "/with/key/" + IFTTT_Key + "
value1=" + String((int)value1) + "&value2="+String((int)value2);
Serial.println(url);
//Start to send data to IFTTT
HTTPClient http;
Serial.print("[HTTP] begin...\n");
http.begin(url); //HTTP
Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if(httpCode > 0)
{
// HTTP header has been send and Server
response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
}
else
{
Serial.printf("[HTTP] GET... failed, error: %s\n",
http.errorToString(httpCode).c_str());
}
http.end();
}
void loop()
{
value1 = sensorValueSoil;
value2 = sensorValuePressure;
Serial.print("Values are ");
Serial.print(value1);
Serial.print(' ');
Serial.print(value2);
Serial.print(' ');
sendDataToSheet();
delay(5000);
}
You need to pass WiFiClient object into HTTPClient arguments.
HTTPClient http;
WiFiClient client;
void sendDataToSheet(void) {
String url = server + "/trigger/" + eventName + "/with/key/" + IFTTT_Key + "value1 = " + String((int)value1) + " & value2 = " + String((int)value2);
Serial.println(url);
//Start to send data to IFTTT
Serial.print("[HTTP] begin...\n");
http.begin(client, url);
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}

After each sending data packet, I add Thread.sleep(1), why does the packet loss rate of udp drop?

Udp server
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 10086
int main() {
int server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_fd < 0) {
perror("create socket");
_exit(2);
}
int ret;
struct sockaddr_in s_addr;
s_addr.sin_family = AF_INET;
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
s_addr.sin_port = htons(PORT);
ret = bind(server_fd, (struct sockaddr *) &s_addr, sizeof(s_addr));
if (ret < 0) {
perror("bind error");
_exit(2);
}
for (;;) {
struct sockaddr_in c_addr;
socklen_t c_addr_len;
char buf[100];
int ret = recvfrom(server_fd, buf, 100, 0, (struct sockaddr *) &c_addr, &c_addr_len);
if (ret < 0) {
perror("accept error");
_exit(2);
} else {
char temp[100];
char *host2 = inet_ntoa(c_addr.sin_addr);
printf("A client connect: %d, %s, %d with msg: %s.\n", c_addr.sin_port, host2, c_addr.sin_family, buf);
}
}
}
Server listen on 10086, recvfrom a udp data packet, print client IP, port and data.
And here is client code:
public static void main(String[] args) throws IOException {
String server = "192.168.1.5";
DatagramSocket ds = new DatagramSocket();
byte[] data = "Hello".getBytes();
DatagramPacket p = new DatagramPacket(data, data.length);
p.setAddress(InetAddress.getByName(server));
p.setPort(10086);
ds.send(p);
data = "world".getBytes();
p = new DatagramPacket(data, data.length);
p.setAddress(InetAddress.getByName(server));
p.setPort(10086);
ds.send(p);
}
After run client, I get server output(tested several times, same output)
A client connect: 38394, 192.168.1.2, 2 with msg: Hello.
After I add Thread.sleep(1); after send "Hello" to server.
public static void main(String[] args) throws IOException, InterruptedException {
DatagramSocket ds = new DatagramSocket();
byte[] data = "Hello".getBytes();
DatagramPacket p = new DatagramPacket(data, data.length);
String server = "192.168.1.5";
p.setAddress(InetAddress.getByName(server));
p.setPort(10086);
ds.send(p);
Thread.sleep(1);
data = "world".getBytes();
p = new DatagramPacket(data, data.length);
p.setAddress(InetAddress.getByName(server));
p.setPort(10086);
ds.send(p);
}
After run client, I get server output(tested several times, same output)
A client connect: 38394, 192.168.1.2, 2 with msg: Hello.
A client connect: 38394, 192.168.1.2, 2 with msg: world.
I checked it with Wireshark and it's OK.
I also checked socket read buffer and it's OK.
So why is there packet loss here? There should be no buffer overflow, and the network environment is not that bad. Is there any other reason for UDP packet loss?
Thanks in advance.

ESP8266 Sniffing and sending Mac address

I'm trying to make my ESP8266 sniffing nearby devices, then posting them by with a HTTP request. With purpose is to record when my roommate and I are at home. Then in the future, trigger certain tasks like turning on/off the lights if we're home or not. I don't care at all about the packets content just the mac addresses.
So fare I've found this, script that prints out the mac adresses for nearby devices, created by kalanda: esp8266-sniffer.
Aswell as this HTTP posting script ESP8266 http get requests.
I've tried to combine those two and in the callback function make the ESP send the found data, but doesn't look like the ESP establish the wifi connection.
I tried using different WIFI modes: STATION_MODE, SOFTAP_MODE, STATIONAP_MODE. None of them worked for both sniffing and http request at the same time. I know that the STATIONAP_MODE do have some flaws. What I've found is that it has to switch both somehow, but unfortunately I'm not a ESP expert and don't know how this can be done.
Here is my code(srry for any rubbish coding on my side):
#include <ESP8266WiFi.h> // added this
#include <ESP8266HTTPClient.h> // added this
const char* ssid = "**********"; // Wifi SSID
const char* password = "**********"; // Wifi Password
String main_url = "http://*********.php?"; // Website url to post the information
String temp_url = ""; // Url with information
extern "C" {
#include <user_interface.h>
}
#define DATA_LENGTH 112
#define TYPE_MANAGEMENT 0x00
#define TYPE_CONTROL 0x01
#define TYPE_DATA 0x02
#define SUBTYPE_PROBE_REQUEST 0x04
struct RxControl {
signed rssi:8; // signal intensity of packet
unsigned rate:4;
unsigned is_group:1;
unsigned:1;
unsigned sig_mode:2; // 0:is 11n packet; 1:is not 11n packet;
unsigned legacy_length:12; // if not 11n packet, shows length of packet.
unsigned damatch0:1;
unsigned damatch1:1;
unsigned bssidmatch0:1;
unsigned bssidmatch1:1;
unsigned MCS:7; // if is 11n packet, shows the modulation and code used (range from 0 to 76)
unsigned CWB:1; // if is 11n packet, shows if is HT40 packet or not
unsigned HT_length:16;// if is 11n packet, shows length of packet.
unsigned Smoothing:1;
unsigned Not_Sounding:1;
unsigned:1;
unsigned Aggregation:1;
unsigned STBC:2;
unsigned FEC_CODING:1; // if is 11n packet, shows if is LDPC packet or not.
unsigned SGI:1;
unsigned rxend_state:8;
unsigned ampdu_cnt:8;
unsigned channel:4; //which channel this packet in.
unsigned:12;
};
struct SnifferPacket{
struct RxControl rx_ctrl;
uint8_t data[DATA_LENGTH];
uint16_t cnt;
uint16_t len;
};
static void showMetadata(SnifferPacket *snifferPacket) {
unsigned int frameControl = ((unsigned int)snifferPacket->data[1] << 8) + snifferPacket->data[0];
uint8_t version = (frameControl & 0b0000000000000011) >> 0;
uint8_t frameType = (frameControl & 0b0000000000001100) >> 2;
uint8_t frameSubType = (frameControl & 0b0000000011110000) >> 4;
uint8_t toDS = (frameControl & 0b0000000100000000) >> 8;
uint8_t fromDS = (frameControl & 0b0000001000000000) >> 9;
// Only look for probe request packets
if (frameType != TYPE_MANAGEMENT ||
frameSubType != SUBTYPE_PROBE_REQUEST)
return;
Serial.print("RSSI: ");
Serial.print(snifferPacket->rx_ctrl.rssi, DEC);
Serial.print(" Ch: ");
Serial.print(wifi_get_channel());
char addr[] = "00:00:00:00:00:00";
getMAC(addr, snifferPacket->data, 10);
Serial.print(" Peer MAC: ");
Serial.print(addr);
uint8_t SSID_length = snifferPacket->data[25];
Serial.print(" SSID: ");
printDataSpan(26, SSID_length, snifferPacket->data);
Serial.println();
if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status
{
HTTPClient http; //Declare an object of class HTTPClient
temp_url = main_url;
temp_url = temp_url + "mac=30:a8:db:96:a4:75";
temp_url = temp_url + "&rssi=-90";
temp_url = temp_url + "&ssid=none";
http.begin(temp_url); //Specify request destination
int httpCode = http.GET(); //Send the request
temp_url = "";
if (httpCode > 0)
{ //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
}
http.end(); //Close connection
}
else
{
Serial.println("Wifi connection failed"); //Prints out this
}
}
/**
* Callback for promiscuous mode
*/
static void ICACHE_FLASH_ATTR sniffer_callback(uint8_t *buffer, uint16_t length) {
struct SnifferPacket *snifferPacket = (struct SnifferPacket*) buffer;
showMetadata(snifferPacket);
}
static void printDataSpan(uint16_t start, uint16_t size, uint8_t* data) {
for(uint16_t i = start; i < DATA_LENGTH && i < start+size; i++) {
Serial.write(data[i]);
}
}
static void getMAC(char *addr, uint8_t* data, uint16_t offset) {
sprintf(addr, "%02x:%02x:%02x:%02x:%02x:%02x", data[offset+0], data[offset+1], data[offset+2], data[offset+3], data[offset+4], data[offset+5]);
}
#define CHANNEL_HOP_INTERVAL_MS 1000
static os_timer_t channelHop_timer;
/**
* Callback for channel hoping
*/
void channelHop()
{
// hoping channels 1-14
uint8 new_channel = wifi_get_channel() + 1;
if (new_channel > 14)
new_channel = 1;
wifi_set_channel(new_channel);
}
#define DISABLE 0
#define ENABLE 1
void setup() {
// set the WiFi chip to "promiscuous" mode aka monitor mode
Serial.begin(115200);
delay(10);
wifi_set_opmode(STATION_MODE);
wifi_set_channel(1);
wifi_promiscuous_enable(DISABLE);
delay(10);
wifi_set_promiscuous_rx_cb(sniffer_callback);
delay(10);
wifi_promiscuous_enable(ENABLE);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print("Connecting..");
}
Serial.println("");
Serial.println("Connected..");
// setup the channel hoping callback timer
os_timer_disarm(&channelHop_timer);
os_timer_setfn(&channelHop_timer, (os_timer_func_t *) channelHop, NULL);
os_timer_arm(&channelHop_timer, CHANNEL_HOP_INTERVAL_MS, 1);
}
void loop() {
delay(10);
}
Here's the code which aggregates probe requests (MAC addresses and RSSIs) for 3 seconds and then sends them to specified server's endpoint using json (WIFI_AP_STA mode):
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <vector>
const char* apSsid = "ap-ssid";
const char* apPassword = "ap-password";
const char* clientSsid = "client-ssid";
const char* clientPassword = "client-password";
HTTPClient http;
WiFiEventHandler probeRequestPrintHandler;
String macToString(const unsigned char* mac) {
char buf[20];
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(buf);
}
std::vector<WiFiEventSoftAPModeProbeRequestReceived> myList;
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt) {
myList.push_back(evt);
}
void setup() {
Serial.begin(115200);
Serial.println("Hello!");
// Don't save WiFi configuration in flash - optional
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(apSsid, apPassword);
WiFi.begin(clientSsid, clientPassword);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("");
probeRequestPrintHandler = WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
}
void loop() {
delay(3000);
String json = "";
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonArray& probes = root.createNestedArray("probes");
for(WiFiEventSoftAPModeProbeRequestReceived w : myList){
JsonObject& probe = probes.createNestedObject();
probe["address"] = macToString(w.mac);
probe["rssi"] = w.rssi;
}
myList.clear();
root.printTo(json);
Serial.println("json:" + json);
http.begin("http://example.com/api/v1/probe");
http.addHeader("Content-Type", "application/json");
http.POST(json);
http.end();
}
Remember to use the latest version (actually a pre-release - 2.4.0-rc1 or newer) of arduino-esp8266 library since those WiFiEvents were just recently added.
You can download ArduinoJson library using Library Manager (Sketch -> Include Library -> Manage Libraries...) if you don't have that already.

Trouble with Sending HTTP 1.1 GET request

I am trying to use PubNub to publish a message to a channel but I always get "Connection Failed!".
I know the structure of a publish URL is the following:
http://pubsub.pubnub.com/publish/<PUB-KEY>/<SUB-KEY>/0/<CHANNEL>/0/%22<MESSAGE>%22
I have tested the URL on Google Chrome and it works just fine.
The following is a C flavored code is running on an Arduino UNO + Adafruit HUZZAH CC3000 WIFI Breakout. This is not an Arduino hardware question per se, because I believe there is nothing wrong with my circuit. My issue is with the structure of the HTTP GET request created using Adafruit CC3000 Library.
I am having to go with sending a GET rather than using PubNub Arduino Library because it doesn't seem to support CC3000 WIFI module. They have a JSON WIFI and Ethernet examples but both do not communicate with the CC3000 WIFI module.
char PUBKEY[] = "XXXXXXX";
char SUBKEY[] = "XXXXXXX";
Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
if (client.connected())
{
client.print("GET /publish/");
client.print(PUBKEY);
client.print("/");
client.print(SUBKEY);
client.print("/0/");
client.print("MyPubChannel"); // Channel Name
client.print("/0/%22");
client.print("Hello World from Arduino!"); // Msg to publish
client.print("%22");
client.println(" HTTP/1.1");
client.print("Host: ");
client.println("pubsub.pubnub.com");
client.println();
}
else
{
Serial.println(F("Connection failed"));
}
I have read this page and understood that a correct GET request would be of the form:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org
I am pretty sure there is something wrong with my GET request. Can anyone look at this and provide ANY hints as to what could be going wrong?
I am finally able to connect to PubNub using the code below.
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#define ADAFRUIT_CC3000_IRQ 3 // MUST be an interrupt pin!
#define ADAFRUIT_CC3000_VBAT 5
#define ADAFRUIT_CC3000_CS 10
#define WLAN_SSID "XXXWifi"
#define WLAN_PASS "XXX"
#define WLAN_SECURITY WLAN_SEC_WPA2
#define IDLE_TIMEOUT_MS 3
uint32_t ip;
// PubNub Setup
#define WEBSITE "pubsub.pubnub.com"
#define WEBPAGE "/publish/"
char PUBKEY[] = "pub-XXXX";
char SUBKEY[] = "sub-XXXX";
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER); // you can change this clock speed
Adafruit_CC3000_Client www;
void setup(void)
{
Serial.begin(115200);
/* Initialize the module */
Serial.print(F("\n Initializing WIFI Adapter..."));
if (!cc3000.begin())
{
Serial.println(F("Couldn't begin()! Check your wiring?"));
while(1);
}
Serial.print(F("Ready!\n"));
Serial.print(F("Connecting to [")); Serial.print(WLAN_SSID);
Serial.print(F("]..."));
if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
Serial.println(F("Failed!"));
while(1);
}
Serial.print(F("Connected!\n"));
//Wait for DHCP to complete
Serial.print(F("Waiting for DHCP..."));
while (!cc3000.checkDHCP())
{
delay(100); // ToDo: Insert a DHCP timeout!
}
Serial.print(F("Done!\n"));
Serial.print(F("Resolving PubNub..."));
ip = 0;
// Try looking up the website's IP address
while (ip == 0) {
if (! cc3000.getHostByName(WEBSITE, &ip)) {
Serial.println(F("Couldn't resolve!"));
}
delay(500);
}
Serial.print(F("Resolved!\n"));
www = cc3000.connectTCP(ip, 80);
for(int i=0;i<=50;i++)
{
char buffer[4];
dtostrf(i, 4, 0, buffer);
Publish("ch2", buffer);
}
/* You need to make sure to clean up after yourself or the CC3000 can freak out */
/* the next time your try to connect ... */
Serial.println(F("\n\nDisconnecting"));
www.close();
cc3000.disconnect();
}
void loop(void)
{
delay(1000);
}
void Publish(char* CH, char* MSG)
{
if (www.connected()) {
www.fastrprint(F("GET "));
www.fastrprint(WEBPAGE);
www.fastrprint(PUBKEY);
www.fastrprint(F("/"));
www.fastrprint(SUBKEY);
www.fastrprint(F("/0/"));
www.fastrprint(CH);
www.fastrprint(F("/0/%22"));
www.fastrprint(MSG);
www.fastrprint(F("%22"));
www.fastrprint(F(" HTTP/1.1\r\n"));
www.fastrprint(F("Host: "));
www.fastrprint(WEBSITE);
www.fastrprint(F("\r\n"));
www.fastrprint(F("\r\n"));
www.println();
} else {
Serial.println(F("Connection failed"));
return;
}
//Read data until either the connection is closed, or the idle timeout is reached.
unsigned long lastRead = millis();
while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
while (www.available()) {
char c = www.read();
//Serial.print(c);
lastRead = millis();
}
}
}
char* clean(char* MSG)
{
return MSG;
}