This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Basic Internet of Things Tutorial Using Raspberry Pi and Cloudways Laravel Cloud

Updated on December 27, 2021

6 Min Read
iot basic tutorial

Internet of Things (IoT)—or as I like to explain it—is simply the Extended Internet. It is a fabric of systems that can be a gadget, a device, a machine, or even your pet that are uniquely identified over the network without human to computer interactions.

According to Google, there is the potential for 50 billion connected devices by 2020. With embedded computers becoming commonplace, we are reaching new avenues to explore the true potential of the Internet. We are expanding our capabilities to grab as much data as possible.

With such advancement, nobody would like to miss a chance to enter this area as soon as possible. Whether you have a cash machine at your store which you want continuous updates for, servers that continuously require health monitoring, or simple wireless nodes you have made to monitor the electricity consumption of your office and home.

It will help you gain new data-driven insights and drive actions from IoT by connecting, analyzing, and integrating device data into your business processes and applications; enabling your business to deliver innovative services faster and with less risk.

Why IoT With Cloud?

IoT ensures the continuous data collection from your deployed nodes, which in return brings large data into your server and the Cloud helps you scale up or down depending on your needs.

Tada! It’s as simple as that.

With high connectivity and backup ability, your cloud will make sure you have your nodes accessible across the globe and have tendencies to grow on your demand.

Creating an IoT device via Cloudways

For this tutorial, we will use a Raspberry Pi computer to create an IoT device. Through this device, you can do the following things:

  • You can deploy your apps in a single click.
  • You can scale them in a single click.
  • You can manage your apps smoothly

You can use Python at the server end to analyze your gathered data with immense computing power—”pay as you go computing” power. (Python is not officially supported as of now but us geeks can actually get our things done.)

Well, let’s start with our tutorial today. First, we look into our objective:

  • We are developing a simple Laravel based logging mechanism, which will connect our Raspberry Pi to our remote server.
  • We will then make our Pi gather local information and send it to your Cloudways server. Now we won’t be teaching here how to use GPIOs and stuff, that is something you can find at various other places. Here we will discuss integrating the marvelous PHP Laravel framework.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Prerequisites

