SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
FrOSCon 2013
Controlling Arduino With PHP
About Me
● Thomas Weinert
– @ThomasWeinert
● papaya Software GmbH
– papaya CMS
● PHP, Javascript, XSLT
● XML Fanatic (JSON is BAD)
Arduino
Arduino Mega
Arduino Nano
Arduino Nano Breadboard
Arduino Nano Breakout
Arduino IDE
Firmata
● MIDI Based
● Serial Port
– Forks for TCP
● http://firmata.org
Non-Blocking I/O
● Event Loop
● Event Emitter
● Promises
Event Loop
Listeners
Loop
External
Process
External
Process
File
Event Loop
● Timeouts
● Intervals
● Stream Listeners
● Implementations
– StreamSelect
– LibEvent
– MySQLi
Browser Example
var e = document.getElementById('output');
var counter = 0;
var interval = window.setInterval(
function() {
e.textContent =
e.textContent +
counter.toString() +
', ';
counter++;
},
1000
);
Event Emitter
Object
Event
Callback
Callback
Event
Callback
Event Event
● Attach
● on(), once()
● Trigger
● emit()
Event Emitter Example
$stream = new StreamFile('c:/tmp/sample.txt');
$stream->events()->on(
'read-data',
function($data) {
echo $data;
}
);
$stream->events()->on(
'error',
function($error) use ($loop) {
echo $error;
$loop->stop();
}
);
Promises
● Asynchronous Condition
● Attach Callbacks
– done()
– fail()
– always()
● Change Status
– reject()
– resolve()
jQuery Example
jQuery(
function () {
jQuery
.get('hello-world.xml')
.done(
function (xml) {
$('#output').text(
$('data', xml).text()
);
}
);
}
);
Carica Projects
● Carica I/O
– https://bitbucket.org/ThomasWeinert/carica-io
● Carica Firmata
– https://bitbucket.org/ThomasWeinert/carica-firmata
● Carica Chip
– https://bitbucket.org/ThomasWeinert/carica-chip
Carica I/O
● Event Loop
– CaricaIoEventLoop
● Event Emitter
– CaricaIoEventEmitter
● Promises
– CaricaIoDeferred
– CaricaIoDeferredPromise
Timers
$loop = LoopFactory::get();
$i = 0;
$loop->setInterval(
function () use (&$i) {
echo $i++;
},
1000
);
$loop->setTimeout(
function () use ($loop) {
$loop->stop();
},
10000
);
$loop->run();
Asynchronous MySQL
$mysqlOne = new IoDeferredMySQL(
new mysqli('localhost')
);
$mysqlTwo = new IoDeferredMySQL(
new mysqli('localhost')
);
$time = microtime(TRUE);
$debug = function($result) use ($time) {
var_dump(iterator_to_array($result));
var_dump(microtime(TRUE) - $time);
};
$queries = IoDeferred::When(
$mysqlOne("SELECT 'Query 1', SLEEP(5)")
->done($debug),
$mysqlTwo("SELECT 'Query 2', SLEEP(1)")
->done($debug)
);
IoEventLoopFactory::run($queries);
Asynchronous MySQL
HTTP Server
Why?
HTTP Server
● PHP Daemons
– Single process for all pequests
– Share variables
Carica HTTP Server
<?php
include(__DIR__.'/../../src/Carica/Io/Loader.php');
CaricaIoLoader::register();
use CaricaIoNetworkHttp;
$route = new CaricaIoNetworkHttpRoute();
$route->startsWith(
'/files', new HttpRouteFile(__DIR__)
);
$server = new CaricaIoNetworkHttpServer($route);
$server->listen(8080);
CaricaIoEventLoopFactory::run();
Carica Firmata
Carica Firmata Board
<?php
$board = new FirmataBoard(
new IoStreamSerial(
CARICA_FIRMATA_SERIAL_DEVICE,
CARICA_FIRMATA_SERIAL_BAUD
)
);
$board
->activate()
->done(
function () use ($board) { ... }
);
CaricaIoEventLoopFactory::run();
Carica Firmata Pins
function () use ($board) {
$buttonPin = 2;
$ledPin = 13;
$board->pins[$buttonPin]->mode = FirmataPIN_STATE_INPUT;
$board->pins[$ledPin]->mode = FirmataPIN_STATE_OUTPUT;
$board->digitalRead(
$buttonPin,
function($value) use ($board, $ledPin) {
$board->pins[$ledPin]->digital =
$value == FirmataDIGITAL_HIGH;
}
);
}
Example: Blink
function () use ($board, $loop) {
$led = 9;
$board->pinMode($led, FirmataPIN_STATE_OUTPUT);
$loop->setInterval(
function () use ($board, $led) {
static $ledOn = TRUE;
echo 'LED: '.($ledOn ? 'on' : 'off')."n";
$board->digitalWrite(
$led,
$ledOn
? FirmataDIGITAL_HIGH : FirmataDIGITAL_LOW
);
$ledOn = !$ledOn;
},
1000
);
}
RGB Wheel
Carica Chip
● Hardware Abstraction
● Device Objects
LED
function () use ($board) {
$led = new CaricaChipLed($board, 9);
$led->blink();
}
RGB LED
function () use ($board) {
$colors = array('#F00', '#0F0', '#00F');
$led = new CaricaChipLedRgb($board, 10, 11, 9);
$led->setColor('#000');
$index = 0;
$next = function() use ($led, $colors, &$index, &$next) {
if (isset($colors[$index])) {
$color = $colors[$index];
$led->fadeTo($color)->done($next);
}
if (++$index >= count($colors)) {
$index = 0;
}
};
$next();
}
Servo
function () use ($board, $loop) {
$positions = array(
0, 45, 90, 180
);
$servo = new CaricaChipServo($board, 7, -180);
$index = 0;
$loop->setInterval(
$next = function () use ($servo, $positions, &$index) {
if (isset($positions[$index])) {
$position = $positions[$index];
$servo->moveTo($position);
echo $position, " Grad , ", $servo->getPosition(), " Gradn";
}
if (++$index >= count($positions)) {
$index = 0;
}
},
2000
);
$next();
}
Analog Sensor
function () use ($board) {
$sensor = new CaricaChipSensorAnalog($board, 14);
$sensor->onChange(
function ($sensor) {
echo $sensor, "n";
}
);
}
Thank You
● Questions?
● Twitter: @ThomasWeinert
● Blog: http://a-basketful-of-papayas.net

