2017-10-03

FluentDOM 7.0, The Next Step

FluentDOM 7.0 is out, so what has changed? Well, the FluentDOM namespace got a little crowded so I moved all the DOM child classes into FluentDOM\DOM, made the Creator a top level class and collected the utility classes. If you're updating you might need to change some imports. FluentDOM now requires PHP 7 and uses scalar type hints. In other words, lots of cleanup.

FluentDOM\XMLReader\SiblingIterator

Large XML files usually consist of a list element with many record elements as its children. The whole list is to large to load into memory, but the records are small enough.

The SiblingIterator takes a XMLReader, a tag name and a filter callback. It matches the tag name and executes the filter callback. If the tag name matches and the filter callback returns TRUE it will expand the node into DOM. After the first match it will only consider following siblings. This allows you to improve the read performance.

Here is an example that read a XML sitemap including video information.

$reader = new FluentDOM\XMLReader();
$reader->open($sitemapFile);
$reader->registerNamespace(
  's', 'http://www.sitemaps.org/schemas/sitemap/0.9'
);
$reader->registerNamespace(
  'v', 'http://www.google.com/schemas/sitemap-video/1.1'
);

foreach (new FluentDOM\XMLReader\SiblingIterator($reader, 's:url') as $url) {
  /** @var FluentDOM\DOM\Element $url */
  var_dump(
    [
      $url('string(v:video/v:title)'),
      $url('string(s:loc)')
    ]
  );
}

FluentDOM\XMLWriter::collapse()

FluentDOM 7.0 adds a collapse() method to XMLWriter. It is the missing opposite of XMLReader::expand(). Using the two methods allows you to work with large XML files in a really easy way.

The collapse() method takes any DOM node or node list and will write it to the output stream. You can use the extended DOM classes, FluentDOM\Creator or FluentDOM\Query to create the record node.

$writer = new FluentDOM\XMLWriter();
$writer->openURI('php://stdout');
$writer->registerNamespace(
  '', 'http://www.sitemaps.org/schemas/sitemap/0.9'
);
$writer->registerNamespace(
  'video', 'http://www.google.com/schemas/sitemap-video/1.1'
);

$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('urlset');
$writer->writeAttribute(
  'xmlns:video', 'http://www.google.com/schemas/sitemap-video/1.1'
);

$_ = FluentDOM::create();
$_->registerNamespace(
  '', 'http://www.sitemaps.org/schemas/sitemap/0.9'
);
$_->registerNamespace(
  'video', 'http://www.google.com/schemas/sitemap-video/1.1'
);

foreach ($videos as $video) {
  $writer->collapse(
    $_(
      'url',
      $_('loc', $video['url']),
      $_(
        'video:video',
        $_('video:title', $video['title'])
      )
    )
  );
}
$writer->endElement();
$writer->endDocument();

XMLWriter::setAttribute() recognizes if you write an namespace definition so it will not add it to descendant nodes.

Put Together

If you combine the expand iterator with collapse you can easily write mappers that can consume large XML files. You can basically use each record as a separate DOM document.

For example you can use it to merge XML documents and change the namespaces:

$writer = new \FluentDOM\XMLWriter();
$writer->openURI('php://stdout');
$writer->registerNamespace('p', 'urn:persons');
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('p:persons');

// iterate the example sources
foreach ($data as $sourceFile) {
  // load the source into a reader
  $reader = new \FluentDOM\XMLReader();
  $reader->open($sourceFile);

  // iterate the person elements
  $persons = new FluentDOM\XMLReader\SiblingIterator($reader, 'person');
  foreach ($persons as $person) {
    // use the transformer to move the nodes into the namespace
    $writer->collapse(
      new \FluentDOM\Transformer\Namespaces\Replace(
        $person,
        // namespaces to replace
        ['' => 'urn:persons', 'urn:example' => 'urn:persons'],
        // prefix for target namespace
        ['urn:persons' => 'p']
      )
    );
  }
}

$writer->endElement();
$writer->endDocument();

2017-07-02

FluentDOM 6.1 released - Improvements

Release: FluentDOM 6.1.0

MultiByte HTML

Thanks to some issues reported by Kyle Tse the multibyte handling for HTML was improved. It should now work properly. The HTML loader can read the encoding/charset from meta tags or you can specify as an loader option. The default is UTF-8. FluentDOM\Document::saveHTML() has got some additional logic as well.

XMLReader/XMLWriter

If you need to handle huge XML files, the XMLReader and XMLWriter APIs are the way to do it. Well you could try using SAX, but believe me THAT is no fun. XMLReader and XMLWriter are nice APIs by itself, so FluentDOM adds only slight changes for namespace handling.

XMLReader::read()/XMLReader::next()

Of the two traversing methods, only next() allows to specify a local name as a condition. FluentDOM extends the signature of both methods to allow for a tag name and a namespace URI. As a result the source reading an XML with namespaces can be simplified:

$sitemapUri = 'http://www.sitemaps.org/schemas/sitemap/0.9';
$reader = new FluentDOM\XMLReader();
$reader->open($file);
if ($reader->read('url', $sitemapUri)) {
  do {
    //...
  } while ($reader->next('url', $sitemapUri));
}

XMLReader::registerNamespace()

Additionally you can register namespaces on the XMLReader object itself. This allows it resolve namespace prefixes in tag name arguments.

Namespace definitions will be propagated to an FluentDOM\Document instance created by FluentDOM\XMLReader::expand().

$reader = new FluentDOM\XMLReader();
$reader->open($file);
$reader->registerNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9');
if ($reader->read('s:url')) {
  do {
    $url = $reader->expand();
    var_dump(
      $url('string(s:loc)')
    );
  } while ($reader->next('s:url'));
}

XMLWriter::registerNamespace()

The same registration is possible on an FluentDOM\XMLWriter. It keeps track track of the namespaces defined in the current context and avoid adding unnecessary definitions to the output (PHP Bug).

XMLWriter has many methods that have a tag name argument and this change allows all of them to become namespace aware.

