Click here to Skip to main content
15,886,518 members
Articles / Internet of Things / Raspberry-Pi
Tip/Trick

Connect, Send and Receive data from web page to control PC/RaspberryPi

Rate me:
Please Sign up or sign in to vote.
3.55/5 (6 votes)
9 Jan 2019CPOL2 min read 13.9K   227   16   1
Control Anything from a web page using sockets and ports.

Image 1

Introduction

How to connect to RaspberryPi or any computer using WebPage and Socket so you can access it from any device. (Web server side) In this Article, you will learn how to connect php webpage to RaspberryPi or computer in the same network.

Background

Lately, I developed a robotics solution with remote control Web Application using simple and clean code of PHP, JavaScript, Socket, RaspberryPi, Arduino, LEDs, and Sensors I think it is a good opportunity to share it with the world by explaining them one by one so people can learn from it.

Using the code

This snippet of code is a full control scenario to control a microcontroller board RaspberryPi. The code will include: Firstly: Interface layer or front end with is a web HTML page. Which handle the events to backend, Secondly and the backend is PHP-based code. And finally, RaspberryPi code which will receive the commands and data from php server remotely.

Front End , Back End

Let's start by the first part : Front end contains WebPage as presentation layer.

1- Front End

For simplicity, we will draw a simple HTML page for device image and two Buttons for led on and off.

HTML code

HTML
<html>
	<body>
	..
	..
	<a href="run.php?op=on"> ON </a>// Turn On the Light
	...
	<a href="run.php?op=off"> Off </a> //Turn Off the Light 
	..

Trick: You can wrap it in Ajax as well to avoid refresh :)

Please refer to my trick: Simple Dynamic JavaScript Ajax Function

2- Back End

This is a php code which will connect to the RaspberryPi and send code to it. it will use Sockets.

BackEnd Items :

A- Connection

B- backend PHP page

Connection Socket class

Here is Socket PHP class for connect to RaspberryPi , it contains Read and Write data : read_data, socket_write Also contains open and close socket: open_socket , close_socket

/////////php Code///////
    class Socket{
    public $socket;
    public $host ;
    public $port;

       public function __construct($host,$port){
           $this->host = $host;
           $this->port = $port;

       }
       public function init()
       {
           $this->socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
       }
    public function open_socket()
    {
    $result = socket_connect($this->socket,$this->host,$this->port);
        return $result;
    }
    public function getStatus()
    {
        try
        {
            $status = socket_get_status($this->socket);
            if ($status['timed_out']) {
              return FALSE;
            }
            if ($status=="")
            {
                return TRUE;
            }
        }
        catch (Exception $e) {
            echo $e->getMessage();
        }
    }


       public function send_data($content){

           socket_write($this->socket,$content,strlen($content));

       }

       public function read_data(){
             while($buf = socket_read($this->socket, 1024))
            if($buf = trim($buf))
                break;
        return $buf;
       }

       public function close_socket(){
              socket_close($this->socket);
       }

    }
Prepare command string

To prepare the content of sending data we should commit a data string which we can recognize in RaspberryPi side, for example :

$on = "on";
$off = "off";
$data = "";
$operation = $_GET["op"];
if ($operation =="on")
{

$command = $on;
}
if ($operation =="off")
{

$command = $off;
}

C- Send the command

$connection->send_data($command);

B- backend PHP page

Full Backend Script file

run.php

#include("socket.php");
$RaspberryPiIP = '192.168.1.XXX'; // Change by your RaspberryPi/PC IP 
$RaspberryPiPORT = 5000; // Change by your RaspberryPi / PC Port Number ..
$connection = new Socket(RaspberryPiIP,$RaspberryPiPORT); // Create a new socet Connection object. 
$connection->init();

////////  Get Command from front end page

$on = "on";
$off = "off";
$data = "";
$operation = $_GET["op"];
if ($operation =="on")
{

$command = $on;
}
if ($operation =="off")
{

$command = $off;
}

//// end Get Command from front end page

$connection->open_socket(); // Connect PHP to RaspberryPi or computer.
$connection->send_data($command); //Send command String
$connection->close_socket(); //////////Close connection 
///////////// DONE :)  ///////////////

History

Next I will post Another article for how to receive Socket commands and Excecute it in RaspberryPi. Also I will upload the sourcecode for Full project in GitHub if you liked it. https://gitHub.com/ArabicRobotics

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader ArabicRobotics.com
Egypt Egypt
Tareq Gamal El-din Mohammed,
---------
Website:
www.ArabicRobotics.com

---------

Graduated from Modern Academy for Computer science and Information Technology. Egypt,
Then flow Microsoft development track Certificates:
MCAD.NET (Microsoft Certified Application Developer)
MCSD.NET (Microsoft Certified Solution Developer)
Microsoft SharePoint Administration, Configuration and Development.

Robotics fields was a Hobby since 2002,
started to develop some applications for "Robosapien", "RoboSapienV2", "RS Media", RoboMe and WowWee Rovio. from WowWee company,

Started working with robots as a professional way at 2014
By using "NAOqi" Robotics from Aldebaran.

By developing some applications and libraries like :
NAO.NET.
https://www.youtube.com/watch?v=oOyy-2XyT-c

OpenCV with NAO Robot:

- NAORobot Vision using OpenCV -TotaRobot P1
https://www.youtube.com/watch?v=MUcj8463x08

- NAO Robot Vision using OpenCV - P2
https://www.youtube.com/watch?v=93k1usaS-QM

NAO Alarm Clock :
https://www.youtube.com/watch?v=djLlMeGLqOU
-----------------------------

also Robotic Arm Project:


Other Projects Developed by Tareq Gamal El-din Mohammed :

Developed and posted some applications in Code Project web site like :

- Control your Distributed Application using Windows and Web Service
http://www.codeproject.com/Articles/101895/Control-your-Distributed-Application-using-Windows


- Quick and dirty directory copy
http://www.codeproject.com/Articles/12745/Quick-and-dirty-directory-copy

- Program Execute Timer(From the Web)
http://www.codeproject.com/Articles/12743/Program-Executer-Timer

Comments and Discussions

 
-- No messages could be retrieved (timeout) --