Más contenido relacionado

La actualidad más candente

Isi and nyquist criterion
Isi and nyquist criterionIsi and nyquist criterion
Isi and nyquist criterion
srkrishna341
 
Gi Fi - Fastest Wireless Transfer Technology
Gi Fi - Fastest Wireless Transfer TechnologyGi Fi - Fastest Wireless Transfer Technology
Gi Fi - Fastest Wireless Transfer Technology
Pradeep Rapolu
 
10 gigabit ethernet technology
10 gigabit ethernet technology10 gigabit ethernet technology
10 gigabit ethernet technology
Likan Patra
 
Lecture 8-9 block-diagram_representation_of_control_systems
Lecture 8-9 block-diagram_representation_of_control_systemsLecture 8-9 block-diagram_representation_of_control_systems
Lecture 8-9 block-diagram_representation_of_control_systems
Saifullah Memon
 
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)
Surbhi Maheshwari
 
Reduction of multiple subsystem [compatibility mode]
Reduction of multiple subsystem [compatibility mode]Reduction of multiple subsystem [compatibility mode]
Reduction of multiple subsystem [compatibility mode]
azroyyazid
 
Theory Communication
Theory CommunicationTheory Communication
Theory Communication
Hikari Riten
 

La actualidad más candente (20)

Gifi wireless Technology
Gifi wireless TechnologyGifi wireless Technology
Gifi wireless Technology
 
Pulse Code Modulation
Pulse Code Modulation Pulse Code Modulation
Pulse Code Modulation
 