$writer = new FluentDOM\XMLWriter();
$writer->openURI('php://stdout');
$writer->registerNamespace('', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('urlset');

foreach ($urls as $url) {
  $writer->startElement('url');
  $writer->writeElement('loc', $url['href']);
  // ...
  $writer->endElement();
}

$writer->endElement();
$writer->endDocument();

2016-12-24

FluentDOM 6.0 - What's New

FluentDOM 6.0 is released.

So a major version jump means that here are backwards compatibility breaks and major new features. File loading has changed to improve security. FluentDOM\Query has got a major overhaul to improve the integration of alternative formats. This affected the interfaces and usage. I tried to keep the breaks to a minimum and easily fixable.

Loading Files

To load a file you will now have to explicitly allow it using the options argument. Here are two options. FluentDOM\Loader\Options::ALLOW_FILE basically restores the previous behaviour. The loader still checks if it is a file or string and will load both. FluentDOM\Loader\Options::IS_FILE means that only a file will be loaded. This has to be implemented into to respective loader. So if you notice that some loader behaves differently, please drop me a note.

All loading functions allow you to provide the option.

$fd = FluentDOM($file, 'xml', [ FluentDOM\Loader\Options::ALLOW_FILE => TRUE ]);
$document = FluentDOM::load(
  $file, 'xml', [ FluentDOM\Loader\Options::IS_FILE => TRUE ]
);

Fragment Loading / Query Content Types

Several loaders now support fragment loading. It is used by methods like FluentDOM\\Query::append(). It allows the Query API to keep the content type that you loaded. So if you load HTML, the fragment are expected to be html, if you load XML the fragments are expected to be XML, if you load JSON ... well you get the picture. :-)

$fd = FluentDOM('<form></form>', 'text/html')->find('//form');
$fd->append('<input type="text" name="example">');
echo $fd;

You can change the behaviour by setting the content type. It works with additional loaders, so if you install fluentdom/html5 you get transparent support for HTML5.

$fd = FluentDOM('<form></form>', 'text/html5')->find('//html:form');
$fd->append('<input type="text" name="example">');
echo $fd; 

The changes mean that all existing loaders need to be updated for FluentDOM 6.0.

Serializers

Serializers need to register itself on the FluentDOM class. It allows the FluentDOM\Query objects to output the same content type it loaded. Additionally you can use FluentDOM::getSerializerFactories()->createSerializer(); to get a serializer for a node by content type. I am thinking about adding something like a FluentDOM::save() function as a shortcut for that, but I am not sure about the name and implementation yet. If you have a suggestion please add it to the Issue.

Replace Whole Text

Character nodes (Text nodes and CDATA sections) have a property $wholeText. It returns the text content and the sibling character nodes. It even resolves entity references for that. The property is read only, but DOM Level 3 specifies a method replaceWholeText() as a write method for it. FluentDOM 6.0 implements that method in its extended DOM classes now.

$document = new FluentDOM\Document();
$document->loadXML(
  '<!DOCTYPE p ['."\n".
  '  <!ENTITY t "world">'."\n".
  ']>'."\n".
  '<p>Hello &t;<br/>, Hello &t;</p>'
);
/** @var \FluentDOM\Text $text */
$text = $document->documentElement->firstChild;
$text->replaceWholeText('Hi universe');
echo $document->saveXML();

Examples

The examples directory did grow a little confusing over the years. I restructured and refactored it. Some examples got removed, because the features are shown by newer examples.

What's Next?

I still have to updated some of the plugin repositories (loaders, serializers) and add some more documentation to the wiki. After that I plan to take a look into DOM Level 4. If you have suggestions please add a ticket to the issue tracker

2015-05-30

Surface Pro 3 - Versatility

The SP3 is the most useful laptop I ever had and the reason is not performance it is versatility.

One: Notes

The Surface replaces a legal pad in this case. The battery is strong enough to last even a long meeting (>8h). The stylus is precise.  Sensitivity was an issue at first, but the configuration app fixed it.

Two: Media Tablet

Movies, web browsing, reading - I do that mostly in tablet mode using the kickstand to prop it up. If you want better sound, connect a Bluetooth speaker/headphones.

Three: Presentations

PDF works as well as any Windows presentation program. MDP adapters allow to connect to VGA or HDMI. If you forgot your own, just ask another speaker with a Macbook.

You want to control the presentation wireless? The Kensington Presentair is a nice Bluetooth presenter with a Micro USB loading port.

Also, the stylus allows flip chart like presentations.

Four: Mobile Work

It is light enough to carry around and the display has a high resolution - large enough to use an IDE comfortably. The battery last long enough that I do not carry the power supply. It stays at home or in the hotel room. If I expect to need more time, I take a battery pack with me.

The Logitech T630 mouse does not take much space in the bag, has an Micro USB loading port ans support gestures.

A small UMTS stick provides connectivity at the moment, but I hope for LTE in the Surface Pro 4.

Five: Portable Workstation

Working in a customers office for some days allows for a larger setup. The USB port on the SP3 is not powerful enough for an external monitor, but the one in the power supply is. I use a MS168B+ connected to a small USB hub with a Micro USB port for power. The hub provides LAN and an SD-Card reader, too. Typically I set it up with the SP3 power supply, but it works with the battery pack. The wireless adapter converts the type cover into an Bluetooth keyboard.

Maybe Microsoft will fix the USB port power issue in the next Surface Pro.

Six: Desktop Workstation

I have two of the docking stations - at work and at home. At home it is connected to an LG ultra widescreen monitor (3440x1440px). At work it is connected to two monitors with the EVGA DisplayPort MST Hub. I could connect the monitors directly to the two MDP ports (docking station and SP3). But the whole point of a docking station is to not have to connect separate cables.

2015-02-02

FluentDOM 5.2 - New Features

FluentDOM 5.2 is released and here some new features:

FluentDOM::load()

The new static FluentDOM::load() function allows to use the loaders to get a FluentDOM\Document instance.
$json = FluentDOM::load($json, 'text/json');
echo $json(
  'string(//phoneNumbers/*[type="home"]/number)'
);

DOM Living Standard


