Sending Data to WEB server: Data is being sent, but only once - mysql

This code sends data to my server, where it is being get with php and sent to mysql.
The main problem is, that I use cycle void loop(), but it does its task only once. If I will reset the Arduino, then it sends data twice and so on.. I have tried to to send multiple data with delays without a cycle, but it repeatedly sends data, that was send first.. Help :)
#include <SPI.h>
#include <Ethernet.h>
#include <stdlib.h> //Including libraries
int moi_int = 12;
int temp_int = 13; //doing some convertion
int moi_int1 = moi_int %10;
int moi_int2 = moi_int - moi_int1;
int moi_int3 = moi_int2/10;
char moi1 = (char)(((int)'0')+moi_int1);
char moi2 = (char)(((int)'0')+moi_int3);
int temp_int1 = temp_int %10;
int temp_int2 = temp_int - temp_int1;
int temp_int3 = temp_int2/10;
char temp1 = (char)(((int)'0')+temp_int1); //convertion
char temp2 = (char)(((int)'0')+temp_int3);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = { my server };
IPAddress ip(my ip);
EthernetClient client;
void setup() {
Serial.begin(9600);
}
void SendInfo() //Info
{
char string[29]; //Here is displayed by char some adress (data) I need to send
string[0] = 'G'; string[1] = 'E'; string[2] = 'T'; string[3] = ' '; string[4] = '/'; string[5] = 'a'; string[6] = 'd'; string[7] = 'd';
string[8] = '.'; string[9] = 'p'; string[10] = 'h'; string[11] = 'p'; string[12] = '?'; string[13] = 't'; string[14] = 'e'; string[15] = 'm';
string[16] = 'p'; string[17] = '1'; string[18] = '='; string[19] = temp2; string[20] = temp1; string[21] = '&'; string[22] = '&';
string[23] = 'm'; string[24] = 'o'; string[25] = 'i'; string[26] = '1'; string[27] = '='; string[28] = moi2; string[29] = moi1;
String adresas(string);
client.println(adresas); // Sending Data
client.print(" HTTP/1.1");
client.println( "Host: my server" );
client.println("Connection: close");
client.println();
}
void Connect() //Connecting
{
Ethernet.begin(mac, ip);
delay(1000);
if (client.connect(server, 80)) {
delay(1000);
SendInfo();
delay(1000);
}
else Serial.println("connection failed");
}
void loop() //Main Loop
{
Connect();
}