Isi and nyquist criterion
Isi and nyquist criterionIsi and nyquist criterion
Isi and nyquist criterion
 
Gi Fi - Fastest Wireless Transfer Technology
Gi Fi - Fastest Wireless Transfer TechnologyGi Fi - Fastest Wireless Transfer Technology
Gi Fi - Fastest Wireless Transfer Technology
 
Controlling a home appliance using IR remote
Controlling a home appliance using IR remoteControlling a home appliance using IR remote
Controlling a home appliance using IR remote
 
Gi fi technology
Gi fi technologyGi fi technology
Gi fi technology
 
10 gigabit ethernet technology
10 gigabit ethernet technology10 gigabit ethernet technology
10 gigabit ethernet technology
 
Gi fi technology-Aditya sehgal
Gi fi technology-Aditya sehgalGi fi technology-Aditya sehgal
Gi fi technology-Aditya sehgal
 
Wifi tecnology
Wifi tecnology Wifi tecnology
Wifi tecnology
 
Lecture 8-9 block-diagram_representation_of_control_systems
Lecture 8-9 block-diagram_representation_of_control_systemsLecture 8-9 block-diagram_representation_of_control_systems
Lecture 8-9 block-diagram_representation_of_control_systems
 
Control chap4
Control chap4Control chap4
Control chap4
 
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)
 
Graficas de erlang b en matlab
Graficas de erlang b en matlabGraficas de erlang b en matlab
Graficas de erlang b en matlab
 
Frequency synthesizer(mm)
Frequency synthesizer(mm)Frequency synthesizer(mm)
Frequency synthesizer(mm)
 
Reduction of multiple subsystem [compatibility mode]
Reduction of multiple subsystem [compatibility mode]Reduction of multiple subsystem [compatibility mode]
Reduction of multiple subsystem [compatibility mode]
 
Theory Communication
Theory CommunicationTheory Communication
Theory Communication
 
Tutorials questions
Tutorials questionsTutorials questions
Tutorials questions
 
My Final Year Project - Individual Control Home Automation System
My Final Year Project - Individual Control Home Automation SystemMy Final Year Project - Individual Control Home Automation System
My Final Year Project - Individual Control Home Automation System
 
Digital Thermometer Arduino Based Abstract Details
Digital Thermometer Arduino Based Abstract DetailsDigital Thermometer Arduino Based Abstract Details
Digital Thermometer Arduino Based Abstract Details
 
311 pulse modulation
311 pulse modulation311 pulse modulation
311 pulse modulation
 

Similar a Controlling Arduino With PHP

Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHP
Thomas Weinert
 
YAPC::Brasil 2009, POE
YAPC::Brasil 2009, POEYAPC::Brasil 2009, POE
YAPC::Brasil 2009, POE
Thiago Rondon
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
Qiangning Hong
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
Simon Su
 
Jakob Holderbaum - Managing Shared secrets using basic Unix tools
Jakob Holderbaum - Managing Shared secrets using basic Unix toolsJakob Holderbaum - Managing Shared secrets using basic Unix tools
Jakob Holderbaum - Managing Shared secrets using basic Unix tools
DevSecCon
 
2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Heroku2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Heroku
ronnywang_tw
 

Similar a Controlling Arduino With PHP (20)

Phpconf 2013 - Agile Telephony Applications with PAMI and PAGI
Phpconf 2013 - Agile Telephony Applications with PAMI and PAGIPhpconf 2013 - Agile Telephony Applications with PAMI and PAGI
Phpconf 2013 - Agile Telephony Applications with PAMI and PAGI
 
Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHP
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers Steal
 
YAPC::Brasil 2009, POE
YAPC::Brasil 2009, POEYAPC::Brasil 2009, POE
YAPC::Brasil 2009, POE
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Job Managment Portlet
Job Managment PortletJob Managment Portlet
Job Managment Portlet
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
 
Application Layer in PHP
Application Layer in PHPApplication Layer in PHP
Application Layer in PHP
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
 
Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
 
PHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnPHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vuln
 
