sending arduino data to my database using EtherCard.h library - arduino

I am having a problem in sending Arduino data into my database. I am currently using WAMPSERVER. I have an arduino mini w/ ATMEGA 328 and I am using ENC28J60. The problem is I have tried different libraries and examples to send data into the server but I failed. I just notice that some libraries are not compatible with my enc28J60. I have tried UIPEthernet.h, Ethernet.h, etherShield.h and EtherCard.h. The etherShield.h and EtherCard.h seemed to work just fine. But I prefer to use EtherCard.h because I heard etherShield is the older lib. I know a little php.
I think the things that might guide me is to see a working example of using the EtherCard.h library demonstrating the sending of sensor data from arduino into my database. The network setup I am currently working on is that, the ENC28J60 is connected in my home network with an ip address of 192.168.10.10. The server to which I placed the database is my laptop with an IP address of 192.168.10.2. I am placing the php files in this directory C:\wamp\www. I hope I have explained it well. I'm sorry for my English.

I am currently working of a port of my homewatch server from Arduino Uno w Ethernet lib to AVR-NETIO with Ethercard lib (or UIPEthernet).
On the server side there is a Apache/PHP/MySQL server.
To update data on a webserver connected database, you can use POST or GET requests to a php web page. These data can then be added easily to a database and the same or another web page can also display the data of the database.
<?php
require 'dbhelp.php';
//header('Content-type: text/plain');
echo "<html>";
echo "<head>";
echo "<meta name='viewport' content='width=device-width, user-scalable=false, initial-scale=1;'>";
echo "</head>";
echo "<body>" . "<h2>Temperatur und Luftfeuchte</h2>";
// GET requests are sent as a query string on the URL:
// GET index.html?name1=value&name2=value HTTP/1.1
// Host: about.com
// http://192.168.0.40/homewatch/index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if($DEBUG){
print("<pre>");
print_r($_GET);
print("</pre>");
}
openDB();
if( isset($_GET['channel']) && isset($_GET['temp']) && isset($_GET['humidity']) )
{
if($DEBUG)
echo "<p>addData()";
$c=$_GET['channel'];
$t=$_GET['temp'];
$h=$_GET['humidity'];
addData($c, $t, $h);
if($DEBUG)
echo "<p>all done";
//listData();
echo "<p>OK updated data for channel:" . $c . "</p>";
}
else
{
if($DEBUG)
echo "listData()";
//listData();
//echo "<p>missing arg";
}
echo "<p><a href='linechart_hour.php'>Stunden-Übersicht</a></p>";
echo "<p><a href='barchart_days.php'>Tages-Übersicht</a></p>";
echo "<p><a href='http://www.unwetterzentrale.de/uwz/getwarning_de.php?plz=41363&uwz=UWZ-DE&lang=de'>Unwetterwarnungen Jüchen</a></p>";
echo showAllCharts();
//#################################################################################
// see http://code.google.com/p/googlechartphplib/wiki/GettingStarted
//#################################################################################
// don't forget to update the path here
require './lib/GoogleChart.php';
$chart = new GoogleChart('lc', 500, 200);
// manually forcing the scale to [0,100]
$chart->setScale(0,100);
// add one line
$data = new GoogleChartData(array(49,74,78,71,40,39,35,20,50,61,45));
$chart->addData($data);
// customize y axis
$y_axis = new GoogleChartAxis('y');
$y_axis->setDrawTickMarks(false)->setLabels(array(0,50,100));
$chart->addAxis($y_axis);
// customize x axis
$x_axis = new GoogleChartAxis('x');
$x_axis->setTickMarks(5);
$chart->addAxis($x_axis);
echo $chart->toHtml();
//#################################################################################
// END
//#################################################################################
echo "<p>v0.9" . "</body>" . "</html>";
?>
the dbhelp.php file creates the DB automatically if not already exists:
<?php
//global dbhelp.php file
$server="localhost";
$user="root";
$passwd="password";
$names=array(
1 => "Aussen",
2 => "Schlaf",
3 => "Andreas");
$DEBUG=false;
function openDB(){
global $DEBUG;
global $user;
global $passwd;
$link = mysql_connect("localhost", $user, $passwd);
if(!$link){
echo "SqlConnect failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SqlConnect OK";
$query="CREATE database IF NOT EXISTS avrdb;";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateDB OK";
$result = mysql_select_db("avrdb", $link);
if(!$result){
echo "SelectDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SelectDB OK";
$query="CREATE TABLE IF NOT EXISTS `avrtemp` (" .
"`id` int(11) NOT NULL AUTO_INCREMENT, " .
"`channel` int(11), " .
"`temp` int(11), " .
"`humidity` int(11), " .
"`date_time` TIMESTAMP, " .
"PRIMARY KEY (`id`) );";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateTable failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateTable OK";
return true;
}
...
function addData($c,$t,$h){
global $DEBUG;
$lastStoredDateTime=getLastStoredDateTime();
if($DEBUG){
echo "<p>" . $c . "</p>\n";
echo "<p>LastDateTime=".$lastStoredDateTime."</p>\n";
}
// add data but do not save seconds (use 00)
$query="INSERT INTO avrtemp (`channel`,`temp`,`humidity`,`date_time`)".
" VALUES ( $c,$t,$h,".
// " DATE_FORMAT(NOW()),".
" DATE_FORMAT('".$lastStoredDateTime."', ".
" '%Y-%c-%d %H:%i') )";
if($DEBUG)
echo "<p>" . $query;
$result = mysql_query($query);
if(!$result){
echo "addData failed";
echo mysql_error();
}
else
if($DEBUG)
echo "addData OK";
}
The Arduino posts (using GET) updated data every 5 minutes. The data arrives at the Arduino via 433MHz wireless sensors every minute or so.
Using the Ethernet Lib the data update is done via
char cBuf[maxBuf+1];
const char getHttpString[] =
"GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0";
...
// and send data: /index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if (client.connect(server, 80)) {
Serial.println("connected. Send GET...");
snprintf(cBuf, maxBuf,
getHttpString,
sensorData[idxChannel].channel,
sensorData[idxChannel].temp,
sensorData[idxChannel].humidity,
sensorData[idxChannel].time_long
);
Serial.println(F("####"));
Serial.println(cBuf);
Serial.println(F("####"));
client.println(cBuf);
...
https://github.com/hjgode/homewatch/blob/master/arduino/SketchBook/WebClientTemperature/WebClientTemperature.ino:
The string "GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0" is simply filled with actual sensor data and the server saves that to its database.
The Ethercard lib comes with similar examples: see the examples noipClient, pachube and webclient. Unfortunately I was not yet able to adopt these for my AVR-NETIO.
The code to post (GET) some data to the server I am currently working is
void sendData(int idxChannel){
Serial.print(F("in sendData for idx=")); Serial.println(idxChannel);
byte sd;
int channel=sensorData[idxChannel].channel;
int temp=sensorData[idxChannel].temp;
int humidity=sensorData[idxChannel].humidity;
char* stime="201301011122";
stime=printDateTime((char*)&stime, 13, sensorData[idxChannel].time_long);
if(sensorData[idxChannel].bUpdated==0){
//nothing new
if (MYDEBUG==0){
Serial.println(F("leaving for not updated channel data"));
goto exit_sendData;
}
else
{
sensorData[idxChannel].channel=idxChannel;
sensorData[idxChannel].temp=222;
sensorData[idxChannel].humidity=55;
sensorData[idxChannel].time_long=now();
}
}
// generate two fake values as payload - by using a separate stash,
// we can determine the size of the generated message ahead of time
sd = stash.create();
stash.print("0,");
stash.println((word) millis() / 123);
stash.print("1,");
stash.println((word) micros() / 456);
stash.save();
// generate the header with payload - note that the stash size is used,
// and that a "stash descriptor" is passed in as argument using "$H"
Stash::prepare(PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S" "\r\n"
"Host: $F" "\r\n"
"Content-Length: $D" "\r\n"
"\r\n"
"$H"),
website,
channel,
temp,
humidity,
stime,
website, stash.size(), sd);
// send the packet - this also releases all stash buffers once done
ether.tcpSend();
exit_sendData:
lastConnectionTime = now();//millis();
Serial.println(F("...end of sendData()"));
}
As you see, there is a formatted string
PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S"
which is filled with variables. $F fills from Flash Memory, $D a number var, $S from a RAM memory string. Using this without my SensorCode (which uses Interrupts) is working.

Related

Creating multiple zip files with PHP

I have a problem in PHP / Laravel to create multiple zip files synchronously, I copy all commands that is generated and squeeze into the Shell, it executes normally, but when I step into the PHP run it only generates the first file = /.
Controller code.
foreach ($passwords as $p){
if($i == 0){
$command = 'zip -u -j -P '.$p.' '.$dir.'/'.$count.'.zip '.storage_path().'/app/'.$directory.'/'.$file1->getClientOriginalName();
$commands->push($command);
}else{
$command = 'zip --quiet -j -P '.$p.' '.$dir.'/'.$count.'.zip '.storage_path().'/app/'.$directory.'/'.($count+1).'.zip';
$commands->push($command);
}
$count--;
$i++;
}
foreach ($commands as $p){
echo $p.'<br/>';
}
foreach ($commands as $c){
$process = new Process($c);
$process->start();
sleep(10);
if($process->isTerminated()){
sleep(1);
}
if ($errorOutput = $process->getErrorOutput()) {
throw new RuntimeException('Process: ' . $errorOutput);
}
}
Data $commands
The script only generates the file 50.zip.
Not sure if sleep could interfere with subprocess (shell command). Please try:
foreach ($commands as $c){
$process = new Process($c);
// Set the timeout instead of sleeping
$process->setTimeout(10);
$process->start();
// Wait for the process to finish
$process->wait();
if ($errorOutput = $process->getErrorOutput()) {
throw new RuntimeException('Process: ' . $errorOutput);
}
}
wait() call uses usleep in a more fine-grained manner it might help with that.
Does it work like this?

How to run PHPUnit test using browser?

I am new in PHPUnit and i am required to run the test using browser and save the result in xml format.
But every time when i run this code, i got following error:
FatalErrorException: Error: Interface 'PHPUnit_Framework_Test' not found in /usr/share/php/PHPUnit/Framework/TestSuite.php line 83
My code looks like this:
require_once '/var/www/Drillsight/app/autoload.php';
require_once "PHPUnit/Framework/TestSuite.php";
require_once "PHPUnit/TextUI/TestRunner.php";
$run_command = new PHPUnit_TextUI_Command;
$run_command ->run(array('phpunit', '--log-junit', 'results.xml', 'MyPHPUnitTest.php'),true);
Can anybody help in this matter?
Any other recommendation options will be highly appreciated !
Thanks in advance !
Do it really need to be runned in a browser?
I personally use a .bat file containing all my unit test like this
REM GEM_MECHANIC_TESTS
ECHO.
ECHO FILE : GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
REM GEM_MECHANIC_INTERFACE_BUILDER_TESTS
ECHO.
ECHO FILE : HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/TEST_INTERFACE_BUILDER/HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
And run a command like this in my Xampp console:
C:\xampp\htdocs\PC_administration_interface\Controler/script/temp_unit_test.bat >C:\xampp\htdocs\PC_administration_interface\Controler/test_result.txt
Or if you want to do it automatically each night with a windows task:
Launch_xampp.bat
#echo off
tasklist | find /i "xampp-control.exe" && goto :eof
start /b "xampp-control.exe" "C:\xampp\xampp-control.exe"
launch_automatic_test.bat
#echo off
call %~DP0\launch_xampp.bat
call %~DP0\..\..\..\..\xampp_shell.bat
cls
call %~DP0\run_unit_test.bat > "%~DP0\..\test_result.txt"
The method don't matter as much as I export the result in a textfile and than use PHP to parse the output (you can just change the code a bit to produce XML).
public static function fetchTestResult(&$errorMessage){
$echoString = '';
$failure = false;
$fileContent = '';
$errorMessage = '';
$dbManager = GeneralDbManager::getInstance();
if (file_exists(realpath(dirname(__FILE__)) . '/test_result.txt')) {
#$fileContent = file(realpath(dirname(__FILE__)) . '/test_result.txt');
if ($fileContent === false){
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_RESULT_LOG_ERR', "An error happened while reading the unit tests results log.");
}
else{
unlink(realpath(dirname(__FILE__)) . '/test_result.txt');
if (file_exists(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat')) {
unlink(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat');
}
$echoString = HtmlTagBuilder::createCustomTextArea("TA_UNIT_TEST_RESULT", TextAlign::ALIGN_LEFT, false, 1100, 500);
foreach ($fileContent as $line){
if (StringManager::stringStartWith($line, "FILE :")){
$failure = false;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::TITLE_LINE);
}
elseif (StringManager::stringStartWith($line, "time:")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::WARNING_LINE);
}
elseif (StringManager::stringStartWith($line, "OK (")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::SUCCESS_LINE);
}
elseif ((StringManager::stringStartWith($line, "There ") and strpos($line, "failure") !== false)
or $failure === true){
$failure = true;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
elseif (strpos(strtolower($line), "failure") !== false){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
else{
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::REGULAR_LINE);
}
}
$echoString .= '</DIV><br><br>';
}
}
else{
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_NO_RESULT_LOG_ERR', "You must run the unit test and generate the test log before displaying it.");
}
return $echoString;
}

using phpunit on cgi environment

I'm new to PHPUnit. I'm developing on an existing system, adding new features. I want to use PHPUnit to test codes I made. However, the system runs only on server (CGI) environment (access from a browser), and everything breaks while running from command-line.
Is it possible to setting PHPUnit to make a test suite which can be invoked from web browser?
Personally, I'm using windows task manager (cron can do the same thing on linux) to generate my unit test and send it to a text file every night.
Instead of display it directly in the web browser like I do, you could parse the result file directly on your server and then send the html output by email. So you could simply examine the result page on your local machine every morning like I do. Here's some code to start up your solution (on windows/PHP).
In task manager:
Action 1: C:\xampp\htdocs\PC_administration_interface\Controler\Script\launch_automatic_test.bat
Action 2: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Argument action 2: http://localhost/PC_administration_interface/view/unit_test.php?DISPLAY_RESULT=TRUE
Launch_automatic_test.bat
#echo off
call %~DP0\launch_xampp.bat
call %~DP0\..\..\..\..\xampp_shell.bat
cls
call %~DP0\run_unit_test.bat > "%~DP0\..\test_result.txt"
launch_xampp_bat
#echo off
tasklist | find /i "xampp-control.exe" && goto :eof
start /b "xampp-control.exe" "C:\xampp\xampp-control.exe"
And here's a sample of run_unit_tets.bat
#ECHO OFF
CLS
REM GEM_MECHANIC_TESTS
ECHO.
ECHO FILE : GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GEM_MECHANIC/CONTROLER/TEST/GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
REM GEM_MECHANIC_INTERFACE_BUILDER_TESTS
ECHO.
ECHO FILE : HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GEM_MECHANIC/CONTROLER/TEST/TEST_INTERFACE_BUILDER/HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
Then I'm launching a web page that parse my result and display it in the web browser:
public static function fetchTestResult(&$errorMessage){
$echoString = '';
$failure = false;
$fileContent = '';
$errorMessage = '';
$dbManager = GeneralDbManager::getInstance();
if (file_exists(realpath(dirname(__FILE__)) . '/test_result.txt')) {
#$fileContent = file(realpath(dirname(__FILE__)) . '/test_result.txt');
if ($fileContent === false){
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_RESULT_LOG_ERR', "An error happened while reading the unit tests results log.");
}
else{
unlink(realpath(dirname(__FILE__)) . '/test_result.txt');
if (file_exists(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat')) {
unlink(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat');
}
$echoString = HtmlTagBuilder::createCustomTextArea("TA_UNIT_TEST_RESULT", TextAlign::ALIGN_LEFT, false, 1100, 500);
foreach ($fileContent as $line){
if (StringManager::stringStartWith($line, "FILE :")){
$failure = false;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::TITLE_LINE);
}
elseif (StringManager::stringStartWith($line, "time:")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::WARNING_LINE);
}
elseif (StringManager::stringStartWith($line, "OK (")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::SUCCESS_LINE);
}
elseif ((StringManager::stringStartWith($line, "There ") and strpos($line, "failure") !== false)
or $failure === true){
$failure = true;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
elseif (strpos(strtolower($line), "failure") !== false){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
else{
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::REGULAR_LINE);
}
}
$echoString .= '</DIV><br><br>';
}
}
else{
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_NO_RESULT_LOG_ERR', "You must run the unit test and generate the test log before displaying it.");
}
return $echoString;
}
Additional note: I'm currently getting some information about CGI and it seem that it is pretty inefficient. You might also consider take a look at this post (question and answers):
What is Common Gateway Interface (CGI)?

WordPress | Text email issue

I am trying to modify the reset-password notification e-mail, but the issue is that the e-mail body is auto-wrapped every ~26 characters.
Is there a way to overcome that issue ?
My message variable is this :
$message = sprintf(__('Το Όνομα χρήστη (User Name) του λογαριασμού σας MySiteTitle είναι : %s', 'z'), $user_login) . "\r\n\r\n";
$message .= __("Σε περίπτωση που θέλετε να δημιουργήσετε νέο κωδικό πρόσβασης πατήστε τον ακόλουθο σύνδεσμο.", 'z') . "\r\n\r\n";
$message .= $link . "\r\n\r\n";
$message .= __('Εάν δεν αιτηθήκατε της συγκεκριμένης υπενθύμισης αγνοείστε το παρόν μήνυμα.', 'z');
and the send message I get both in my regular e-mail and the Gmail email account is the following:
Το Όνομα χρήστη (User Name) του
λογαριασμού σας MySiteTitle είναι
: admin
Σε περίπτωση που θέλετε να
δημιουργήσετε νέο κωδικό
πρόσβασης πατήστε τον
ακόλουθο σύνδεσμο.
http://www.mysite.dch/wp-login.php?action=rp&key=dWBF1extfudBP6Yrrq1P&login=admin
Εάν δεν αιτηθήκατε της
συγκεκριμένης υπενθύμισης
αγνοείστε το παρόν μήνυμα.
You can add a div to solve this issue :
<div style="width:600px;"></div>
Problem solved after a lot of hours of research.
Following the solution I have applied for other users may have the same issue in the future:
The wp_mail function, initiating a new PHPMAiler object. This object among the other properties has own called WordWrap. This property controlling the length of the text lines.
In order to change this property, or any of the properties of the WPMailer object execute the following code in your funcions.php.
function mailWordWrap($ar)
{
$ar->WordWrap = 150;
return $ar;
}
add_action('phpmailer_init', 'mailWordWrap', 10, 1);

error in sqlite database when loaded in php [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
SQLite database path not working
D:/wamp/www/umer.db
Warning: sqlite_query() [function.sqlite-query]: no such table: config in
D:\wamp\www\sqllite\index.php on line 15
Error in query: SQL logic error or missing database
I found this error when loaded data base in PHP. My source code is this:
<?php
$db = $_SERVER['DOCUMENT_ROOT']."umer.db";
echo $db;
$handle = sqlite_open($db) or
die("Could not open database".sqlite_error_string(sqlite_last_error($handle)));
$query = ("SELECT * FROM config");
$result = sqlite_query($handle,$query) or
die("Error in query: ".sqlite_error_string(sqlite_last_error($handle)));
if (sqlite_num_rows($result) > 0) {
echo "<table cellpadding=10 border=1>";
while($row = sqlite_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "</tr>";
}
echo "</table>";
}
sqlite_close($handle);
?>
Well, it looks like you don't have a config table:
D:/wamp/www/umer.db Warning: sqlite_query() [function.sqlite-query]:
no such table: config in <<<<< SEE HERE!
D:\wamp\www\sqllite\index.php on line 15
Error in query: SQL logic error or missing database
Are you sure that table exists?
It seems to be opening the database okay since the first error occurs on the sqlite_query() call.

Resources