A large part of the DOM Living Standard is implemented. It adds properties like $element->firstElementChild and methods like $element->remove().

Query selectors are not implemented yet. Still thinking about that. If you have an opinion please add a comment to the issue.

Two New Loaders

Loader Plugins

It was already possible to use the loaders directly or to set the loaders for a FluentDOM\Query object. It is now possible to register them on the FluentDOM class. This makes them available to the FluentDOM() and FluentDOM::load() functions.

Additional packages like FluentDOM/HTML5 can register their loaders with specific content types. Just require the package with Composer and you're ready to go:
$dom = FluentDOM::load($html, 'text/html5');

FluentDOM\Query::find()

The behavior of find() has been changed to allow two modes. FIND_MODE_MATCH executes the selector directly. It should be faster and work better with XPath. FIND_MODE_FILTER filters the descendant nodes of the current context - like the jQuery documentation describes it.

2014-11-22

Surface Pro - USB Hub

The Surface Pro is a cool device but USB connectivity is one of its weak point. It has a single USB 3 port that is not fully powered. Devices that need the more power like an USB monitor will not work.

Up until now I used a hub with 3 USB ports and LAN (RJ45). An Y cable connected the USB port on the power supply to provide additional power to the hub.

I found something better. 
  • Really small form factor
  • 2 USB 3 ports, 
  • 1 RJ45 LAN port
  • Card reader (SD and Micro SD)
  • Micro USB power connector
So I loose 1 USB port, but get the SD card reader. The form factor is really nice. The killer feature is the Micro USB port. Finally a powered USB hub that does not need a special power supply.

Take a look:



I tested it connected to the Surface Pro power supply and the Asus MB168B+ USB monitor. Works fine.  

2014-09-20

FluentDOM 5.1 - New Features

FluentDOM 5.1 is now available. Here are some of the highlights:

Functors 

The classes can now be called as functions to navigate in a DOM with XPath expressions. The following example fetches all link hrefs attributes from an HTML page:
$dom = new \FluentDOM\Document();
$dom->loadHTMLFile('http://fluentdom.org/');

$links = [];
foreach ($dom('//a[@href]/@href') as $href) {
  $links[] = (string)$href;
}


This works for most of the nodes in a DOM. 

Creator

The new Creator class provides short syntax to create DOM nodes. More detailed information can be found in the wiki.
$_ = FluentDOM::create();
echo $_(
  'ul',
  ['class' => 'navigation'],
  $_('li', 'FluentDOM')
);

XML To JSON

Several serializers/loaders for JSON where added. JSONML, Rayfish, BadgerFish and RabbitFish are supported.
echo "XML -> JsonML\n\n";
$json = json_encode(
  new FluentDOM\Serializer\Json\JsonML($dom), 
  JSON_PRETTY_PRINT);
echo $json;

echo "\n\nJsonML -> XML\n\n";
echo FluentDOM(
  $json, 'application/jsonml+json')->formatOutput();

The Release

2014-08-17

FluentDOM + HTML5

HTML 5 is not directly supported by PHPs DOM extension. That means FluentDOM can not understand it, too. But here is a solution. HTML5-PHP is library that can parse HTML5 into a DOM document.

Both libraries use Composer:
"require": {
  "fluentdom/fluentdom": "5.*",
  "masterminds/html5": "2.*"
}

Read HTML5 into FluentDOM:
$html5 = new Masterminds\HTML5();
$fd = FluentDOM($html5->loadHTML($html));

Or write it:
echo $html5->saveHTML($fd->document);

HTML5-PHP puts the elements into the XHTML namespace. To use XPath expressions, you will need to register a prefix for it:
$html5 = new Masterminds\HTML5();
$fd = FluentDOM($html5->loadHTML($html));
$fd->registerNamespace(
  'xhtml', 'http://www.w3.org/1999/xhtml'
);
echo $fd->find('//xhtml:p')->text();

2014-08-09

Xpath 1.0 - Quoting Strings

Strings in Xpath 1.0 can be enclosed in single or double quotes. The following expressions are equivalent.

//div[@id = 'foo']
//div[@id = "foo"]


This is nice because you can use the variant that requires less or none escaping. I prefer single quotes for PHP because they need less escaping (only single quote and backslash). I usually end up with something like this:

$xpath->evaluate('//div[@id = "foo"]');

However a problem comes up if the value is dynamic.

$xpath->evaluate('//div[@id = "'.$_GET['foo'].'"]');

If $_GET['foo'] contains a double quote, it will break the expression. It is compare able to an SQL-Injection and should be avoided, don't you think?

The Xpath 1.0 specification for a literal is:

Literal   ::=   '"' [^"]* '"'


| "'" [^']* "'"

It disallows the use of the enclosing quote in the literal itself, here is no way to escape it.

Hint: This is different in Xpath 2.0. You can duplicate the quotes to escape them.

Deciding Which Quote To Use

 The first and obvious step is to check the value for quotes and use the one that it does not contain:

function quote($value) {
  $char = strpos($value, '"') === FALSE ? '"' : "'";
  return $char.$value.$char;
}


But a value could contain both kind of quotes. This would still break the expression.

Divide And Conquer

If is not possible to quote the whole value because it contains both kind of quotes you need to divide it into parts that can be quoted. You can then use the Xpath function concat() to rebuild the orignal value again:

//div[. = concat("Singe Quote: '", 'Double Quote: "')]

Matching text structures is the domain of regular expression. So lets use them:

preg_match_all('("[^\']*|[^"]+)', 'Double Quote ", Single Quote \'', $matches);
var_dump($matches);


Output:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(13) "Double Quote "
    [1]=>
    string(16) "", Single Quote "
    [2]=>
    string(1) "'"
  }
}

The pattern matches any string that start with a double quote and contains no single quote or any string that does not contain any double quote.

All that is left is quoting the parts and join them back together:

foreach ($matches[0] as $part) {
  $quoteChar = (substr($part, 0, 1) == '"') ? "'" : '"';
  $result .= ", ".$quoteChar.$part.$quoteChar;
}
return 'concat('.substr($result, 2).')';

Put Together