Jakob Holderbaum - Managing Shared secrets using basic Unix tools
Jakob Holderbaum - Managing Shared secrets using basic Unix toolsJakob Holderbaum - Managing Shared secrets using basic Unix tools
Jakob Holderbaum - Managing Shared secrets using basic Unix tools
 
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry PiMonitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
Monitoring Your ISP Using InfluxDB Cloud and Raspberry Pi
 
こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 
2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Heroku2012 coscup - Build your PHP application on Heroku
2012 coscup - Build your PHP application on Heroku
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 

Más de Thomas Weinert (13)

PHPUG CGN: Controlling Arduino With PHP
PHPUG CGN: Controlling Arduino With PHPPHPUG CGN: Controlling Arduino With PHP
PHPUG CGN: Controlling Arduino With PHP
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard Interfaces
 
Lumberjack XPath 101
Lumberjack XPath 101Lumberjack XPath 101
Lumberjack XPath 101
 
FluentDom
FluentDomFluentDom
FluentDom
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
 
Experiences With Pre Commit Hooks
Experiences With Pre Commit HooksExperiences With Pre Commit Hooks
Experiences With Pre Commit Hooks
 
The Lumber Mill - XSLT For Your Templates
The Lumber Mill  - XSLT For Your TemplatesThe Lumber Mill  - XSLT For Your Templates
The Lumber Mill - XSLT For Your Templates
 
The Lumber Mill Xslt For Your Templates
The Lumber Mill   Xslt For Your TemplatesThe Lumber Mill   Xslt For Your Templates
The Lumber Mill Xslt For Your Templates
 
SVN Hook
SVN HookSVN Hook
SVN Hook
 
Deliver Files With PHP
Deliver Files With PHPDeliver Files With PHP
Deliver Files With PHP
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
 