You will need the following stuff to get things started:

  • You must have launched a Laravel app on Cloudways. (If not, click here.
  • You should have a Raspberry Pi. If not, it’s OK you can test the code on your simple machine.
  • You must have some knowledge of PHP, Python, MySQL, and a little bit about Laravel.
  • We will be using VIM, so you better know how to exit and save. 😀

Any Raspberry Pi Laravel model can run a web server, such as Apache + PHP or Nginx + PHP, to serve a Laravel application. Likely the easiest way to utilize PHP with Raspberry Pi is through the shell_exec() function. This work lets you execute shell commands, so it can act as a sort of bridge between PHP and the Raspberry Pi. Within the most simple case, shell_exec() can call Python scripts that perform certain errands and control GPIO pinsc.

Getting Started

We will make two routes that present the entry point for our remote nodes to push the data and to get the details. We will then configure our controllers to create a database of our logs. In the end, we will make our views display our logs in table form. In integrating IoT solutions like MQTT Raspberry PI, it’s essential to understand the communication protocols and data handling involved. MQTT, a lightweight messaging protocol for small sensors and mobile devices, is ideal for IoT applications using Raspberry Pi due to its low bandwidth usage and effective data distribution methods. By utilizing MQTT with Raspberry Pi, iot development company can efficiently manage real-time data communication between various IoT devices, enhancing the capabilities of their IoT systems.

Establishing a Connecting With MySQL Database

Well, we will need a database of course.

  • Inside Cloudways, navigate to Application > Access Details > Launch Database Manager.
  • Click on the Create Table button.
  • Name the table “CPU” and add the following fields:
    • id (int auto incr)
    • date
    • time
    • usage (float)
    • status (string)
  • Now in your public_html folder, there is a .env file. Add your database details like following:
DB_DATABASE=XXxXXxxxXx

DB_USERNAME=XXXxxxXXXX

DB_PASSWORD=XXXxxxXXXX
  • Don’t forget to change XxXxxx with your Database name and password.

Making Our Routes

You will need this API routes as entry points. Through these, we can push our data.

  • Routes are placed in App/Http/routes.php
  • Add the two following routes
Route::get('/datago/{usage}/{status}',['uses'=>"LogController@storeData"]);

Route::get('/datashow',"LogController@showData");
  • First Route pushes the data CPU usage and CPU status. It then passes it to our Controller ( LogController ) which has the function StoreData . We will make this controller in a moment.
  • Second Route simply calls the function ShowData of our controller LogController .

Creating a Controller

We require this to safely handle requests for IoT devices.

  • Controllers are placed in App/Http/Controllers/<Controller_Name>.php
  • By default, there is a Controller made for you. We will just extend this controller to make our own controller named LogController .
  • Make App/Http/Controllers/ LogController .php file.
  • Paste the following code.
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\View;

use Illuminate\Database\Eloquent\Model;

use DB;

class LogController extends Controller

{

public function showData (){

$results = DB::select('select * from cpu'); //query to fetch all the records in an array

       return View::make('showdata',['data'=>$results]);   //passing this array (results) with a key (data)

}

       public function storeData ($usage,$status){

       DB::table('cpu')->insert( //insert into table cpu

[ 'date' => DB::raw('now()') , 'time'=> DB::raw('now()') , 'usage'=>$usage , 'status'=>$status]

       );

return response()->json(200); //return 200 response when done.

               }

}

?>

To use the controllers, we have to define the namespace. We have to give the fetching directories of our Views and Models.

Creating the View

This will create a presentable output for your data logs.

  • Views are placed in public_html/resources/views folder
  • Make a view and use showdata.blade.php as its name. This is the naming conventions PHP uses for Views.
  • Paste the following code.
<!DOCTYPE html>

<html>

<body>

<title>Raspberry PI Data Logs</title>

<h1>Raspberry PI Data Logs</h1>

<table style="width:100%">

 <tr>

   <td>Date</td>

   <td>time</td>

   <td>Cpu Usage % </td>

   <td>Status</td>

 </tr>

 <tr>

 @foreach($data as $values) //data from controller is retrieved by view in "data" key.

 <tr>

   <td> {{ $values->date }}</td>

   <td> {{ $values->time }}</td>

   <td> {{ $values->usage }}</td>

   <td> {{ $values->status }}</td>

 </tr>

 @endforeach

</table>

</body>

</html>

So, this was all we had to do on the server side. You can alter your code according to your desired results. Now, let’s get our little script running on a Raspberry PI device which brings us the CPU usage to our server. I have used a sneaky way to find out CPU usage. :p You can use your own method to make the script shorter.

import time
import urllib2



INTERVAL = 0.1
def getTimeList():
    """
    Fetches a list of time units the cpu has spent in various modes
    Detailed explanation at http://www.linuxhowtos.org/System/procstat.htm
    """
    cpuStats = file("/proc/stat", "r").readline()
    columns = cpuStats.replace("cpu", "").split(" ")
    return map(int, filter(None, columns))
def deltaTime(interval):
    """
    Returns the difference of the cpu statistics returned by getTimeList
    that occurred in the given time delta
    """
    timeList1 = getTimeList()
    time.sleep(interval)
    timeList2 = getTimeList()
    return [(t2-t1) for t1, t2 in zip(timeList1, timeList2)]
def getCpuLoad():
    """
    Returns the cpu load as a value from the interval [0.0, 1.0]
    """
    dt = list(deltaTime(INTERVAL))
    idle_time = float(dt[3])
    total_time = sum(dt)
    load = 1-(idle_time/total_time)
    return load
	
def main ():
	while(True):
		 usage=0;											
		 status="fail"
		 time.sleep(2)
		 usage=str(getCpuLoad()*100.0)
		 url="http://phplaravel-14171-43979-113153.cloudwaysapps.com/datago/"	//base URL
		 if (usage != 0):
			status="OK"
		 else:
			status="fail"
		 data=(urllib2.urlopen(url+usage+'/'+status).read())	//URL appended
		 print data
main()

Now, let’s test our code.

Run the Python Code in your Pi:

python code.py

You will see the following results.

Now, let’s visit our Laravel app. Paste the link in your browser. I have my live app here:

http://phplaravel-14171-43979-113153.cloudwaysapps.com/datashow

Your logs should be somewhere like this.

The World Is Your Oyster (or Raspberry Pi)

So, here you go with our tiny little objective, which I guess is enough for you guys to carry on with your IoT projects. You can use different charts libraries too to get real-time plotting.

I have come across LavaCharts, which is a powerful graph and charts library of Laravel. I will try to make something out of it if I get the chance. Till then, see ya—and oh yeah, here is the repo link in case you need the complete project.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now