It does not make sense to create the function call for a single argument. So the check is still needed:

  1. If the value contains no single quote, use single quotes
  2. If the value contains no double quote, use the double quotes
  3. Otherwise divide the string and use concat()

A complete implementation can be found in FluentDOM\Xpath::quote().

2014-08-06

FluentDOM 5 + XML Namespaces

FluentDOM 5 allows to register namespaces on the DOM document class. These are not the namespaces of a loaded document, but a definition of namespaces for your programming logic.

Namespaces In An XML File

People mistake the namespace prefixes for the namespaces often. The namespace definitions are the xmlns:* Attributes. Let's take a really simple example:

<atom:feed xmlns:atom="http://www.w3.org/2005/Atom"/>

This is a feed element in the Atom namespace. The actual namespace is "http://www.w3.org/2005/Atom". Because this would be difficult to read and write the prefix/alias 'atom' is defined for the namespace. 

You can read the element name as '{http://www.w3.org/2005/Atom}:feed'

It is possible to define a default namespace for elements in an XML. 

<feed xmlns="http://www.w3.org/2005/Atom"/> 

This should still be interpreted as '{http://www.w3.org/2005/Atom}:feed'. The namespace prefix in the source document is not relevant. You need a way to match the namespace itself and not the alias.

Hint 1: Namespace prefixes can be redefined on any element node in the document.

Hint 2: Attributes always need a prefix to use a namespace. Any attribute without a prefix is in the "none/empty" namespace.

Namespaces in XPath

An XPath expresssion that could match the Atom feed element would need to use a prefix and needs a way to resolve that prefix into the actual namespace. 

A PHP Example:

$xpath = new DOMXpath($document);
$xpath->registerNamespace('a', 'http://www.w3.org/2005/Atom');
$nodes = $xpath->evaluate('/a:feed');


In PHP the DOMXpath class provides the evaluate() method and the namespace resolver. You register your own namespace prefixes. '/a:feed' gets resolved to '/{http://www.w3.org/2005/Atom}:feed'. The prefixes in the document and the expression can be different, but the resolved namespace has to be the same.

A JavaScript example:

var xmlns = {
  namespaces : {
    'a' : 'http://www.w3.org/2005/Atom'
  },
  lookupNamespaceURI : function(prefix) {
    return this.namespaces[prefix] || null;
  }
};
var nodes = xmlDocument.evaluate('/a:feed', xmlDocument, xmlns, XPathResult.ANY_TYPE, null); 


In JavaScript the document object provides the evaluate() method and the namespace resolver is an argument for it. This will work in most of the current browsers, but not IE. 

Namespaces in FluentDOM

In FluentDOM 5 the document and the element classes both have an evaluate() method. To define your namespace mapping you register the namespace on the document object:

$document->registerNamespace('a', 'http://www.w3.org/2005/Atom')
$nodes = $document->evaluate('/a:feed');


Now because the document has a way to resolve namespaces, it can do this for other methods, too. Basically for all methods a have a namespace aware variant, like 'createElement()' and 'createElementNS()' or 'setAttribute()' and 'setAttributeNS()'. If FluentDOM can resolve a tagname it will call the namespace aware variant of the method.

// Standard DOM
$feed = $document->createElementNS(
  'http://www.w3.org/2005/Atom', 'atom:feed'
);
// FluentDOM
$document->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
$feed = $document->createElement('atom:feed');

Default Namespace 

FluentDOM adds the concept of a default element namespace, too.

// Standard DOM
$feed = $document->createElementNS(
  'http://www.w3.org/2005/Atom', 'feed'
);
// FluentDOM
$document->registerNamespace('#default', 'http://www.w3.org/2005/Atom');
$feed = $document->createElement('feed');

appendElement()


FluentDOM\Document and FluentDOM\Element implement an appendElement() method. It is a shortcut for serveral methods. It creates the element, adds attributes and a text node and appends it to the parent node. Together with the namespace handling, creating an XML document becomes a lot simpler. You can find an example in the wiki.


2014-08-01

FluentDOM 5

FluentDOM 5.0.0 is now released.

Up to version 4.1, FluentDOM was an implementation of the jQuery Traversing and Manipulation APIs in PHP. Version 5 is a complete rewrite and adds a secondary focus. FluentDOM now provides extended variants of PHPs DOM classes, too. This allows workarounds for bugs, syntax sugar and shortcuts.

Bugs

#39521

The second argument to DOMDocument::createElement() it breaks if it contains an entity. FluentDOM avoids that by creating and appending a text node. Additionally it adds a third argument to provide attributes.

#55700

By default PHP registers the namespace definitions of the current context. This uses the namespace prefixes as identifiers, but they are not. They are allowed to change (even on different elements in the same document). You should always register your own prefixes so you do not depend on the prefixes in the document - they are just not relevant. So the automatic registration costs performance without a real gain in the best case. In the worst case it overrides a your namespace registration and you can not fetch the data you want.

FluentDOM adds a property to change this behavior. The automatic namespace registration is disabled by default and can be activated using the property or the third argument for evaluate()/query().

Syntax Sugar

Cast To String


Most of the nodes can be cast to string. for example the following will return the whole text content of an document.

echo $dom->documentElement;

Iterator For Child Nodes


FluentDOM\Element is iterate-able. Using foreach() on it will iterate over the child nodes. The Iterator is a RecursiveIterator, too.

ArrayAccess

FluentDOM\Element allows array syntax. A numeric key like $element[1] will access the child node. An qualified name string like $element['href'] will access the attribute.

Namespaces

FluentDOM\Document allows to register namespaces on the document. If methods like setAttribute() or createElement() recognize a colon in the tag name, they will resolve the namespace prefix an call their namespace aware variant.

Shortcuts

FluentDOM\Document::createElement() allows to provided content and attributes. FluentDOM\Element::appendElement() allows to create and append an element with a single call.

Other methods of the FluentDOM\Element class are variants of the document variants using the element node as default context. 

Backwards Compatbility

FluentDOM 5 is mostly backwards compatible. The FluentDOM() function still exists and the returned FluentDOM\Query instance has the same jQuery like API. Only the loaders where changed.

