Laravel 4 Embedded Systems

A Comprehensive Tutorial

Christopher Pitt
Jan 9, 2014 · 11 min read

What do you think of when you hear the name Laravel? Laravel 4 powers an increasing number of websites, but that’s not the only place it can be used. In this tutorial we’re going to use it to control embedded systems.

While much effort has been spent in the pursuit of accuracy; there’s a good chance you could stumble across a curly quote in a code listing, or some other egregious errata. Please make a note and I will fix where needed.

I have also uploaded this code to Github. You need simply follow the configuration instructions in this tutorial, after downloading the source code, and the application should run fine.

This assumes, of course, that you know how to do that sort of thing. If not; this shouldn’t be the first place you learn about making PHP applications.

https://github.com/formativ/tutorial-laravel-4-embedded-systems

If you spot differences between this tutorial and that source code, please raise it here or as a GitHub issue. Your help is greatly appreciated.

Gathering Parts

This tutorial demonstrates the use of an Arduino and a web cam. There are other smaller parts, but these are the main ones. The Arduino needs firmata installed (explained later) and the webcam needs to be compatible with Linux and Motion (installed later).

We will go over using things like LEDs and resistors, but none of those are particularly important. We will also go over using servos and these are important. You can find the bracket I use at: https://www.sparkfun.com/
products/10335
and the servos I use at: https://www.sparkfun.com/
products/9065
. You can get these parts, and an Arduino Uno, for less than $55.

Installing Dependencies

We’re developing a Laravel 4 application which has lots of server-side aspects; but there’s also an interactive interface. There be scripts!

For this; we’re using Bootstrap and jQuery. Download Bootstrap at: http://getbootstrap.com/ and unpack it into your public folder. Where you put the individual files makes little difference, but I have put the scripts in public/js, the stylesheets in public/css and the fonts in public/fonts. Where you see those paths in my source code; you should substitute them with your own.

Next up, download jQuery at: http://jquery.com/download/ and unpack it into your public folder.

For the server-side portion of dependencies, we need to download a library called Ratchet. I’ll explain it shortly, but in the meantime we need to add it to our composer.json file:

"require" : {
"laravel/framework" : "4.0.*",
"cboden/Ratchet" : "0.3.*"
},

This was extracted from composer.json.

Follow that up with:

composer update

Ratchet isn’t built specifically for Laravel 4, so there are no service providers for us to add.

We’ll now have access to the Ratchet library for client-server communication, Bootstrap for styling the interface and jQuery for connecting these two things together.

Note About Errata

I love all things Arduino and Raspberry Pi. When I’m not programming; I’m trying to build things (in the real world) which can interact with my programming. Don’t let that fool you though: I am not an expert in electronics. There are bound to be better ways to do all of this stuff.

If you can’t get a specific program installed because apt or permissions or network settings or aliens; I cannot help you. I have neither the time nor the experience to guide you through the many potential problems. Hit me up on Twitter and, if I have not yet already done so, I will connect you to a forum where you can discuss this with other (smarter) people.

Creating An Interface

The first step to creating an interface is returning static HTML for a web request. We handle this by creating a route, a controller and a view:

<?php

Route::get("/", [
"as" => "index/index",
"uses" => "IndexController@indexAction"
]);

This file should be saved as app/routes.php.

<?php

class IndexController
extends BaseController
{
public function indexAction()
{
return View::make("index/index");
}
}

This file should be saved as app/controllers/IndexController.php.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Laravel 4 Embedded Systems</title>
<link rel="stylesheet" href="/css/bootstrap.3.0.0.css" />
<link rel="stylesheet" href="/css/bootstrap.theme.3.0.0.css" />
<link rel="stylesheet" href="/css/shared.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Laravel 4 Embedded Systems</h1>
<input type="number" max="255" min="0" name="led" />
<input type="number" min="0" name="sensor" />
<input type="number" max="180" min="0" name="x" />
<input type="number" max="180" min="0" name="y" />
</div>
</div>
</div>
<script src="/js/jquery.1.9.1.js"></script>
<script src="/js/shared.js"></script>
</body>
</html>

This file should be saved as app/views/index/index.blade.php.

