PHP/My SQL Database -> to Arduino Serial Monitor - php

I'm using this domain http://www.decathlon.commonarchitecture.ca/ to host my phpmyadmin database and php code. I would like to read a specific column of the database in the serial monitor, displaying each number one right after the other. I'm unsure of whether to work with a GSM shield, an Ethernet shield or an Arduino wifi shield. Here is my php code (indents are off I know):
<?php
$dbhost = "mysql.commonarchitecture.ca";
$username = "arduinodb";
$password = "*******";
$db = "arduinodb" ;
mysql_connect("$dbhost" , "$username" , "$password");
//echo "Connected" ;
//select db
mysql_select_db($db);
//echo "Connected to db" ;
$sql="SELECT * FROM data";
$records=mysql_query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title> Consumption Data </title>
</head>
<body>
<table width="600" border="1" cellpadding="1" cellspacing"1">
<tr>
<th>Day</th>
<th>Date</th>
<th>Water Consumption (liters per person)</th>
<tr>
<?php
while($data=mysql_fetch_assoc($records)) {
echo "<tr>";
echo "<td>".$data['id']."</td>";
echo "<td>".$data['date']."</td>";
echo "<td>".$data['value']."</td>";
echo "</tr>";
}//end while
?>
</table>
</body>
</html>
The code works, however I'm unsure of how to go about reading the data on an Arduino (very new to Arduino)
Here's my Arduino code paired with an ethernet shield
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, *, *);
EthernetClient client;
char server[] = "www.decathlon.commonarchitecture.ca";
void setup()
{
Serial.begin(9600);
// attempt a DHCP connection:
Serial.println("Attempting to get an IP address using DHCP:");
if (!Ethernet.begin(mac)) {
// if DHCP fails, start with a hard-coded address:
Serial.println("failed to get an IP address using DHCP, trying
manually");
Ethernet.begin(mac, ip);
}
Serial.print("My address:");
Serial.println(Ethernet.localIP());
}
void loop()
{
// connect to the server
if (client.connect(server, 80))
{
// print to serial monitor
Serial.println("connected...");
Serial.println("ARDUINO: forming HTTP request message");
// send data the server through GET request
client.print("GET /index.php?value");
client.println(" HTTP/1.1");
client.print("HOST: ");
client.println(server);
Serial.println("ARDUINO: HTTP message sent");
// give server time to receive request
delay(1000);
// get the response from the page and print it to serial port
// to ascertain that request was received properly
if(client.available())
{
Serial.println("ARDUINO: HTTP message received");
Serial.println("ARDUINO: printing received headers and
script response...\n");
while(client.available())
{
char c = client.read();
Serial.print(c);
}
}
else
{
Serial.println("ARDUINO: no response received / no response
received in time");
}
client.stop();
}
// do nothing forever after:
while(true);
}
My issue now is in getting the Arduino to read my php data, can I not use an http GET request to display data in my serial monitor? Am I using this function properly? There's a ton of documentation on posting Arduino sensor data to the web using php/my sql but not as much on retrieval of set data back into the serial monitor. Here's what the monitor reads currently...
Attempting to get an IP address using DHCP:
My address:192.168.*.*
connected...
ARDUINO: forming HTTP request message
ARDUINO: HTTP message sent
ARDUINO: no response received / no response received in time

Related

How to GET data from MySql server?

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

Arduino not sending numbers to SQL (via PHP) correctly

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.

Unable send message continuity via socket

I'm trying to make a communication system between python server and php client. Php client will connect to python server and send a message and close to make completely. But when I connect and send message again, python server can't receive this message while in opening then client can't get you are client111111111111111111111111111111111111111111 line, but when I telnet on commandline to connect to server then everything work well. Please help! Sorry my bad english.
Here is my code.
python server
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall('you are client111111111111111111111111111111111111111111')
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
php client
socket.php
<?php
$fp = fsockopen("127.0.0.1", 10000, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "You message");
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
Update question : Message sent via ajax when press a button event
<script type="text/javascript">
function buttonPress() {
$.ajax({
type : 'post',
url : 'socket.php',
success : function(mess){
}
});
}
</script>

fsocketopen() Not connecting to server?

I've been trying to connect to a Twitch chat via IRC. I've added an echo function to test where I had connected or not as that page was blank and an account didn't join the IRC.
Here is my code:
<?php
set_time_limit(0);
ini_set('display_errors', 'on');
$datatwitch= array(
'server' => 'irc.twitch.tv',
'port' => 6667,
'nick' => 'greatbritishbgbot',
'name' => 'greatbritishbgbot',
'pass' => 'oauth:HERE',
);
?>
<?php
//The server host is the IP or DNS of the IRC server.
$server_host = $datatwitch['server'];
//Server Port, this is the port that the irc server is running on. Deafult: 6667
$server_port = $datatwitch['port'];
//Server Chanel, After connecting to the IRC server this is the channel it will join.
$server_chan = "#greatbritishbg";
//login password
$nickname = $datatwitch['name'];
$nickname_pass = $datatwitch['pass'];
//Ok, We have a nickname, now lets connect.
$server = array(); //we will use an array to store all the server data.
//Open the socket connection to the IRC server
$server['SOCKET'] = #fsockopen($server_host, $server_port, $errno, $errstr, 2);
if($server['SOCKET'])
{
//Ok, we have connected to the server, now we have to send the login commands.
echo "connected";
SendCommand("PASS $nickname_pass \n\r"); //Sends the password not needed for most servers
SendCommand("NICK $nickname\n\r"); //sends the nickname
SendCommand("USER $nickname USING PHP IRC\n\r"); //sends the user must have 4 paramters
while(!feof($server['SOCKET'])) //while we are connected to the server
{
$server['READ_BUFFER'] = fgets($server['SOCKET'], 1024); //get a line of data from the server
echo "[RECIVE] ".$server['READ_BUFFER']."<br>\n\r"; //display the recived data from the server
/*
IRC Sends a "PING" command to the client which must be anwsered with a "PONG"
Or the client gets Disconnected
*/
//Now lets check to see if we have joined the server
if(strpos($server['READ_BUFFER'], "422")) //422 is the message number of the MOTD for the server (The last thing displayed after a successful connection)
{
//If we have joined the server
SendCommand("JOIN $server_chan\n\r"); //Join the chanel
}
if(substr($server['READ_BUFFER'], 0, 6) == "PING :") //If the server has sent the ping command
{
SendCommand("PONG :".substr($server['READ_BUFFER'], 6)."\n\r"); //Reply with pong
//As you can see i dont have it reply with just "PONG"
//It sends PONG and the data recived after the "PING" text on that recived line
//Reason being is some irc servers have a "No Spoof" feature that sends a key after the PING
//Command that must be replied with PONG and the same key sent.
}
flush(); //This flushes the output buffer forcing the text in the while loop to be displayed "On demand"
}
} else {
echo "connection failed";
}
function SendCommand ($cmd)
{
global $server; //Extends our $server array to this function
#fwrite($server['SOCKET'], $cmd, strlen($cmd)); //sends the command to the server
echo "[SEND] $cmd <br>"; //displays it on the screen
}
?>
It appears I can't Get passed if($server['SOCKET']). Is there anyway I can diagnose this? As I have directly connect with the details in hexChat.
The server had actually been preventing me to use fsocket. After contacting my host and moving away from a shared host it started to work.
Please take a look at this answer: https://stackoverflow.com/a/24835967/1163786
Especially:
$socket = fsockopen($bot["Host"], $bot["Port"], $error1, $error2);
if(!$socket) {
echo 'Crap! fsockopen failed. Details: ' . $error1 . ': ' . $error2;
}
To get the details about the socket error = reason for socket not connecting.
Currently, you have $errno, $errstr on fsockopen, but echo only "connection failed".

Why is my PHP Socket Server hanging?

I created a PHP Socket Server with PHP_NORMAL_READ mode. So, a message to the server is read when it ends with \n or \r. I tried it by connecting to the server with multiple telnet instances, and it works great.
However, when I connect to the server with 1 flash application and 1 telnet application (I first start the flash one), the flash one seems to make the server hang - the server is getting stuck somewhere and no longer receiving data from eg. the telnet client.
Because anyone can code a flash client, this has to be fixed server side. The server's code:
<?php
// config
$timelimit = 60; // amount of seconds the server should run for, 0 = run indefintely
$port = 9000; // the port to listen on
$address = $_SERVER['SERVER_ADDR']; // the server's external IP
$backlog = SOMAXCONN; // the maximum of backlog incoming connections that will be queued for processing
// configure custom PHP settings
error_reporting(1); // report all errors
ini_set('display_errors', 1); // display all errors
set_time_limit($timelimit); // timeout after x seconds
ob_implicit_flush(); // results in a flush operation after every output call
//create master IPv4 based TCP socket
if (!($master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) die("Could not create master socket, error: ".socket_strerror(socket_last_error()));
// set socket options (local addresses can be reused)
if (!socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1)) die("Could not set socket options, error: ".socket_strerror(socket_last_error()));
// bind to socket server
if (!socket_bind($master, $address, $port)) die("Could not bind to socket server, error: ".socket_strerror(socket_last_error()));
// start listening
if (!socket_listen($master, $backlog)) die("Could not start listening to socket, error: ".socket_strerror(socket_last_error()));
//display startup information
echo "[".date('Y-m-d H:i:s')."] SERVER CREATED (MAXCONN: ".SOMAXCONN.").\n"; //max connections is a kernel variable and can be adjusted with sysctl
echo "[".date('Y-m-d H:i:s')."] Listening on ".$address.":".$port.".\n";
$time = time(); //set startup timestamp
// init read sockets array
$read_sockets = array($master);
// continuously handle incoming socket messages, or close if time limit has been reached
while ((!$timelimit) or (time() - $time < $timelimit)) {
$changed_sockets = $read_sockets;
socket_select($changed_sockets, $write = null, $except = null, null);
foreach($changed_sockets as $socket) {
if ($socket == $master) {
if (($client = socket_accept($master)) < 0) {
continue;
} else {
array_push($read_sockets, $client);
}
} else {
$data = #socket_read($socket, 1024, PHP_NORMAL_READ); //read a maximum of 1024 bytes until a new line has been sent
if ($data === false) { //the client disconnected
$index = array_search($socket, $read_sockets);
unset($read_sockets[$index]);
socket_close($socket);
} elseif ($data = trim($data)) { //remove whitespace and continue only if the message is not empty
echo "we received: ".$data."\n\n";
//handleData($data, $socket);
}
}
}
}
socket_close($master); //close the socket
echo "[".date('Y-m-d H:i:s')."] SERVER CLOSED.\n";
//function to write to the flash client
function flash_write($socket, $msg) {
socket_write($socket, $msg.chr(0x0));
}
?>
Does anyone know what may cause this? I tried changing the timeout on the socket_select from none to 0 (instant return), but that didn't seem to change anything.
Could you post the source of the flash client? That would show what the problem is?
Are you sure the last thing you send from the flash client is a \n ?
Otherwise the server would block on socket_read() as the flash client socket can be read without blocking (triggered socket_select()), but doesn't send the ending \n.
One thing to help you debug: error_reporting(1) does not enable the display of all errors. Look at the documentation at http://us3.php.net/manual/en/function.error-reporting.php. You need something like error_reporting(E_ALL).

Categories