CSS Selectors

The FluentDOM\Query class allows to set an callback function that is used to convert the provided selectors to xpath expressions. FluentDOM::QueryCss() returns a FluentDOM\Query instance that supports CSS selectors. You will need to have Carica PhpCss or Symfony CSS-Selector installed in you project.



2013-11-17

Building A Sensor Phalanx With PHP

Sensors are fun. They report from the physical world into the digital. But getting the signal into php is only the first part, you will have to get them out again. This post shows how to get data from analog sensors pushed to the browser. It uses Carica Chip, if you haven't read my previous blog post you should do it first.

Carica Io implements its own event loop, but if it finds ReactPHP installed, it will base it on this implementation, making it compatible and allowing to use the libraries. One of the libraries for ReactPHP is Ratchet, a websocket server implementation.

In this example two servers are used. An http server for file delivery (html and javascript for the UI) and a websocket server that pushes the sensor values to the browser. Smootie Charts displays the data in the browser as a running line chart, not unlike an oscilloscope.

Source

The latest source for this example can be found on Bitbucket:
https://bitbucket.org/ThomasWeinert/carica-sensor-phalanx

Project Setup

Clone Carica Chip Skeleton to create a new project and add Ratchet to the dependencies.

composer create-project carica/chip-skeleton SensorPhalanx \
  --stability=dev 

cd SensorPhalanx

composer require cboden/ratchet

copy dist.configuration.php configuration.php

Edit configure.php to match your hardware setup.

The HTTP Server

In the LED example, the http server had only one route to deliver the html file. Now we need to deliver the javascript, too. An additional route allows to deliver static files from a subdirectory.

$route = new Http\Route();
$route->match('/', new Http\Route\File('index.html'));
$route->startsWith('/files', new Http\Route\Directory(__DIR__));
$httpServer = new Http\Server($route);
$httpServer->listen(8080);

The Sensor Phalanx

The Sensor Phalanx object encapsulates the Ratchet websocket server and provides the callbacks for it. It needs an array of sensors. Port 8080 is already used for the http server, so it should listen on port 8081. An interval triggers the update of the clients.

// create the phalanx with some sensors
include(__DIR__.'/class/SensorPhalanx.php');
$phalanx = new Carica\SensorPhalanx(
  [
    'lightsensor' => new Chip\Sensor\Analog($board->pins[15]),
    'potentiometer' => new Chip\Sensor\Analog($board->pins[16])
  ]
);
// tell the websocket server to listen
$phalanx->listen(8081);

// update clients connected to the phalanx with the current sensor data
$loop->setInterval(
  function () use ($phalanx) {
    $phalanx->update();
  },
  200
);

The SensorPhalanx Class

The SensorPhalanx class needs to implement two interfaces. Carica\Io\Event\HasLoop defines access to the Carica Io event loop. It can be implemented using the trait Carica\Io\Event\Loop\Aggregation.

Ratchet\MessageComponentInterface defines the callback methods for the websocket server.
  • onOpen() - add a client
  • onClose() - remove a client
  • onMessage() - handle data recieved from the browser
  • onError() - log/handle errors
public function onOpen(Ratchet\ConnectionInterface $connection) {
  $this->_clients[spl_object_hash($connection)] = $connection;
}

public function onClose(Ratchet\ConnectionInterface $connection) {
  unset($this->_clients[spl_object_hash($connection)]);
}

public function onMessage(Ratchet\ConnectionInterface $connection, $message) {
}

public function onerror(Ratchet\ConnectionInterface $connection, \Exception $e) {
  echo "Error: ", $e->getMessage(), "\n";
  $connection->close();
}

Create And Listen

The constructor of the class just validates the sensor objects, and stores them. Listen creates the needed subobjects. Unlike the examples on the Ratchet website, the factory methods can not be used. They would create a new event loop. The script already has one, used for the Arduino board and the http server. The $this->loop() method returns the Carica Io event loop and in a second step allows access to the actual ReactPHP event loop.

public function __construct(array $sensors) {
  foreach ($sensors as $index => $sensor) {
    if ($sensor instanceOf Chip\Sensor\Analog) {
      $this->_sensors[$index] = $sensor;
    }
  }
}

public function listen($port = 8081) {
  $socket = new \React\Socket\Server($this->loop()->loop());
  $socket->listen($port);
  $this->_server = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
      new Ratchet\WebSocket\WsServer(
        $this
      )
    ),
    $socket,
    $this->loop()->loop()
  );
}

Update

Update collects the data from all sensors into an array, encodes it to json and sends it to all connected clients.

public function update($log = TRUE) {
  $values = ['type' => 'sensors'];
  foreach ($this->_sensors as $index => $sensor) {
    $values['sensors'][$index] = $sensor->get();
  }
  $json = json_encode($values);
  if ($log) {
    echo $json, "\n";
  }
  foreach ($this->_clients as $client) {
    $client->send($json);
  }
}

User Interface

The html file uses Smoothie Charts. It defines some CSS and a canvas for the chart. The chart is created and connected to the canvas. A list of colors provides a different color for each line.

The websocket server connects and gets a callback. If a message is received it loops over the sensor values. If a line for the index already exists the value is appended. For an unknown index a new line is created and the assigned color is removed from the internal list.

var smoothie = new SmoothieChart(
  {
    maxValue : 1,
    minValue: 0
  }
);
smoothie.streamTo(document.getElementById('monitorCanvas'), 250);

var colors = ['#00FF00', '#FF0000', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];
var lines = [];

websocket = new WebSocket('ws://localhost:8081/');
websocket.onmessage = function(event) {
  var data = JSON.parse(event.data);
  if (data && data.type == 'sensors') {
    for (index in data.sensors) {
      if (typeof lines[index] == 'undefined') {
        var color = colors.shift();
        if (!color) {
          color = '#FFFFFF';
        }
        lines[index] = new TimeSeries();
        smoothie.addTimeSeries(
          lines[index],
          {
            lineWidth: 2,
            strokeStyle: color
          }
        );
      }
      lines[index].append(new Date().getTime(), data.sensors[index]);
    }
  }
};