You should call begin() only once in the setup:
void setup() {
...
Ethernet.begin()
You call
client.connect(server, 80)
but never a matching disconnect. You need to add one of these to cleanup the connection:
if (client.connect(server, 80)) {
...
client.stop();
}
An alternate approach is to re-user the previously opened connection on each loop.
// open the connection if needed
if(!client.connected()) {
client.connect(server, 80);
}
// ensure connection is available before trying to write
if(client.connected()) {
// do something with connection
}
If you are going to be transmitting very frequent small data, then this second approach is better because less time is wasted to the open/close of the connection.

Related

How to fix no matching function for call in Arduino IDE?

This is my first time using Arduino IDE, and after replacing the jsonBuffer with jsonDOcument, as jsonBuffer was an older version, instructed by the jsonarduino website, and i have received the error message, "no matching function for call to 'ArduinoJson6171_91::BasicJsonDocument<ArduinoJson6171_91::DefaultAllocator>::BasicJsonDocument()'"
What should I do?
This is my code:
#include <FS.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <RCSwitch.h>
#include <WiFiUdp.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
#include
#ifndef CALLBACKFUNCTION_H //this is the beginning of the callbackfunction script
#define CALLBACKFUNCTION_H
#include <Arduino.h>
typedef void (*CallbackFunction) ();
#endif //this is the end of the callbackfunction script
#ifndef SWITCH_H //this is the beginning of the switch script
#define SWITCH_H
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiUDP.h>
#include "CallbackFunction.h"
class Switch {
private:
ESP8266WebServer *server = NULL;
WiFiUDP UDP;
String serial;
String persistent_uuid;
String device_name;
unsigned int localPort;
CallbackFunction onCallback;
CallbackFunction offCallback;
void startWebServer();
void handleEventservice();
void handleUpnpControl();
void handleRoot();
void handleSetupXml();
public:
Switch();
Switch(String alexaInvokeName, unsigned int port, CallbackFunction onCallback, CallbackFunction offCallback);
~Switch();
String getAlexaInvokeName();
void serverLoop();
void respondToSearch(IPAddress& senderIP, unsigned int senderPort);
};
#endif //this is the end of the switch script
#include "switch.h"
#include "UpnpBroadcastResponder.h"
#include "CallbackFunction.h"
UpnpBroadcastResponder upnpBroadcastResponder;
Switch *alexa_switch1 = NULL;
Switch *alexa_switch2 = NULL;
Switch *alexa_switch3 = NULL;
Switch *alexa_switch4 = NULL;
Switch *alexa_switch5 = NULL;
// Callback prototypes
void alexa_switch1On();
void alexa_switch1Off();
void alexa_switch2On();
void alexa_switch2Off();
void alexa_switch3On();
void alexa_switch3Off();
void alexa_switch4On();
void alexa_switch4Off();
void alexa_switch5On();
void alexa_switch5Off();
// Set Relay Pins
int relayOne = 12;
int relayTwo = 13;
int relayThree = 14;
int relayFour = 16;
// Names each relay/outlet/device is known by -- these are set during config
char alexa_name1[100] = "1";
char alexa_name2[100] = "2";
char alexa_name3[100] = "3";
char alexa_name4[100] = "4";
char alexa_name5[100] = "5";
const char* AP_Name = "EchoBase1";
char saved_ssid[100] = "";
char saved_psk[100] = "";
// Flag for saving config data
bool shouldSaveConfig = false;
bool forceConfigPortal = false;
WiFiManager wifiManager;
// RF Tooling - https://codebender.cc/sketch:80290#RCSwitch%20-%20Transmit%20(Etekcity%20Power%20Outlets).ino
RCSwitch RFSwitch = RCSwitch();
int RF_PULSE_LENGTH = 179; // Pulse length to use for RF transmitter
int RF_TX_PIN = 0; // Digital pin connected to RF transmitter
int RF_BIT_LENGTH = 24;
// RF Signals (varies per remote controlled plugin set)
unsigned long rc_codes[5][2] = {
// ON //OFF
{5313843, 5313852}, /* Outlet 1 /
{5313987, 5313996}, / Outlet 2 /
{5314307, 5314316}, / Outlet 3 /
{335107, 335116}, / Outlet 4 /
{341251, 341260}, / Outlet 5 */
};
// Callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
void setup()
{
Serial.begin(115200);
// -- WifiManager handling
// 5-second delay in case you wish to observe boot-up
for(int i=0; i < 5; i++) {
Serial.print(".");
delay(1000);
}
Serial.println("Booting");
// Clean FS, for testing... consider enabling if jumper is in flash mode, etc.
// SPIFFS.format();
// Set the flash/boot pin for input so we can read if the jumper is present
pinMode(0, INPUT);
// If the jumper is in "flash" mode (i.e., pin 0 is grounded), we will be enabling the config portal
forceConfigPortal = (digitalRead(0) == 0);
if(forceConfigPortal) {
Serial.println("Jumper set for flash - will trigger config portal");
} else {
Serial.println("Jumper set for boot - will attempt autoconnect, else config portal");
}
// Read configuration from FS json
Serial.println("Mounting ESP8266 integrated filesystem...");
if (SPIFFS.begin()) {
Serial.println("Mounted file system");
if (SPIFFS.exists("/config.json")) {
Serial.println("Found existing config; reading file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("Opened config file for reading");
size_t size = configFile.size();
Serial.print("File size (bytes) = ");
Serial.println(size);
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument jsonDocument;
JsonObject& json = jsonDocument.parseObject(buf.get());
Serial.println("Parsed JSON content:");
json.printTo(Serial);
Serial.println();
if (json.success()) {
strcpy(alexa_name1, json["alexa_name1"]);
strcpy(alexa_name2, json["alexa_name2"]);
strcpy(alexa_name3, json["alexa_name3"]);
strcpy(alexa_name4, json["alexa_name4"]);
strcpy(alexa_name5, json["alexa_name5"]);
Serial.println("Parsed Alexa relay name #1: " + String(alexa_name1));
Serial.println("Parsed Alexa relay name #2: " + String(alexa_name2));
Serial.println("Parsed Alexa relay name CharlesJGantt#3: " + String(alexa_name3));
Serial.println("Parsed Alexa relay name CharlesJGantt#4: " + String(alexa_name4));
Serial.println("Parsed Alexa relay name CharlesJGantt#5: " + String(alexa_name5));
} else {
Serial.println("** ERROR ** Failed to load/parse JSON config");
}
} else {
Serial.println("No JSON file found in filesystem");
}
}
} else {
Serial.println("** ERROR ** Failed to mount ESP8266's integrated filesyste,m");
}
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
WiFiManagerParameter custom_alexa_name1("alexa_name1", "Device #1 name", alexa_name1, 100);
WiFiManagerParameter custom_alexa_name2("alexa_name2", "Device #2 name", alexa_name2, 100);
WiFiManagerParameter custom_alexa_name3("alexa_name3", "Device CharlesJGantt#3 name", alexa_name3, 100);
WiFiManagerParameter custom_alexa_name4("alexa_name4", "Device CharlesJGantt#4 name", alexa_name4, 100);
WiFiManagerParameter custom_alexa_name5("alexa_name5", "Device CharlesJGantt#5 name", alexa_name5, 100);
// Set the function that will be called to save the custom parameter after config
wifiManager.setSaveConfigCallback(saveConfigCallback);
// Hand the parameter defintions to the WifiManager for use during config
wifiManager.addParameter(&custom_alexa_name1);
wifiManager.addParameter(&custom_alexa_name2);
wifiManager.addParameter(&custom_alexa_name3);
wifiManager.addParameter(&custom_alexa_name4);
wifiManager.addParameter(&custom_alexa_name5);
//reset settings - for testing
//wifiManager.resetSettings();
//set minimu quality of signal so it ignores AP's under that quality
//defaults to 8%
//wifiManager.setMinimumSignalQuality();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
//wifiManager.setTimeout(120);
if(forceConfigPortal) {
wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// Force config portal while jumper is set for flashing
if (!wifiManager.startConfigPortal(AP_Name)) {
Serial.println("** ERROR ** Failed to connect with new config / possibly hit config portal timeout; Resetting in 3sec...");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
} else {
// Autoconnect if we can
// Fetches ssid and pass and tries to connect; if it does not connect it starts an access point with the specified name
// and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect(AP_Name)) {
Serial.println("** ERROR ** Failed to connect with new config / possibly hit timeout; Resetting in 3sec...");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
}
// --- If you get here you have connected to the WiFi ---
Serial.println("Connected to wifi");
// Save the connect info in case we need to reconnect
WiFi.SSID().toCharArray(saved_ssid, 100);
WiFi.psk().toCharArray(saved_psk, 100);
// Read updated parameters
strcpy(alexa_name1, custom_alexa_name1.getValue());
strcpy(alexa_name2, custom_alexa_name2.getValue());
strcpy(alexa_name3, custom_alexa_name3.getValue());
strcpy(alexa_name4, custom_alexa_name4.getValue());
strcpy(alexa_name5, custom_alexa_name5.getValue());
Serial.println("Read configured Alexa relay name #1: " + String(alexa_name1));
Serial.println("Read configured Alexa relay name #2: " + String(alexa_name2));
Serial.println("Read configured Alexa relay name CharlesJGantt#3: " + String(alexa_name3));
Serial.println("Read configured Alexa relay name CharlesJGantt#4: " + String(alexa_name4));
Serial.println("Read configured Alexa relay name CharlesJGantt#5: " + String(alexa_name5));
// Save the custom parameters to the ESP8266 filesystem if changed
if (shouldSaveConfig) {
Serial.println("Saving config to ESP8266 filesystem");
DynamicJsonDocument jsonDocument;
JsonObject& json = jsonDocument.createObject();
json["alexa_name1"] = alexa_name1;
json["alexa_name2"] = alexa_name2;
json["alexa_name3"] = alexa_name3;
json["alexa_name4"] = alexa_name4;
json["alexa_name5"] = alexa_name5;
Serial.println("Attempting to open config JSON file for writing");
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("** ERROR ** Failed to open JSON config file for writing");
} else {
json.printTo(Serial);
Serial.println();
json.printTo(configFile);
configFile.close();
Serial.println("File write complete");
}
}
Serial.print("SSID: " );
Serial.println(WiFi.SSID());
Serial.print("Local IP: ");
Serial.println(WiFi.localIP());
// -- ALEXA setup/handling --
upnpBroadcastResponder.beginUdpMulticast();
// Define your switches here. Max 14
// Format: Alexa invocation name, local port no, on callback, off callback
alexa_switch1 = new Switch(alexa_name1, 80, alexa_switch1On, alexa_switch1Off);
alexa_switch2 = new Switch(alexa_name2, 81, alexa_switch2On, alexa_switch2Off);
alexa_switch3 = new Switch(alexa_name3, 82, alexa_switch3On, alexa_switch3Off);
alexa_switch4 = new Switch(alexa_name4, 83, alexa_switch4On, alexa_switch4Off);
alexa_switch5 = new Switch(alexa_name5, 85, alexa_switch5On, alexa_switch5Off);
Serial.println("Adding switches upnp broadcast responder");
upnpBroadcastResponder.addDevice(*alexa_switch1);
upnpBroadcastResponder.addDevice(*alexa_switch2);
upnpBroadcastResponder.addDevice(*alexa_switch3);
upnpBroadcastResponder.addDevice(*alexa_switch4);
upnpBroadcastResponder.addDevice(*alexa_switch5);
// Setup RF Transmitter
RFSwitch.enableTransmit(RF_TX_PIN);
RFSwitch.setPulseLength(RF_PULSE_LENGTH);
}
/* If disconnected from Wifi, enter a blocking loop that periodically attempts reconnection */
void reconnectIfNecessary() {
while(WiFi.status() != WL_CONNECTED) {
Serial.println("Disconnected; Attempting reconnect to " + String(saved_ssid) + "...");
WiFi.disconnect();
WiFi.mode(WIFI_AP_STA);
WiFi.begin(saved_ssid, saved_psk);
// Output reconnection status info every second over the next 10 sec
for( int i = 0; i < 10 ; i++ ) {
delay(1000);
Serial.print("WiFi status = ");
if( WiFi.status() == WL_CONNECTED ) {
Serial.println("Connected");
break;
} else {
Serial.println("Disconnected");
}
}
if(WiFi.status() != WL_CONNECTED) {
Serial.println("Failure to establish connection after 10 sec. Will reattempt connection in 2 sec");
delay(2000);
}
}
}
void loop()
{
// Ensure wifi is connected (won't return until it has connected)
reconnectIfNecessary();
// Respond to any Alexa/discovery requests
upnpBroadcastResponder.serverLoop();
// Respond to any UPnP control requests
alexa_switch1->serverLoop();
alexa_switch2->serverLoop();
alexa_switch3->serverLoop();
alexa_switch4->serverLoop();
alexa_switch5->serverLoop();
}
void alexa_switch1On() {
Serial.println("Switch 1 turn on ...");
enableOutlet(1, true);
}
void alexa_switch1Off() {
Serial.println("Switch 1 turn off ...");
enableOutlet(1, false);
}
void alexa_switch2On() {
Serial.println("Switch 2 turn on ...");
enableOutlet(2, true);
}
void alexa_switch2Off() {
Serial.println("Switch 2 turn off ...");
enableOutlet(2, false);
}
void alexa_switch3On() {
Serial.println("Switch 3 turn on ...");
enableOutlet(3, true);
}
void alexa_switch3Off() {
Serial.println("Switch 3 turn off ...");
enableOutlet(3, false);
}
void alexa_switch4On() {
Serial.println("Switch 4 turn on ...");
enableOutlet(4, true);
}
void alexa_switch4Off() {
Serial.println("Switch 4 turn off ...");
enableOutlet(4, false);
}
void alexa_switch5On() {
Serial.println("Switch 5 turn on ...");
enableOutlet(5, true);
}
void alexa_switch5Off() {
Serial.println("Switch 5 turn off ...");
enableOutlet(5, false);
}
void enableOutlet(int outletNumber, bool onOrOff)
{
if (outletNumber < 1 || outletNumber > 5) {
Serial.println("Invalid outlet number");
return;
}
unsigned long *onOffCodes = rc_codes[outletNumber - 1];
unsigned long codeToSend = onOffCodes[onOrOff ? 0 : 1];
RFSwitch.send(codeToSend, RF_BIT_LENGTH);
char outletNumberString[1];
int retVal = snprintf(outletNumberString, 1, "%d", outletNumber);
if (retVal < 0) {
Serial.println("Log encoding error");
return;
}
Serial.print("Switch " + String(outletNumber) + " turned ");
if (onOrOff) {
Serial.println("on");
} else {
Serial.println("off");
}
}

MQTT esp8266 client.subscribe() not working

I am working in a Iot based project in which want to store my data in to data base as well as use mqtt for communication between client and esp8266 . I tried to implement both mysql and mqtt in esp8266 node mcu. In a loop i first check if mqtt message is arrived and then update the database with sensor value.
Client.publish() works but Client.suscribe() doesnot work when update of databse is done.But when only mqtt is done it works fine.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <PubSubClient.h>
IPAddress server_addr(***, , ,); // IP of the MySQL server
char user[] = "root"; // MySQL user login username
char password[] = ""; // MySQL user login password
char ssid[] = "***"; // your SSID
char pass[] = "*****"; // your SSID Password
const char mqtt_server = "192.168.0.109";
long lastMsg = 0;
char msg[50];
int value = 0;
WiFiClient espClient;
MySQL_Connection conn((Client *)&espClient);
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, pass); // initializing the WIFI library
while ( WiFi.status() != WL_CONNECTED ) { // while loop to write dots during connecting
delay ( 500 );
Serial.print ( "." );
}
// print out information about the WIFI connection
Serial.println ( "" );
Serial.print ( "Connected to " );
Serial.println ( ssid );
Serial.print ( "IP address: " );
Serial.println ( WiFi.localIP() );
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "SAAIL");
// ... and resubscribe
client.subscribe("say");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(1000);
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
int newTemp = sht1x.readTemperatureC();
int newHum = sht1x.readHumidity();
Serial.print("temp:");
Serial.print(newTemp);
char INSERT_SQL[] = "INSERT INTO test.users (humidity,temp) VALUES (%d, %d );";
char query[255];
sprintf(query, INSERT_SQL, newHum, newTemp);
Serial.println("Recording data.");
conn.connect(server_addr, 3306, user, password);
// Initiate the query class instance
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
// Execute the query
cur_mem->execute(query);
// Note: since there are no results, we do not need to read any data
// Deleting the cursor also frees up memory used
delete cur_mem;
conn.close();
}
}
Actually, your Code is kept on moving inside a loop only and you are calling client. subscribe() inside reconnect() function. SO if your ESP8266 gets connected to MQTT Broker in a single hit then your Reconnect() will not be called.
Here is the code
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <PubSubClient.h>
IPAddress server_addr(***, , ,); // IP of the MySQL server
char user[] = "root"; // MySQL user login username
char password[] = ""; // MySQL user login password
char ssid[] = "***"; // your SSID
char pass[] = "*****"; // your SSID Password
const char mqtt_server = "192.168.0.109";
long lastMsg = 0;
char msg[50];
int value = 0;
WiFiClient espClient;
MySQL_Connection conn((Client *)&espClient);
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, pass); // initializing the WIFI library
while ( WiFi.status() != WL_CONNECTED ) { // while loop to write dots during connecting
delay ( 500 );
Serial.print ( "." );
}
// print out information about the WIFI connection
Serial.println ( "" );
Serial.print ( "Connected to " );
Serial.println ( ssid );
Serial.print ( "IP address: " );
Serial.println ( WiFi.localIP() );
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
connectmqtt();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "SAAIL");
// ... and resubscribe
client.subscribe("say");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(1000);
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
int newTemp = sht1x.readTemperatureC();
int newHum = sht1x.readHumidity();
Serial.print("temp:");
Serial.print(newTemp);
char INSERT_SQL[] = "INSERT INTO test.users (humidity,temp) VALUES (%d, %d );";
char query[255];
sprintf(query, INSERT_SQL, newHum, newTemp);
Serial.println("Recording data.");
conn.connect(server_addr, 3306, user, password);
// Initiate the query class instance
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
// Execute the query
cur_mem->execute(query);
// Note: since there are no results, we do not need to read any data
// Deleting the cursor also frees up memory used
delete cur_mem;
conn.close();
}
}
void connectmqtt()
{
client.connect("ESP8266Client");
{
Serial.println("connected");
// Once connected, publish an announcement...
// ... and resubscribe
client.subscribe("say");
client.publish("outTopic", "SAAIL");
if (!client.connected())
{
reconnect();
}
}
}

