I am working on a very important project using Arduino Uno and SIM900 GSM Module. Basically I correctly read the ID from an RFID Card(RFID-RC522) and I need to send the ID using an URL to the Host Provider's Database(000webhost) and I need to get the OUTPUT of my query but as you will see a simple change in the code and the output is completely changed.
Here is the code for the PHP file that needs to send the OUTPUT:
<?php
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$db = "********";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_select_db($conn,$db);
date_default_timezone_set('Europe/Rome');
$date = date("Y-m-d G:i:s");
$code=$_REQUEST['code'];
$sql_u = "SELECT * FROM users WHERE code='$code'";
$res_u = mysqli_query($conn, $sql_u);
if (mysqli_num_rows($res_u) > 0)
{
echo "ALREADY EXISTENT $code";
}
else
{
$sql = "INSERT INTO users(code,used) VALUES ('$code','$date')";
if (mysqli_query($conn, $sql)) {
echo "SUCCESS $code";
} else {
echo "ERROR INSERTING $code";
}
}
mysqli_close($conn);
?>
Anyways, here is the Arduino Code:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9
#define SS_PIN 10
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
SoftwareSerial myGsm(7, 8);
String UID = "";
String pUID;
void setup() {
Serial.setTimeout(100);
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
myGsm.begin(19200);
Serial.begin(9600);
myGsm.println("AT+CGATT=1");
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"APN\",\"internet.wind\"");
printSerialData();
myGsm.println("AT+SAPBR=2,1");
printSerialData();
myGsm.println("AT+SAPBR=1,1");
printSerialData();
myGsm.println("AT+HTTPINIT");
printSerialData();
}
void loop() {
if (!mfrc522.PICC_IsNewCardPresent()) {
return;
}
if (!mfrc522.PICC_ReadCardSerial()) {
return;
}
pUID = UID;
UID = mfrc522.PICC_DumpDetailsToSerialUid(&(mfrc522.uid));
if (UID != pUID) {
Serial.print("RFID Code: ");
Serial.print(UID);
Serial.print("\n");
String url = "http://mywebsite.000webhostapp.com/test.php?code=", code = "";
url += UID;
code = "";
String httpara = "";
httpara += "AT+HTTPPARA=\"URL\",";
httpara += url;
url = "http://mywebsite.000webhostapp.com/test.php?code=";
myGsm.println(httpara); // setting the httppara,
printSerialData();
myGsm.println("AT+HTTPPARA=\"CID\",1");
printSerialData();
myGsm.println("AT+HTTPACTION=0"); //submit the GET request
//delay(8000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
myGsm.println("AT+HTTPREAD=0,20"); // read the data from the website you access
//delay(3000);
printSerialData();
}
}
void printSerialData() {
String readI = myGsm.readStringUntil("\r\n");
Serial.println(readI);
}
The OUTPUT for this code is:
AT+CGATT=1
OK
AT+SAPBR=3,1,"CONTYPE","GPRS"
OK
AT+SAPBR=3,1,"APN","internet.wind"
OK
AT+SAPBR=2,1
+SAPBR: 1,3,"X.X.X.X"
OK
AT+SAPBR=1,1
OK
RFID Code: 172D9B32
AT+HTTPPARA="URL",http://mywebsite.000webhostapp.com/test.php?code=172D9B32
OK
AT+HTTPPARA="CID",1
OK
AT+HTTPACTION=0
OK
AT+HTTPREAD=0,20
OK
If you take a closer look at the last part of the Arduino code, under the line myGsm.println("AT+HTTPACTION=0"); and under the line myGsm.println("AT+HTTPREAD=0,20"); there are some delays that almost all the other SIM900 examples use... I didn't use the delays but with the help from other people, I made it in a way that as soon as the SIM900 has an OUTPUT it just prints it out and eliminating the delay this way. It works fine for all the other commands, but for the last 2 commands it just does something random I think because it should give me the result from the echo of the php file...
NOW look if I enable the two delays:
myGsm.println("AT+HTTPACTION=0"); //submit the GET request
delay(8000);//the delay is important if the return data are very large, the time required longer.
printSerialData();
myGsm.println("AT+HTTPREAD=0,20"); // read the data from the website you access
delay(3000);
printSerialData();
By enabling these 2 line now the OUTPUT is this(correct):
AT+CGATT=1
OK
AT+SAPBR=3,1,"CONTYPE","GPRS"
OK
AT+SAPBR=3,1,"APN","internet.wind"
OK
AT+SAPBR=2,1
+SAPBR: 1,1,"X.X.X.X"
OK
AT+SAPBR=1,1
OK
AT+HTTPINIT
OK
RFID Code: 172D9B32
AT+HTTPPARA="URL",http://mywebsite.000webhostapp.com/test.php?code=172D9B32
OK
AT+HTTPPARA="CID",1
OK
AT+HTTPACTION=0
OK
+HTTPACTION:0,200,16
AT+HTTPREAD=0,20
+HTTPREAD:16
SUCCESS 172D9B32
OK
Related
I have written a code for my Arduino to read data from sensor and then post to a PHP file called post-data.php, which then the PHP will insert the data into a database.
However, my Arduino does not seemed to be able to post the data or it is not posting it correctly.
#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#endif
#define signalPin 12
#define sensorPin A0
const char *ssid = "****";
const char *password = "*****";
const char* serverName = "http://smartswitchfyp.rf.gd/post-data.php";
String apiKeyValue = "*******";
ESP8266WebServer server(80);
void setup() {
Serial.begin(9600);
pinMode(sensorPin, INPUT);
Serial.print("Configuring access point...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFI connected");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
void loop() {
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
sensor();
// Prepare your HTTP POST request data
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(current) + "&value2=" + String(power) + "";
//String httpRequestData = "api_key=******9&value1=24.75&value2=49.54";
//Serial.print("httpRequestData: ");
//Serial.println(httpRequestData);
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(response);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
delay(1000);
}
I have checked that my serverName is correct.
I have tested the post-data.php, and it works fine as there is an update at my database. Below is the test code, test.php I used to test post-data.php
<html>
<body>
<form action="post-data.php" method="post">
api: <input type="text" name="api_key">
Name: <input type="text" name="value1">
Email: <input type="text" name="value2">
<input type="submit">
</form>
</body>
</html>
And below is my post-data.php file
<?php
$servername = "sql101.epizy.com";
$dbname = "epiz_28338452_smartswitch";
$username = "epiz_28338452";
$password = "********";
// Keep this API Key value to be compatible with the ESP32 code provided in the project page. If you change this value, the ESP32 sketch needs to match
$api_key_value = "*******";
$api_key = $value1 = $value2 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$api_key = test_input($_POST["api_key"]);
if($api_key == $api_key_value) {
$value1 = test_input($_POST["value1"]);
$value2 = test_input($_POST["value2"]);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Sensor (value1, value2) VALUES ('" . $value1 . "', '" . $value2 . "')";
$result = $conn->query($sql);
if ($result === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else {
echo "Wrong API Key provided.";
}
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I'm 90% sure that is not the post-data.php file problem but my Arduino not able to post the data to the php file.
At my Arduino code, I used the line
http.begin(serverName);
to connect to the post-data.php and then prepare the header:
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
and prepare the content:
String httpRequestData = "api_key=" + apiKeyValue + "&value1=" + String(current) + "&value2=" + String(power) + "";
where current and power is process in other function/method. I have tested the current and power output, and they are float variables. Finally I used the line
int httpResponseCode = http.POST(httpRequestData);
to post the 3 data to the php file.
When I startup the Arduino, the output shows HTTP Response code: 200, which I believe the php file was successfully called (correct me if I am wrong). However, my database does not have any data inserted. Again the test.php prove that the database can be inserted with data.
Below is image of the database value inserted by the test.php file
Can anyone help me as I'm not sure what cause the Arduino to not able to post the data. Thanks!
you can't access your infinity free site with your arduino because infinity free have a security system
see https://support.infinityfree.net/websites/what-is-the-i-1-suffix/ for more info
Kindly help me in my code. I have arduino code that is sending and getting data from mySql. It is running well and storing data to the database. The problem is that, if I switch ON the button the value 1 is stored in the database, but when I switch OFF the button the value 0 is not stored in the database.
Here is my arduino code:
//Arduino Code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);//Rx,Tx
int buttonPinBulb = 11;
int relay1 = 10;
int buttonBulb;
int currentStatus = LOW;
unsigned long lastMillis = 0;
const unsigned long debounceTime = 100;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
s.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
buttonBulb = digitalRead(buttonPinBulb);
bulbOnOff(buttonBulb);
}
int bulbOnOff(int buttonBulb) {
unsigned long currentMillis = millis();
// protect against overflow
if ( (currentMillis - lastMillis > debounceTime) || (currentMillis < lastMillis)) {
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
//Serial.println(!buttonBulb);
currentStatus = buttonBulb;
// update database here
if(s.available()>0)
{
s.write(!buttonBulb);
}
lastMillis = currentMillis;
}
}
return 0;
}
The following is nodeMCU ESP8266 code
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SoftwareSerial.h>
SoftwareSerial s(D6, D5); //RX,TX
int buttonBulb;
int Led_OnBoard = 2;
const char* ssid = "iPhone"; // Your wifi Name
const char* password = "Qaser.shah.123"; // Your wifi Password
const char *host = "172.20.10.6"; //Your pc or server (database) IP, example : 192.168.0.0 , if you are a windows os user, open cmd, then type ipconfig then look at IPv4 Address.
void setup() {
// put your setup code here, to run once:
wifiConnection();
s.begin(115200);
}
int wifiConnection() {
pinMode(Led_OnBoard, OUTPUT); // Initialize the Led_OnBoard pin as an output
Serial.begin(115200);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(Led_OnBoard, LOW);
delay(250);
Serial.print(".");
digitalWrite(Led_OnBoard, HIGH);
delay(250);
}
digitalWrite(Led_OnBoard, HIGH);
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.println("Connected to Network/SSID");
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
s.write("s");
if (s.available() > 0)
{
buttonBulb = s.read();
Serial.println(buttonBulb);
int result = updateDatabase(buttonBulb);
if(result != 0){
//error updating database
Serial.print("error updating database");
}
}
}
int updateDatabase(int buttonBulb){
HTTPClient http; //Declare object of class HTTPClient
//String ButtonState;
String buttonValueSend, postData;
buttonValueSend = String(buttonBulb); //String to interger conversion
//Post Data
postData = "buttonBulb=" + buttonValueSend;
http.begin("http://172.20.10.6/Nodemcu_db_record_view/InsertDB.php"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
Serial.println("Button Value send=" + buttonValueSend);
http.end(); //Close connection
return 0;
}
The following is my php code which stores the Arduino data
<?php
//Creates new record as per request
//Connect to database
$servername = "localhost"; //example = localhost or 192.168.0.0
$username = "root"; //example = root
$password = "";
$dbname = "automation";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Database Connection failed: " . $conn->connect_error);
}
//Get current date and time
date_default_timezone_set('Asia/Karachi');
$d = date("Y-m-d");
$t = date("H:i:s");
if(!empty($_POST['buttonBulb']))
{
$buttonBulb = $_POST['buttonBulb'];
$sql = "INSERT INTO project (ButtonState, Date, Time) VALUES ('".$buttonBulb."', '".$d."', '".$t."')"; //nodemcu_ldr_table = Youre_table_name
if ($conn->query($sql) === TRUE) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
See the image of output
In this image OK is printing at Value 1 but not printing OK at value 0
I think there is something wrong or I forgot something, that is why it is not happening.
Thanks a lot for any appericiation.
You can create a separate function to update the database and only call the update when the button state is changed.
Combined with my answer on your previous question it would look like this:
void loop() {
unsigned long currentMillis = millis();
if ( (currentMillis - lastMillis > debounceTime)
|| (currentMillis < lastMillis)) { // protect against overflow
int buttonBulb = digitalRead(buttonPinBulb);
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
Serial.println(buttonBulb);
currentStatus = buttonBulb;
// update database
int result = updateDatabase(buttonBulb);
if (result != 0) {
// error updating database
}
}
lastMillis = currentMillis;
}
}
int updateDatabase(int buttonvalue) {
HTTPClient http; //Declare object of class HTTPClient
String buttonValueSend, postData;
buttonValueSend = String(buttonvalue); //String to integer conversion
// ...
http.end(); //Close connection
return 0; // for example return 0 on success, -1 on error
}
I have found the problem. The problem was in my php code that is why the 1 will stored in the database but 0 would not.
Here is what I have change in php code
I just removed if(!empty(&_POST['buttonBulb'])){}
The code that was used in if statement now it is outside from if statement.
Reason
The behind that, when I send 1 to this code it is OK but if send 0 the is statement assumes there is no value and buttonBulb variable is empty.
Thankyou all of you who help me in this code. Now I am going to next step of this project and if I have some problems I will ask.
Specially thanks to #Danny_ds
So, basically I'm trying to get some values from an Arduino board to be saved to my SQL database stored on my PC.
I've looked at multiple resources online, and spent about 5-6 hours trying to crack this, but now i'm here asking for your help.
So, Heres what seems to be working.
Im able to send values to the database Directly by typing in :
[http://localhost/myapp/write_data.php?value1=2&value2=10]
to google chrome. This gives me the expected output from the PHP script and updates into the database. However, when I run it on the Arduino it goes through the code as if its working, but it isnt sending any data to the SQL Server.
Below is the Arduino Code.
#include <SPI.h>
#include <Ethernet.h>
int rand1 = 0;
int rand2 = 0;
//EthServer(80);
//IPAddress server(10,0,0,1);
char server[] =("10.0.0.1");
EthernetClient client;
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x0
};
byte ip[] = { 10, 0, 0, 2 };
void setup(void)
{
// start serial port
Serial.begin(9600);
Ethernet.begin(mac, ip);
}
void printIPAddress()
{
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
void loop() {
delay(1000);
rand1 = random(1, 3);
rand2 = random(25);
Serial.println(rand1);
Serial.println(rand2);
// Connect to the server (your computer or web page)
if (client.connect(("http://10.0.0.1"), 80)) {
client.print("GET /myapp/write_data.php?"); // This
client.print("value1="); // This
client.print(rand1); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
client.print(";");
client.print("value2=");
client.print(rand2);
client.println(" HTTP/1.1"); // Part of the GET request
client.println("Host: 10.0.0.1"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
client.println(); // Empty line
client.println(); // Empty line
client.stop(); // Closing connection to server
}
else {
// If Arduino can't connect to the server (your computer or web page)
Serial.println("--> connection failed\n");
printIPAddress();
}
delay(10000);
}
Then here I have the PHP Script
//connect
$link=new mysqli("localhost", "root", "", "myappdb");
//check connection
if ($link==false) {
die("Connection failed: " . mysqli_connect_error());
}
//insert values
$sql = "INSERT INTO resistence (phase, max_reading)
VALUES (". $_GET['value1'] .",". $_GET['value2'].")";
//// Check if values have been inserted, confirm with user that values are correct.
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
echo "Values inserted are Phase " . $_GET['value1']. " and Max_Reading ". $_GET['value2']. ".";
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
/////
//close connection
mysqli_close($link);
?>
Any help at all would be awesome.
Cheers
John
If you don't get reponse "connection failed" then it should be connected. Try
client.print("&");
instead
client.print(";");
If that still doesn't work, in the PHP file, use
error_log("text");
and check the server error.log to figure out if PHP script is even started, and check if $_GET variable is set at all.
EDIT: addition:
You shouldn't use client.connect in if statement.
client.connect returns an int (1,-1,-2,-3,-4) indicating connection status
SUCCESS 1
TIMED_OUT -1
INVALID_SERVER -2
TRUNCATED -3
INVALID_RESPONSE -4
So print out the return and then continue with debugging. Must be problem with the IP address you provided.
I am having trouble connecting to my Google Cloud PHP server that hosts a MySQL database. Here is my code for sending a notification to my PHP server.
NotificationInstanceService.java
public class NotificationInstanceService extends FirebaseInstanceIdService {
private static final String TAG = "NotificationInstance";
#Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token on logcat
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
//Not required for current project
OkHttpClient client = new OkHttpClient();
//Create the request body
RequestBody body = new FormBody.Builder().add("Token", token).build();
//Know where to send the request to
Request request = new Request.Builder().url("<app server url>/register.php")
.post(body)
.build();
//Create
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This seems to go through correctly and there doesn't seem to be any stack trace thrown. Then, when I deployed my PHP server, I have created the following files:
app.yaml:
application: <app server url>
service: default
runtime: php55
api_version: 1
version: alpha-001
handlers:
- url: /(.+\.(ico|jpg|png|gif))$
static_files: \1
upload: (.+\.(ico|jpg|png|gif))$
application_readable: true
- url: /(.+\.(htm|html|css|js))$
static_files: \1
upload: (.+\.(htm|html|css|js))$
application_readable: true
- url: /(.+\.php)$
script: \1
login: admin
- url: /.*
script: index.php
login: admin
- url: /.*
script: register.php
login: admin
config.inc.php:
<?php
$cfg['blowfish_secret'] = '<Secret>'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
/*
* Servers configuration
*/
$i = 0;
// Change this to use the project and instance that you've created.
$host = '/cloudsql/<app server url>:us-central1:<database name>-app-php';
$type = 'socket';
/*
* First server
*/
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
$cfg['Servers'][$i]['socket'] = $host;
$cfg['Servers'][$i]['connect_type'] = $type;
$cfg['Servers'][$i]['compress'] = false;
/* Select mysql if your server does not have mysqli */
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/*
* End of servers configuration
*/
/*
* Directories for saving/loading files from server
*/
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
$cfg['PmaNoRelation_DisableWarning'] = true;
$cfg['ExecTimeLimit'] = 60;
$cfg['CheckConfigurationPermissions'] = false;
// [END all]
php.ini:
google_app_engine.enable_functions = "php_uname, getmypid"
And lastly, register.php which is my php script located in the current directory of all these files:
register.php:
<?php
function dbg($data){
file_put_contents(__DIR__.'/log.txt',$data.PHP_EOL,FILE_APPEND );
}
$conn = mysql_connect(':/cloudsql/<app server url>:us-central1:<database name>',
'root', // username
'' // password
);
if (isset($conn) && isset($_POST["Token"])) {
$_uv_Token=$_POST["Token"];
echo $conn;
$q="INSERT INTO users (Token) VALUES ( '$_uv_Token') "
." ON DUPLICATE KEY UPDATE Token = '$_uv_Token';";
$result = mysqli_query($conn,$q) or die(mysqli_error($conn));
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Inserted successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
dbg($q); /* where $q is the sql */
dbg(print_r($result,true)); /* config */
mysqli_close($conn);
}
?>
I can't seem to find where I am going wrong with this. I cant seem to debug or find any error logs as to if I am connected to the wrong database, or if my REST call is simply getting intercepted somewhere for whatever reason. It seems that on the client side, in NotificationInstanceService.java the registration token is sent to the server, but then the server never actually stores the id or token in it. I am pretty sure I have all the URLs for my application server configured correctly. I tried to $echo all the responses and such I am getting but can't seem to find where to get these $echo statements. Any help would be much appreciated. Thanks!
One thing you might do to help debug ( other than checking the php errorlog ) is to write a small function that writes to a text file.
function dbg($data){
file_put_contents(__DIR__.'/log.txt',$data.PHP_EOL,FILE_APPEND );
}
/* then call it like: */
dbg($q); /* where $q is the sql */
dbg(print_r($cfg,true)); /* config */
Then use it though the php code to see what data you get at various stages - either by ftp download or browsing to that file location with a browser. Just an idea...
<?php
function dbg($data){
file_put_contents( __DIR__.'/log.txt', $data.PHP_EOL, FILE_APPEND );
}
/* !! assuming `config.inc.php` is available in `register.php` !! */
dbg( print_r( $cfg, true ) );
$conn = mysql_connect(':/cloudsql/<app server url>:us-central1:<database name>',
'root',
''
);
dbg( 'errors: '.mysql_error( $conn ) );
if ( $conn && isset( $_POST["Token"] ) ) {
$_uv_Token=$_POST["Token"];
dbg('POST-Token: '.$_uv_Token);
$q="INSERT INTO users (Token) VALUES ( '$_uv_Token') ON DUPLICATE KEY UPDATE Token = '$_uv_Token';";
dbg('sql: '.$q);
$result = mysqli_query($conn,$q) or die(mysqli_error($conn));
dbg('Query succeeded: '.$result);
if ($result) {
$response["success"] = 1;
$response["message"] = "Inserted successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
mysql_close( $conn );
}
?>
Is config.inc.php included in register.php? I ask because you defined various settings in the config file but then go on, in register.php to hardocde them again.
I'm working with Arduino and its GSM Shield. This is a hardware device that allows me to make an HTTP GET request to any IP address or web URL.
So we build a PHP script that reads URL parameters, and submits that data to the database. It will be saving our Arduino data when it pings our server.
Right now, when I visit the URL with the parameters in my browser, it works great. Everything saves and can be accessed via DB. But when the Arduino makes the request or I ping the URL with cURL, the record doesn't get saved.
The response I get shows that it is loading the page and spitting back the expected HTML. Why is my PHP not reading these URL parameters and saving them?
I've looked into sessions, etc no luck.
Thanks in advance!!
EDIT:::
handle_data.php (parses parameters, saves them to DB)
<?php
// Setup our DB login info
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "arduino";
if (!empty($_GET['lat']) && !empty($_GET['lon'])) {
function getParameter($par, $default = null){
if (isset($_GET[$par]) && strlen($_GET[$par])) return $_GET[$par];
elseif (isset($_POST[$par]) && strlen($_POST[$par]))
return $_POST[$par];
else return $default;
}
$lat = getParameter("lat");
$lon = getParameter("lon");
$person = $lat.",".$lon.",".$time.",".$sat.",".$speed.",".$course."\n";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO gps_data (latitude, longitude)
VALUES (".$lat.", ".$lon.")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
// close connection
$conn->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else {
};
?>
Here's the Arduino Code:
if(started) {
//GPRS attach, put in order APN, username and password.
//If no needed auth let them blank.
if (inet.attachGPRS("internet.wind", "", ""))
Serial.println("status=ATTACHED");
else Serial.println("status=ERROR");
delay(1000);
//Read IP address.
gsm.SimpleWriteln("AT+CIFSR");
delay(5000);
//Read until serial buffer is empty.
gsm.WhileSimpleRead();
//TCP Client GET, send a GET request to the server and
//save the reply.
numdata=inet.httpGET("http://cd5d6640.ngrok.io", 80, "/handle_data.php?lat=44.87654&lon=-88.77373", msg, 50);
//Print the results.
Serial.println("\nNumber of data received:");
Serial.println(numdata);
Serial.println("\nData received:");
Serial.println(msg);
}
Note - We're developing on localhost with MAMP, using ngrok to tunnel to localhost:8888. It works fine when you visit the ngrok url in the browser, but not when we hit it with a request. The url included is irrelevant and not active.