In Action

2013-11-04

Carica Chip 101 - Controlling An LED With PHP

Some time ago, in this blog post, I explained the basic stuff about Arduino, Firmata and PHP. Now it is time for the next step. Carica Io and Carica Firmata have grown and got a third layer called Carica Chip.
  1. Carica Io - Non-Blocking I/O for PHP
  2. Carica Firmata - An implementation of the Firmata protocol
  3. Carica Chip - PHP classes representing hardware devices
Carica Chip provides an easy way to control a device. So let's start with an "Interactive LED" example.

First Step: Project Initialization

Carica Chip uses Composer. Make sure that it is installed and open a console. Go into your projects directory and execute the following line (it will create a new subdirectory "led"):

composer create-project carica/chip-skeleton led \
  --stability=dev

Second Step: Create An HTML Interface

For the interface a simple html file is used. Just two links with an iframe set as the target. This is a basic version, some Javascript and CSS should be used to make it nicer and more usable.

<html>
  <head>
    <title>Led Switch</title>
  </head>
  <body>
    <a href="./switch/on" target="iframe">
      On
    </a>
    <a href="./switch/off" target="iframe">
      Off
    </a>
    <iframe name="iframe" src="about:blank"></iframe>
  </body>
</html>

Store the html source as "index.html" in the project root.

Third Step: Create The PHP Server

This will be a step by step description, the complete file is below and on Gist.

The skeleton includes a bootstrap file that returns a board depending on your configuration. Copy "dist.configuration.php" to "configuration.php" and change it if needed.

Now open "server.php". At the top "bootstrap.php" is included to fetch a Firmata board. If the board is activated, it executes a callback. Carica Chip provides a "Led" class. For the example an instance is created. The constructor needs the pin the led is connected to. Most Arduinos have a led that is connected to pin #13 on board.
$led = new Chip\Led($board->pins[13]);

We need to deliver the html interface to the browser. Carica Io includes a http server and file routings. Add "use Carica\Io\Network\Http as Http;" to the namespace definition, create a new route and add a file delivery for "index.html".
$route = new Http\Route();
// Define html file delivery for /
$route->match(
  '/', 
  new Http\Route\File(__DIR__.'/index.html')
);

A second route defines the switch actions. This is specific and not much source, so an anonymous function is used. For more extensive logic I suggest functors, objects that implement the magic method "__invoke()", like the file handler. The state parameter is fetched from the path. Depending on the parameter the led is switched on or off. A response is created and a string with the new state is used as content. If you don't return a response, a 404 would be send to the browser.
$route->match(
  '/switch/{state}',
  function (Http\Request $request, array $parameters)
    use ($led) {
    $ledOn = ($parameters['state'] == 'on');
    if ($ledOn) {
      $led->on();
    } else {
      $led->off();
    }
    $response = $request->createResponse(
      new Http\Response\Content\String(
        $ledOn ? 'ON' : 'OFF', 
        'text/plain; charset=utf-8'
      )
    );
    return $response;
  }
);

Last the http server is created and started.
$server = new Carica\Io\Network\Http\Server($route);
$server->listen(8080);

Finished!

That's all. You can now start the script on the command line and open the URL in a browser. Clicking the links will (de)activate the led.

I posted the full source of "server.php" including comments on Gist.

2013-06-20

Basics: Using Arduino From PHP

Own Protocol Inside A PHP Page.

This is the version mostly described on the net. For example on Instructables. Basically you write an Arduino Scetch that listens and send plain text data on the serial port. A PHP Script triggered by a webserver request opens the port communicates with the Arduino board an outputs some HTML.

The major downside of this approach is that many Arduino boards reset if the serial port is opened. So the startup and configuration has to be done any time the PHP scripts reads some data or triggers an action. Because the PHP script stops after the page request any data has to be stored in a database, cache or file.

Firmata

Firmata is a generic sketch for Arduino boards that implements an MIDI based protocol. Here are client libraries for several languages. For example Johnny Five for Javascript (Node.js) implements abstraction not only for the communication but for hardware elements. For example you get an led object with blink() and fade() methods.

Firmata Inside A PHP Page. 

Well, It is possible but you don't want to do that. Firmata has a little more complex startup process that takes about two seconds. To much to use it in a web request.

Firmata Over TCP

The official version of Firmata uses the serial port. But here are forks that can use TCP. You need an compatible network shield for your Arduino board and the version may be a little behind the offical one.

Non-Blocking I/O

Node.js uses an concept called Non-blocking I/O or Asynchronous I/O. Basically it means that you add actions to an event loop, trigger events from you objects that execute attached callbacks. Doesn't sound familiar? If you ever programmed some Javascript for your web pages, you used this concept. Each browser window has an event loop. Functions like "window.setTimeout()" add event to the loop. The browser fires event on the page elements that execute callbacks, if you attached them, too.

So using this concept you describe what should happen if an events is triggered and a certain conditions are meet. In classic PHP you work with the current state. In Non-Blocking I/O the result has yet to be calculate at a future time.

Procedual Programming:
If the result of action x is value y now do that.
Non-Blocking I/O
If the result of action x will be y you will have to do that.

Thinking like this is much better suited to hardware control, at the moment you are programming you do not now if somebody will ever press the button on your Arduino device or which values the sensor your connected will send.

Non-Blocking I/O in PHP

PHP has no default event loop implemented but here are several possibilities for it. First it whould be possible just using an while loop and usleep(). This would not be very efficient. Better is an combination of this with stream_select(). The "stream_select()" function  is like a usleep() that monitors streams and return imminently if a stream is changed. It even says which stream is changed how, so it is possible to trigger the exact events for this stream.

Event more efficient is using libevent. PHP has an extension for this event loop implementation. It is used inside the Chrome browser browser and Node.js, too.

Libraries For PHP

Here are libraries in PHP that implement event loops.

ReactPHP
ReactPHP is the most mature project implementing Non-Blocking I/O for PHP. It a general purpose library and has additional components. You can read more about it on reactphp.org.

