03.12.2015 Views

laravel4cookbook

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Embedded Systems 301<br />

.<br />

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

We’re using PHP file read/write methods to communicate with the Arduino. In our fire() method,<br />

we open a connection to the Arduino and store it in $this->device. We also set the stream to nonblocking.<br />

This is so that read requests to the Arduino don’t wait until data is returned before allowing<br />

the rest of the PHP processing to take place.<br />

In the __construct() method we also modify the message event listener to write the incoming<br />

message (from the browser) to the Arduino. We read any info the Arduino has and send it back<br />

to the socket. This effectively creates a bridge between the Arduino and the socket.<br />

We’ve also added two additional methods. The getArguments() method stipulates a required device<br />

argument. We want the serve command to be able to use any device name, so this argument makes<br />

sense. We’ve also added a __destruct() method to close the connection to the Arduino.<br />

Finally, we need to add some JavaScript to read and write from the Arduino:<br />

1 try {<br />

2 if (!WebSocket) {<br />

3 console.log("no websocket support");<br />

4 } else {<br />

5<br />

6 var socket = new WebSocket("ws://127.0.0.1:8081/");<br />

7 var sensor = $("[name='sensor']");<br />

8 var led = $("[name='led']");<br />

9 var x = $("[name='x']");<br />

10 var y = $("[name='y']");<br />

11<br />

12 socket.addEventListener("open", function (e) {<br />

13 socket.send("pinMode,6,output.");<br />

14 socket.send("pinMode,3,servo.");<br />

15 socket.send("pinMode,5,servo.");<br />

16 });<br />

17<br />

18 socket.addEventListener("error", function (e) {<br />

19 // console.log("error: ", e);<br />

20 });<br />

21<br />

22 socket.addEventListener("message", function (e) {<br />

23<br />

24 var data = e.data;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!