PHP 5.3/6
PHP 5.3/6PHP 5.3/6
PHP 5.3/6
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Controlling Arduino With PHP

  • 2. About Me ● Thomas Weinert – @ThomasWeinert ● papaya Software GmbH – papaya CMS ● PHP, Javascript, XSLT ● XML Fanatic (JSON is BAD)
  • 9. Firmata ● MIDI Based ● Serial Port – Forks for TCP ● http://firmata.org
  • 10. Non-Blocking I/O ● Event Loop ● Event Emitter ● Promises
  • 12. Event Loop ● Timeouts ● Intervals ● Stream Listeners ● Implementations – StreamSelect – LibEvent – MySQLi
  • 13. Browser Example var e = document.getElementById('output'); var counter = 0; var interval = window.setInterval( function() { e.textContent = e.textContent + counter.toString() + ', '; counter++; }, 1000 );
  • 14. Event Emitter Object Event Callback Callback Event Callback Event Event ● Attach ● on(), once() ● Trigger ● emit()
  • 15. Event Emitter Example $stream = new StreamFile('c:/tmp/sample.txt'); $stream->events()->on( 'read-data', function($data) { echo $data; } ); $stream->events()->on( 'error', function($error) use ($loop) { echo $error; $loop->stop(); } );
  • 16. Promises ● Asynchronous Condition ● Attach Callbacks – done() – fail() – always() ● Change Status – reject() – resolve()
  • 17. jQuery Example jQuery( function () { jQuery .get('hello-world.xml') .done( function (xml) { $('#output').text( $('data', xml).text() ); } ); } );
  • 18. Carica Projects ● Carica I/O – https://bitbucket.org/ThomasWeinert/carica-io ● Carica Firmata – https://bitbucket.org/ThomasWeinert/carica-firmata ● Carica Chip – https://bitbucket.org/ThomasWeinert/carica-chip
  • 19. Carica I/O ● Event Loop – CaricaIoEventLoop ● Event Emitter – CaricaIoEventEmitter ● Promises – CaricaIoDeferred – CaricaIoDeferredPromise
  • 20. Timers $loop = LoopFactory::get(); $i = 0; $loop->setInterval( function () use (&$i) { echo $i++; }, 1000 ); $loop->setTimeout( function () use ($loop) { $loop->stop(); }, 10000 ); $loop->run();
  • 21. Asynchronous MySQL $mysqlOne = new IoDeferredMySQL( new mysqli('localhost') ); $mysqlTwo = new IoDeferredMySQL( new mysqli('localhost') ); $time = microtime(TRUE); $debug = function($result) use ($time) { var_dump(iterator_to_array($result)); var_dump(microtime(TRUE) - $time); }; $queries = IoDeferred::When( $mysqlOne("SELECT 'Query 1', SLEEP(5)") ->done($debug), $mysqlTwo("SELECT 'Query 2', SLEEP(1)") ->done($debug) ); IoEventLoopFactory::run($queries);
  • 24. HTTP Server ● PHP Daemons – Single process for all pequests – Share variables
  • 25. Carica HTTP Server <?php include(__DIR__.'/../../src/Carica/Io/Loader.php'); CaricaIoLoader::register(); use CaricaIoNetworkHttp; $route = new CaricaIoNetworkHttpRoute(); $route->startsWith( '/files', new HttpRouteFile(__DIR__) ); $server = new CaricaIoNetworkHttpServer($route); $server->listen(8080); CaricaIoEventLoopFactory::run();
  • 27. Carica Firmata Board <?php $board = new FirmataBoard( new IoStreamSerial( CARICA_FIRMATA_SERIAL_DEVICE, CARICA_FIRMATA_SERIAL_BAUD ) ); $board ->activate() ->done( function () use ($board) { ... } ); CaricaIoEventLoopFactory::run();
  • 28. Carica Firmata Pins function () use ($board) { $buttonPin = 2; $ledPin = 13; $board->pins[$buttonPin]->mode = FirmataPIN_STATE_INPUT; $board->pins[$ledPin]->mode = FirmataPIN_STATE_OUTPUT; $board->digitalRead( $buttonPin, function($value) use ($board, $ledPin) { $board->pins[$ledPin]->digital = $value == FirmataDIGITAL_HIGH; } ); }
  • 29. Example: Blink function () use ($board, $loop) { $led = 9; $board->pinMode($led, FirmataPIN_STATE_OUTPUT); $loop->setInterval( function () use ($board, $led) { static $ledOn = TRUE; echo 'LED: '.($ledOn ? 'on' : 'off')."n"; $board->digitalWrite( $led, $ledOn ? FirmataDIGITAL_HIGH : FirmataDIGITAL_LOW ); $ledOn = !$ledOn; }, 1000 ); }
  • 31. Carica Chip ● Hardware Abstraction ● Device Objects
  • 32. LED function () use ($board) { $led = new CaricaChipLed($board, 9); $led->blink(); }
  • 33. RGB LED function () use ($board) { $colors = array('#F00', '#0F0', '#00F'); $led = new CaricaChipLedRgb($board, 10, 11, 9); $led->setColor('#000'); $index = 0; $next = function() use ($led, $colors, &$index, &$next) { if (isset($colors[$index])) { $color = $colors[$index]; $led->fadeTo($color)->done($next); } if (++$index >= count($colors)) { $index = 0; } }; $next(); }
  • 34. Servo function () use ($board, $loop) { $positions = array( 0, 45, 90, 180 ); $servo = new CaricaChipServo($board, 7, -180); $index = 0; $loop->setInterval( $next = function () use ($servo, $positions, &$index) { if (isset($positions[$index])) { $position = $positions[$index]; $servo->moveTo($position); echo $position, " Grad , ", $servo->getPosition(), " Gradn"; } if (++$index >= count($positions)) { $index = 0; } }, 2000 ); $next(); }
  • 35. Analog Sensor function () use ($board) { $sensor = new CaricaChipSensorAnalog($board, 14); $sensor->onChange( function ($sensor) { echo $sensor, "n"; } ); }
  • 36. Thank You ● Questions? ● Twitter: @ThomasWeinert ● Blog: http://a-basketful-of-papayas.net