Carica Io
Caica Io is an implementation I created as a base for Carica Firmata, a client library for the Firmata protocol. It can used separately if you're going to implement your own protocol, too. Here is an basic example with timers:


The event loop uses the API not unlike the Browser. The main difference to Javascript in the Browser or Node.js is that you have to run the event loop explicitly.

Carica Firmata

The Firmata test application
in Carica Firmata
Based on Carica Io, it allows you to create programs that control the Arduino board. They run without an webserver (like Apache HTTP, Nginx, ...). They can even contain an (simple) webserver to control the script from a browser. The php program is started from the command line and runs continuously until you stop it (or it crashes :-) ). The serial connection to the board is opened only once, no reset happens and the start up time is not an issue.

Blink

The "Hello World" for an Arduino is an blinking led. Wait for the board to activate, and add an interval (repeated timer) that switches it on and off.


Dimmer

Carica Firmata can read data, too. Simple attach an callback to the board. On the analog pin this could be a potentiometer dimming an led. The examples uses an OOP api for the pins. The main difference to calling the methods on the board object directly is that values and the mode are only send if the are changed.

On Windows

On Windows the  serial port is seriously broken at the moment. It can not work non-blocking. Any reading action will block your script until it recieves data. One solution is Serpoxy, a little program that maps the serial port to tcp.

Links

2012-07-31

What Iterators Can Do For You

Basically Iterators provide a list interface for an object. Like all interfaces they are a contract how something can be used. If you use an interface it is not relevant how it is implemented - the implementation logic is encapsulated.

It is of course relevant on the integration level. A bad implementation can impact the performance of you application. Even an good implementation may need special resources (like a database). But all this does not impact how you use it. Your code using the object with the Iterator interface stays the same.

Let's start with a simple example that outputs a list.

$elements = array(
  'line one', 'line two'
);

foreach ($lines as $key => $value) {
  echo $key.': '.$value."\n";
}


If we transfer this into an object it would like that:

class MyProjectLineOutput {
  private $_lines = NULL;

  public function __construct($lines) {
    $this->_lines = $lines;
  }

  public function __invoke() {
    foreach ($this->_lines as $key => $value) {
      echo $key.': '.$value."\n";
    }
  }
}

$output = new MyProjectLineOutput(
  array(
    'line one', 'line two'
  )
);
$output();


On the first glance that looks like a lot more work but it isn't. The code includes two tasks. Get the lines and output them. The class encapsulates the output task and makes it reusable. In this simple example that may look superfluous but think a little larger. Like output an select-field or csv.

Encapsulate file()


Still we haven't used an Iterator, but just encapsulated the output. PHP provides several default iterators and one of them is the ArrayIterator.

$output = new MyProjectLineOutput(
  new ArrayIterator(
    array(
      'line one', 'line two'
    )
  )
);
$output();


The ArrayIterator just takes an array and makes it an Iterator. It is mostly used to implement another interface - IteratorAggregate. Both the "Iterator" and the "IteratorAggregate" interfaces inherit from a common ancestor named "Traversable". You can not implement "Traversable" directly but use it to validate if an object is traversable or in other words can be used with foreach.

Now let's load the lines from a file.

class MyProjectFile implements IteratorAggregate {
  private $_file;

  public function __construct($file) {
    $this->_file = $file;
  }

  public function getIterator() {
    return new ArrayIterator(file($this->_file));
  }
}

$output = new MyProjectLineOutput(
  new MyProjectFile('sample.txt')
);
$output();


The main difference between using file directly to this is that the file() is accessed later in the process. The foreach() inside the MyProjectLineOutput::output() method calls MyProjectFile::getIterator(). Until then we can pass the instance of MyProjectFile around without loading the file into memory. Unlike a direct call to file() we don't pass the concrete data around but an information how it can be obtained.

Iterating A Text File


Implementing Iterator we can make sure that only a part of the file needs to be loaded.

class MyProjectFileUnbuffered implements Iterator {
  private $_file;
  private $_handle = NULL;
  private $_key = -1;
  private $_current = NULL;

  public function __construct($file) {
    $this->_file = $file;
  }

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

  public function rewind() {
    if (!is_resource($this->_handle)) {
      $this->_handle = fopen($this->_file, 'r');
    } else {
      fseek($this->_handle, 0);
    }
    $this->_key = -1;
    $this->next();
  }

  public function next() {
    if ($this->_key > 0 or $this->_current !== FALSE) {
      $this->_current = fgets($this->_handle);
      $this->_key++;
    }
  }

  public function key() {
    return $this->_key;
  }

  public function current() {
    return $this->_current;
  }

  public function valid() {
    return $this->_current !== FALSE;
  }
}


This is more source then implementing it directly. Mostly because of the class and function declarations. But you have to write this only once. And it can be improved or replaced without affecting the usage.

Map Elements

Using iterators you can encapsulate mapping actions, like using array_map() on an array but only for elements that are read. Let's say you need to chop all trailing whitespaces from the lines.

Step One: Map Iterator:


class MyProjectMapIterator implements OuterIterator {

  private $_innerIterator = NULL;
  private $_callback = NULL;

  public function __construct(Iterator $innerIterator, $callback) {
    $this->_innerIterator = $innerIterator;
    $this->_callback = $callback;
  }

  public function map($current, $key) {
    return call_user_func($this->_callback, $current, $key);
  }

  public function getInnerIterator() {
    return $this->_innerIterator;
  }

  public function rewind() {
    $this->getInnerIterator()->rewind();
  }

  public function next() {
    $this->getInnerIterator()->next();
  }

  public function key() {
    return $this->getInnerIterator()->key();
  }

  public function current() {
    return $this->map(
      $this->getInnerIterator()->current(),
      $this->getInnerIterator()->key()
    );
  }

  public function valid() {
    return $this->getInnerIterator()->valid();
  }
}


OuterIterator is an interface for iterators that wraps other iterators, it is defined in the SPL. It extends the Iterator interface. The MapIterator is an iterator of that kind, so it is cleaner to implement it that way.

Step Two: Using The Map Iterator:

Using the map iterator is not unlike using array_map.

$output = new MyProjectLineOutput(
  new MyProjectMapIterator(
    new MyProjectFile('sample.txt'),
    function($current, $key) {
      return chop($current);
    }
  )
);
$output();


The file() function has an option to do this. But it is limited to exactly this task. With MapIterator you get a lot more flexibility. You could even extend the MapIterator to get reusable mappings.

Step Three: Extending the Map Iterator

class MyProjectMapIteratorUpper extends MyProjectMapIterator {

  public function __construct(Iterator $innerIterator) {
    parent::__construct(
      $innerIterator,
      function($current, $key) {
        return strToUpper($current);
      }
    );
  }
}

Filter Elements:

Here is another option for file(), that skips empty lines. This would be filter task and here is already an superclass for that in SPL.

class MyProjectFilterIteratorSkipEmptyLines extends FilterIterator {

  public function accept() {
    return trim($this->getInnerIterator()->current()) !== '';
  }
}

Conclusion

Iterators are not about writing less code at one time. But they help you to write source that is encapsulated, easy to test and reusable. Because of this over time you will end up with less code.

2012-07-30

Using The PHP 5.4 Webserver On Windows

Starting a server from the command line
PHP 5.4 has an built-in webserver. For local development it is not necessary to install Apache Httpd or another webserver anymore. You can just start an server from the command line.

Change the directory to your project directory. The argument -S starts the webserver. You need to specify a host and a port. All requests are shown in the console window.

A Shortcut

To make things a little easier you can create a windows shortcut. This allows you to change the console window size, font and color, too. The following pictures show the particular steps:
Step 1: Create A Shortcut
Step 2: Select the PHP binary
Step 3: Name the shortcut
Step 4: Change command and working directory
Step 5: Change the window size

2012-07-14

Matching Classes In XSLT

A while ago (well 2 years) I posted an entry about the differences between CSS selectors and Xpath expressions. An simple ".classname" in CSS is a noisy "contains(concat(' ', normalize-space(@class), ' '), ' first ')" in Xpath.

In XSLT this adds a lot of overhead. But if your XSLT processor supports EXSLT you are able to encapsulate it into a function.

I put this into a file "contains-token.xsl".


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:func="http://exslt.org/functions"
  extension-element-prefixes="func"
>
<func:function name="func:contains-token">
  <xsl:param name="haystack">
  <xsl:param name="needle">
  <xsl:variable name="normalizedHaystack" select="concat(' ', normalize-space($haystack), ' ')"/>
  <xsl:variable name="normalizedNeedle" select="concat(' ', normalize-space($needle), ' ')"/>
  <func:result select="$needle != '' and contains($haystack, $needle)"/>
</func:function>

</xsl:stylesheet>


You need to declare the func namespace and define it as an extension prefix. The function definition is not unlike an normal template definition. You just have to use the "func:function" and "func:result" elements. Function always need to be inside an namespace. If in doubt, just use the "func" namespace itself.

In this case I normalize both parameters first and just validate if the haystack contains the needle.

Now it is possible to import the function and use it.


...
<xsl:import href="../functions/contains-token.xsl"/>

<xsl:template match="/">
  ...
  <xsl:value-of select=".//div[func:contains-token(@class, 'classname')]"/>
  ...
</xsl:template>
...


It is still longer then the CSS version but it is a lot more readable.


2012-04-19

Twin Stem Adapters

I don't like the standard Brompton handlebar. They are to short and to flexible. They are so short that I had to cut of a considerable amount of the right grip to fit the brake lever and the shifter. Not an ideal situation. The S Type is to low for me. One of the users in the German Bromptonauten forum posted an image of his modification. An M Type stem with a stem adapter raising a standard flat handlebar.

So I replaced the M Type stem on my Brompton with an H Type. It is 6cm higher, but the hinge is higher, too. I tested three stem adapters.



TranzX double clamp adapter SATORI Aberhallo Adjustable Stem GUB G-80 folding bike stem
Images
Distance 50 mm 50 mm 55 mm
Weight 188g 198g 141g
Colors black black red, silver, blue, black, gold
Remove Grip and break lever for assembly No No Yes


H Type stem, GUB G-80 adapter and flat handle bar
The major disadvantage of the TranzX adapter are the clamps above the handle bar. The GUB adapter is similiar but the clamps are at the bottom and smaller. The Aberhallo adapter has a different design - it is the most flexible. TranxZ and Aberhallo use plastic barends, but the GUB has threaded aluminium barends, providing a small storage space.

For now I am using the GUB G-80. The 5mm more make a difference (no conflict with the mudguard stay) and I like the look of the bands at the handle bar.

The handle bar is 1 meter from the ground and 8 cm lower then the saddle.

2012-04-14

Einladung zum Kölner Radverkehrstreff

Fast hätte ich es gar nicht mitbekommen, diesmal lädt die Polizei zum Kölner Radverkehrstreff ein. Die Pressemitteilung ist vom Donnerstag den 12.04.2012 - die Veranstaltung wird am Montag, den 16.04.2012 um 18:00 Uhr im Polizeipräsidium Köln (Walter-Pauli-Ring 2-6, Forum 1+2) stattfinden. Großzügige VIER Tage Zeit gibt man also den "interessierten Bürgerinnen und Bürgern" den Termin einzuplanen.

Die Stadt hat es bis heute (Samstag, 14.04.2012 16:00 Uhr)  nicht geschafft eine entsprechende Meldung auf ihrer Radverkehrsseite zu veröffentlichen und um Veranstaltungskalender ist sie auch nicht zu finden. Beim letzten Mal wurde die Ankündigung als Schlussabsatz in einer anderen Meldung untergebracht.

Das Thema ist passender weise diesmal "Fahrradkommunikation und Öffentlichkeitsarbeit".

2012-03-23

Brompton Modifications

I don't like the plastic silver look of the Brompton fenders. So I got some carbon fibre effect foil and a hairdryer. The result are some nice black fenders.


You can see my new rear suspension on the image, too. Here is a real steel spring inside. So it is nothing for weight weenies. :-)



x