How to get all html file with a HTTP GET request using c++?

I need to create a c++ console application that query a site in turn to get the html page.
The site is static because when I queried it in the url I see the html file, so I use this code:
send(Socket, "GET /it/ricette/q-torte_forno_statico.html HTTP/1.1\r\nHost: worldrecipes.expo2015.org/\r\nConnection: close\r\n\r\n", strlen("GET /it/ricette/q-torte_forno_statico.html HTTP/1.1\r\nHost: worldrecipes.expo2015.org\r\nConnection: close\r\n\r\n"), 0);
char buffer[1000000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 1000000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
It doesn't give me any errors but don't show me the whole html page and every time that I call send the request I get different answers ... why?
This code below seems to only work on the index page worldrecipes.expo2015.org and not the sub pages. You might want to look at more advanced webbrowser controls for visual studio for parsing and processing HTML.
Like here : http://www.codeproject.com/Articles/3365/Embed-an-HTML-control-in-your-own-window-using-pla
here : https://msdn.microsoft.com/en-us/library/aa752046(v=vs.85).aspx
and here : http://www.codeproject.com/Articles/3919/Using-the-WebBrowser-control-simplified
Example code:
#include <windows.h>
#include <string>
#include <stdio.h>
using std::string;
#pragma comment(lib,"ws2_32.lib")
HINSTANCE hInst;
WSADATA wsaData;
void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename);
SOCKET connectToServer(char *szServerName, WORD portNum);
int getHeaderLength(char *content);
char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut);
int main()
{
const int bufLen = 1024;
char *szUrl = "http://worldrecipes.expo2015.org/it/ricette/q-torte_forno_statico.html";
long fileSize;
char *memBuffer, *headerBuffer;
FILE *fp;
memBuffer = headerBuffer = NULL;
if ( WSAStartup(0x101, &wsaData) != 0)
return -1;
memBuffer = readUrl2(szUrl, fileSize, &headerBuffer);
printf("returned from readUrl\n");
printf("data returned:\n%s", memBuffer);
if (fileSize != 0)
{
printf("Got some data\n");
fp = fopen("downloaded.file", "wb");
fwrite(memBuffer, 1, fileSize, fp);
fclose(fp);
// SetDlgItemText(hwndDlg, IDC_EDIT4, headerBuffer);
// SetDlgItemText(hwndDlg, IDC_EDIT5, memBuffer);
delete(memBuffer);
delete(headerBuffer);
}
WSACleanup();
return 0;
}
void mParseUrl(char *mUrl, string &serverName, string &filepath, string &filename)
{
string::size_type n;
string url = mUrl;
if (url.substr(0,7) == "http://")
url.erase(0,7);
if (url.substr(0,8) == "https://")
url.erase(0,8);
n = url.find('/');
if (n != string::npos)
{
serverName = url.substr(0,n);
filepath = url.substr(n);
n = filepath.rfind('/');
filename = filepath.substr(n+1);
}
else
{
serverName = url;
filepath = "/";
filename = "";
}
}
SOCKET connectToServer(char *szServerName, WORD portNum)
{
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
SOCKET conn;
conn = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (conn == INVALID_SOCKET)
return NULL;
if(inet_addr(szServerName)==INADDR_NONE)
{
hp=gethostbyname(szServerName);
}
else
{
addr=inet_addr(szServerName);
hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
}
if(hp==NULL)
{
closesocket(conn);
return NULL;
}
server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server.sin_family=AF_INET;
server.sin_port=htons(portNum);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
{
closesocket(conn);
return NULL;
}
return conn;
}
int getHeaderLength(char *content)
{
const char *srchStr1 = "\r\n\r\n", *srchStr2 = "\n\r\n\r";
char *findPos;
int ofset = -1;
findPos = strstr(content, srchStr1);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr1);
}
else
{
findPos = strstr(content, srchStr2);
if (findPos != NULL)
{
ofset = findPos - content;
ofset += strlen(srchStr2);
}
}
return ofset;
}
char *readUrl2(char *szUrl, long &bytesReturnedOut, char **headerOut)
{
const int bufSize = 512;
char readBuffer[bufSize], sendBuffer[bufSize], tmpBuffer[bufSize];
char *tmpResult=NULL, *result;
SOCKET conn;
string server, filepath, filename;
long totalBytesRead, thisReadSize, headerLen;
mParseUrl(szUrl, server, filepath, filename);
///////////// step 1, connect //////////////////////
conn = connectToServer((char*)server.c_str(), 80);
///////////// step 2, send GET request /////////////
sprintf(tmpBuffer, "GET %s HTTP/1.0", filepath.c_str());
strcpy(sendBuffer, tmpBuffer);
strcat(sendBuffer, "\r\n");
sprintf(tmpBuffer, "Host: %s", server.c_str());
strcat(sendBuffer, tmpBuffer);
strcat(sendBuffer, "\r\n");
strcat(sendBuffer, "\r\n");
send(conn, sendBuffer, strlen(sendBuffer), 0);
// SetWindowText(edit3Hwnd, sendBuffer);
printf("Buffer being sent:\n%s", sendBuffer);
///////////// step 3 - get received bytes ////////////////
// Receive until the peer closes the connection
totalBytesRead = 0;
while(1)
{
memset(readBuffer, 0, bufSize);
thisReadSize = recv (conn, readBuffer, bufSize, 0);
if ( thisReadSize <= 0 )
break;
tmpResult = (char*)realloc(tmpResult, thisReadSize+totalBytesRead);
memcpy(tmpResult+totalBytesRead, readBuffer, thisReadSize);
totalBytesRead += thisReadSize;
}
headerLen = getHeaderLength(tmpResult);
long contenLen = totalBytesRead-headerLen;
result = new char[contenLen+1];
memcpy(result, tmpResult+headerLen, contenLen);
result[contenLen] = 0x0;
char *myTmp;
myTmp = new char[headerLen+1];
strncpy(myTmp, tmpResult, headerLen);
myTmp[headerLen] = NULL;
delete(tmpResult);
*headerOut = myTmp;
bytesReturnedOut = contenLen;
closesocket(conn);
return(result);
}