If you’ve created all of these files (and configured your web server to serve the Laravel application) then you should see a set of controls in your browser, when you visit /. Before we move on; let’s just quickly set up a socket server for this interface to talk to the PHP server with….

Creating A Socket Server

We’ve covered this topic before; so I won’t go into too much detail. We’re going to set up a Ratchet socket server, to pass messages back and forth between the interface and the PHP server.

try {
if (!WebSocket) {
console.log("no websocket support");
} else {

var socket = new WebSocket("ws://127.0.0.1:8081/");

socket.addEventListener("open", function (e) {
console.log("open: ", e);
});

socket.addEventListener("error", function (e) {
// console.log("error: ", e);
});

socket.addEventListener("message", function (e) {
var data = JSON.parse(e.data);
console.log("message: ", data);
});

// console.log("socket:", socket);

window.socket = socket;

}
} catch (e) {
// console.log("exception: " + e);
}

This file should be saved as public/js/shared.js.

<?php

namespace Formativ\Embedded;

use Evenement\EventEmitter;
use Illuminate\Support\ServiceProvider;

class EmbeddedServiceProvider
extends ServiceProvider
{
protected $defer = true;

public function register()
{
$this->app->bind("embedded.emitter", function()
{
return new EventEmitter();
});

$this->app->bind("embedded.command.serve", function()
{
return new Command\Serve(
$this->app->make("embedded.socket")
);
});

$this->app->bind("embedded.socket", function()
{
return new Socket(
$this->app->make("embedded.emitter")
);
});

$this->commands(
"embedded.command.serve"
);
}

public function provides()
{
return [
"embedded.emitter",
"embedded.command.serve",
"embedded.socket"
];
}
}

This file should be saved as workbench/formativ/embedded/src/
Formativ/Embedded/EmbeddedServiceController.php
.

<?php

namespace Formativ\Embedded;

use Evenement\EventEmitterInterface;
use Ratchet\MessageComponentInterface;

interface SocketInterface
extends MessageComponentInterface
{
public function getEmitter();
public function setEmitter(EventEmitterInterface $emitter);
}

This file should be saved as workbench/formativ/embedded/src/
Formativ/Embedded/SocketInterface.php
.

<?php

namespace Formativ\Embedded;

use Evenement\EventEmitterInterface as Emitter;
use Exception;
use Ratchet\ConnectionInterface as Connection;

class Socket
implements SocketInterface
{
protected $emitter;

protected $connection;

public function getEmitter()
{
return $this->emitter;
}

public function setEmitter(Emitter $emitter)
{
$this->emitter = $emitter;
}

public function __construct(Emitter $emitter)
{
$this->emitter = $emitter;
}

public function onOpen(Connection $connection)
{
$this->connection = $connection;
$this->emitter->emit("open");
}

public function onMessage(Connection $connection, $message)
{
$this->emitter->emit("message", [$message]);
}

public function onClose(Connection $connection)
{
$this->connection = null;
}

public function onError(Connection $connection, Exception $e)
{
$this->emitter->emit("error", [$e]);
}

public function send($message)
{
if ($this->connection)
{
$this->connection->send($message);
}
}
}

This file should be saved as workbench/formativ/embedded/src/
Formativ/Embedded/Socket.php
.

The Socket class only has room for a single connection. Feel free to change this so that it can handle any number of controlling connections.

<?php

namespace Formativ\Embedded\Command;

use Formativ\Embedded\SocketInterface;
use Illuminate\Console\Command;
use Ratchet\ConnectionInterface;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class Serve
extends Command
{
protected $name = "embedded:serve";

protected $description = "Creates a firmata socket server.";

public function __construct(SocketInterface $socket)
{
parent::__construct();

$this->socket = $socket;

$socket->getEmitter()->on("message", function($message) {
$this->info("Message: " . $message . ".");
});

$socket->getEmitter()->on("error", function($e) {
$this->line("Exception: " . $e->getMessage() . ".");
});
}

public function fire()
{
$port = (integer) $this->option("port");

$server = IoServer::factory(
new HttpServer(
new WsServer(
$this->socket
)
),
$port
);

$this->info("Listening on port " . $port . ".");
$server->run();
}

protected function getOptions()
{
return [
[
"port",
null,
InputOption::VALUE_REQUIRED,
"Port to listen on.",
8081
]
];
}
}