Segfault submitting query

I'm testing a wrapper library for the MySQL C API, and I'm trying to insert a row.
I've tested it in GDB, and the line (in my code) that faults appears as follows:
Breakpoint 1, cq_query (con=0x7fffffffe1c0,
query=0x6014a0 "INSERT INTO TaskType(state,parentID,displayName) VALUES(1,19,'boop')") at cqstatic.c:32
32 return mysql_query(con->con, query);
This query string is formatted correctly (I can paste it into the mysql command line, and it runs fine), so it would appear that something is wrong in the connection (con->con is of type void * cast to MYSQL *).
My other functions which do SELECT and UPDATE work fine. Only insert appears to be broken.
Here is my Test Code
#include <stdio.h>
#include <string.h>
#include <cquel.h>
int main(void)
{
struct dbconn con = cq_new_connection("myurl.tld",
"myuser", "mypasswd", "mydb");
cq_init(1024, 128);
char *fields[] = {
"state",
"parentID",
"displayName"
};
char *vals[] = {
"1",
"19",
"boop"
};
struct drow *row = cq_new_drow(3);
cq_drow_set(row, vals);
struct dlist *list = cq_new_dlist(3, fields, "");
cq_dlist_add(list, row);
cq_insert(con, "TaskType", list);
cq_free_dlist(list);
return 0;
}
Insert Function
int cq_insert(struct dbconn con, const char *table, const struct dlist *list)
{
int rc;
char *query, *columns, *values;
const char *fmt = "INSERT INTO %s(%s) VALUES(%s)";
if (table == NULL)
return 1;
if (list == NULL)
return 2;
query = calloc(CQ_QLEN, sizeof(char));
if (query == NULL)
return -1;
columns = calloc(CQ_QLEN/2, sizeof(char));
if (columns == NULL) {
free(query);
return -2;
}
values = calloc(CQ_QLEN/2, sizeof(char));
if (values == NULL) {
free(query);
free(columns);
return -3;
}
rc = cq_dlist_fields_to_utf8(&con, columns, CQ_QLEN/2, *list);
if (rc) {
free(query);
free(columns);
free(values);
return 100;
}
rc = cq_connect(&con);
if (rc) {
free(query);
free(columns);
free(values);
return 200;
}
for (struct drow *r = list->first; r != NULL; r = r->next) {
rc = cq_drow_to_utf8(&con, values, CQ_QLEN/2, *r);
if (rc)
break;
rc = snprintf(query, CQ_QLEN, fmt, table, columns, values);
if (CQ_QLEN <= (size_t) rc) {
rc = -4;
break;
}
rc = cq_query(&con, query);
if (rc) {
rc = 201;
break;
}
}
cq_close_connection(&con);
free(query);
free(columns);
free(values);
return rc;
}
And one of the important helper functions
int cq_fields_to_utf8(struct dbconn *con, char *buf, size_t buflen,
size_t fieldc, char * const *fieldnames, bool usequotes)
{
int rc = 0;
size_t num_left = fieldc, written = 0;
if (num_left == 0)
return 1;
char *temp = calloc(CQ_FMAXLEN+3, sizeof(char));
if (NULL == temp)
return -1;
char *field = calloc((CQ_FMAXLEN+3)*2+1, sizeof(char));
if (NULL == field) {
free(temp);
return -2;
}
/* prevent appending to buffer */
buf[0] = '\0';
cq_connect(con);
for (size_t i = 0; i < fieldc; ++i) {
bool escaped = fieldnames[i][0] == '\\';
const char *orig = escaped ? &fieldnames[i][1] : fieldnames[i];
const char *value;
bool isstr = false;
if (!escaped) {
mysql_real_escape_string(con->con, field, orig, strlen(orig));
value = field;
if (usequotes)
for (size_t j = 0; j < strlen(value); ++j) {
if (!isdigit(value[j])) {
isstr = true;
break;
}
}
} else {
value = orig;
}
const char *a = isstr ? "'" : "";
const char *c = --num_left > 0 ? "," : "";
written += snprintf(temp, CQ_FMAXLEN+3, "%s%s%s%s", a, value, a, c);
if (written >= buflen) {
rc = 2;
break;
}
strcat(buf, temp);
}
cq_close_connection(con);
free(field);
free(temp);
return rc;
}
used when setting up the query string.
Found my own issue. Blame the 10 minute rule.
I didn't look closely enough at cq_insert(), and it is making a double connection, closing the second one, leaving the first one lost, and the pointer pointing to freed memory, so segfault.

Cocos2dx Web services Json

I am new in cocos2dx .. I have some doubts in json parsing . I have got messages from server .But I cant post messages to the server . here i paste the code of getmessages. Plz hel me to post messages.Thanks in Advance.
void ChatRoom::function()
{
std::vector<std::string> headers;
headers.push_back("Content-Type: application/json; charset=utf-8");
cocos2d::extension::CCHttpRequest * request = new cocos2d::extension::CCHttpRequest();
request->setUrl("url here");
const char* postData ="chatManagerRequestType=GET_MESSAGES_AFTER_CHAT_ENABLED";
request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet);
request->setResponseCallback(this, httpresponse_selector(ChatRoom::onHttpRequestCompleted));
request->setRequestData(postData, strlen(postData));
request->setHeaders(headers);
cocos2d::extension::CCHttpClient::getInstance()->send(request);
request->release();
}
void ChatRoom::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
cocos2d::extension::CCHttpResponse * response = (cocos2d::extension::CCHttpResponse *)data;
if (!response)
{
return;
} std::string command;
if (0 != strlen(response->getHttpRequest()->getTag()))
{
command = response->getHttpRequest()->getTag();
CCLog("%s completed", response->getHttpRequest()->getTag());
}
int statusCode = response->getResponseCode();
char statusString[64] = {};
sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
CCLog("response code: %d", statusCode);
if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return;
}
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());
CCLOG("%s",s2.c_str());
CCArray *arry=new CCArray();
printf("Http Test, dump data: ");
std::string tstr;
for (unsigned int i = 0; i < buffer->size(); i++)
{
char s[10];
sprintf(s, "%c",(*buffer)[i]);
tstr += (*buffer)[i];
arry->addObject((CCObject*)s);
}
for (int i=0; i<9; i++) {
cocos2d::extension::Json * jsondd = cocos2d::extension::Json_create(concatenated);
cocos2d::extension::Json *json1 = cocos2d::extension::Json_getItem(jsondd, "chatValueList");
cocos2d::extension::Json *json2 = cocos2d::extension::Json_getItemAt (json1, 0);
cocos2d::extension::Json *json3 = cocos2d::extension::Json_getItem(json2,"message");
cocos2d::extension::Json *json31 = cocos2d::extension::Json_getItem(json2,"chatId");
cocos2d::extension::Json *json4= cocos2d::extension::Json_getItem(json2,"userValue");
cocos2d::extension::Json *json5= cocos2d::extension::Json_getItem(json4,"userName");
cocos2d::extension::Json *json6= cocos2d::extension::Json_getItem(json4,"emailId");
val1 = json5->valuestring;
val2 = json3->valuestring;
val3 = json31->valueint;
CCLOG("value:%s %s %d",val1.getCString(),val2.getCString(),val3);
}
}
First of all, to post data using http you have to use kHttpPost not kHttpGet. So if you just set the request type to CCHttpRequest::kHttpPost you will be able to send your post data to server.
Second, if you are not having trouble with json then don't mention it in the question title. It misleads the users.