This file should be saved as workbench/formativ/embedded/src/
Formativ/Embedded/Command/Serve.php
.

These four files create a means with which we can start a socket server, listen for messages and respond to them. The shared.js file connects to this server and allows us to send and receive these messages. It’s simpler than last time; but sufficient for our needs!

Connection To Arduino

Real-time communication is typically done through a software layer called Firmata. There are Firmata libraries for many programming languages, though PHP is not one of them. While there is one library listed on the official Firmata website, I could not get it to work.

So we’re going to create our own simple Firmata-like protocol. I managed to put one together that handles analog reads, analog writes and servo control. It does this by parsing strings received over serial connection. This is what it looks like:

#include <Servo.h>

String buffer = "";
String parts[3];
Servo servos[13];
int index = 0;

void setup()
{
Serial.begin(9600);
buffer.reserve(200);
}

void loop()
{

}

void handle()
{
int pin = parts[1].toInt();
int value = parts[2].toInt();

if (parts[0] == "pinMode")
{
if (parts[2] == "output")
{
pinMode(pin, OUTPUT);
}

if (parts[2] == "servo")
{
servos[pin].attach(pin);
}
}

if (parts[0] == "digitalWrite")
{
if (parts[2] == "high")
{
digitalWrite(pin, HIGH);
}
else
{
digitalWrite(pin, LOW);
}
}

if (parts[0] == "analogWrite")
{
analogWrite(pin, value);
}

if (parts[0] == "servoWrite")
{
servos[pin].write(value);
}

if (parts[0] == "analogRead")
{
value = analogRead(pin);
}

Serial.print(parts[0] + "," + parts[1] + "," + value + ".\n");
}

void serialEvent()
{
while (Serial.available())
{
char in = (char) Serial.read();

if (in == '.' || in == ',')
{
parts[index] = String(buffer);
buffer = "";

index++;

if (index > 2)
{
index = 0;
}
}
else
{
buffer += in;
}

if (in == '.')
{
index = 0;
buffer = "";
handle();
}
}
}

This code needs to be uploaded to the Arduino you’re working with for any communication between our server and the Arduino to take place.

The Arduino sketch is only one side of the puzzle. We also need to modify our socket server to communicate with the Arduino:

public function __construct(SocketInterface $socket)
{
parent::__construct();

$this->socket = $socket;

$socket->getEmitter()->on("message", function($message)
{
fwrite($this->device, $message);

$data = trim(stream_get_contents($this->device));
$this->info($data);

$this->socket->send($data);
});

$socket->getEmitter()->on("error", function($e)
{
$this->line("exception: " . $e->getMessage() . ".");
});
}

public function fire()
{
$this->device = fopen($this->argument("device"), "r+");
stream_set_blocking($this->device, 0);

$port = (integer) $this->option("port");

$server = IoServer::factory(
new HttpServer(
new WsServer(
$this->socket
)
),
$port
);

$this->info("Listening on port " . $port . ".");
$server->run();
}

protected function getArguments()
{
return [
[
"device",
InputArgument::REQUIRED,
"Device to use."
]
];
}

public function __destruct()
{
if (is_resource($this->device)) {
fclose($this->device);
}
}

We’re using PHP file read/write methods to communicate with the Arduino. In our fire() method, we open a connection to the Arduino and store it in $this->device. We also set the stream to non-blocking. This is so that read requests to the Arduino don’t wait until data is returned before allowing the rest of the PHP processing to take place.

In the __construct() method we also modify the message event listener to write the incoming message (from the browser) to the Arduino. We read any info the Arduino has and send it back to the socket. This effectively creates a bridge between the Arduino and the socket.

We’ve also added two additional methods. The getArguments() method stipulates a required device argument. We want the serve command to be able to use any device name, so this argument makes sense. We’ve also added a __destruct() method to close the connection to the Arduino.

Finally, we need to add some JavaScript to read and write from the Arduino:

try {
if (!WebSocket) {
console.log("no websocket support");
} else {

var socket = new WebSocket("ws://127.0.0.1:8081/");
var sensor = $("[name='sensor']");
var led = $("[name='led']");
var x = $("[name='x']");
var y = $("[name='y']");

socket.addEventListener("open", function (e) {
socket.send("pinMode,6,output.");
socket.send("pinMode,3,servo.");
socket.send("pinMode,5,servo.");
});

socket.addEventListener("error", function (e) {
// console.log("error: ", e);
});

socket.addEventListener("message", function (e) {

var data = e.data;
var parts = data.split(",");

if (parts[0] == "analogRead") {
sensor.val(parseInt(parts[2], 10));
}

});

window.socket = socket;

led.on("change", function() {
socket.send("analogWrite,6," + led.val() + ".");
});

x.on("change", function() {
socket.send("servoWrite,5," + x.val() + ".");
});

y.on("change", function() {
socket.send("analogWrite,3," + y.val() + ".");
});

setInterval(function() {
socket.send("analogRead,0,void.");
}, 1000);

}
} catch (e) {
// console.log("exception: " + e);
}

This script does a number of cool things. When it loads, we set the pinMode of the LED pin (6) and the two servo pins (3, 5) to the correct modes. We also attach a message event listener to receive and parse messages from the Arduino.

We then attach some event listeners for the input elements in the interface. These will respond to changes in value by sending signals to the Arduino to adjust its various pin values.

Finally, we set a timer to ping the Arduino with analogRead requests on the sensor pin. Thanks to the message event listener, the return values will be received and reflected in the sensor input field.

Spinning Up

To connect to the Arduino, you should run the following command:

php artisan embedded:serve /dev/cu.usbmodem1411

On my system, the Arduino is reflected as /dev/cu.usbmodem1411 by this may differ on yours. For instance, my Ubuntu machine shows it as /dev/ttyACM0. The easiest way to find out what it is, is to unplug it, then run the following command:

ls /dev/tty*

Look over the list to familiarise yourself with the devices you see there. The plug the Arduino in, wait a couple seconds and run that command again. This time you should see a new addition to the list of devices. This is most likely your Arduino.

You may be wondering why my device starts with cu and not tty. I first tried the tty version of the Arduino and it would cause the server to hang. I experimented and found that the cu version let me connect and communicate with the Arduino. Go figure…

I usually like to include Vagrant configurations for running these projects. This time I found it confusing to try and communicate with an Arduino through the host machine. So instead I decided to try the server.php script bundled with Laravel applications. Turns out you can run the server with the following command:

php -S 127.0.0.1:8080 -t ./public server.php

Now you can go to http://127.0.0.1:8080 and see the interface we created earlier. You need to start the serve command successfully before this interface will work. If everything is running correctly, you should immediately start to see the sensor values being updated in the interface.

You can now adjust the LED input to control the brightness of the LED, and the x and y inputs to control the rotation of the servos.

Adding A Webcam

Streaming video from a web cam can be tricky, so we’re going to take time-lapse photos instead…

The utility we’ll be using on OSX is called ImageSnap. We can install it with homebrew:

brew install imagesnap

Once that’s installed; we can periodically take photos with it by using a command resembling:

imagesnap -d "Microsoft LifeCam" -w 3

The web cam I am using is Microsoft LifeCam but you can find the appropriate one for you with the command:

imagesnap -l

I also had to add some warm-up time, with the -w switch.

The utility we’ll be using on Ubuntu/Debian is called Streamer. We can install it with the command:

apt-get install -y streamer

You can take a photo with the web cam, using the following command:

streamer -o snapshot.jpeg

Depending on whether you are using OSX or Ubuntu/Debian; you will need to set up a shell script to periodically take photos. Save them to a web-accessible location and display them with the following changes:

<img name="photo" />

This was extracted from app/views/index/index.blade.php.

setInterval(function() {
$("[name='photo']").attr("src", "[path to photo]");
}, 1000);

This was extracted from public/js/shared.js.

Conclusion

If you enjoyed this tutorial; it would be helpful if you could click the Recommend button.


This tutorial comes from a book I’m writing. If you like it and want to support future tutorials; please consider buying it. Half of all sales go to Laravel.

Laravel 4 Tutorials

Things you can build with Laravel 4.

    Christopher Pitt

    Written by

    Programming → Robotics → Minecraft

    Laravel 4 Tutorials

    Things you can build with Laravel 4.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade