<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Psychic Origami &#187; Development</title>
	<atom:link href="http://www.psychicorigami.com/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.psychicorigami.com</link>
	<description>folding with my brain</description>
	<lastBuildDate>Wed, 03 Aug 2011 19:13:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>A Little Sparql</title>
		<link>http://www.psychicorigami.com/2011/06/05/a-little-sparql/</link>
		<comments>http://www.psychicorigami.com/2011/06/05/a-little-sparql/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 14:31:41 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=432</guid>
		<description><![CDATA[Quite often I&#8217;ll get distracted with an idea/piece of technology and mull it over for quite some time. Most of the time I play through these ideas in my head and don&#8217;t do anything with them. It&#8217;s often just an exercise in learning and understanding. I&#8217;ll read up on something and then try to think [...]]]></description>
			<content:encoded><![CDATA[<p>Quite often I&#8217;ll get distracted with an idea/piece of technology and mull it over for quite some time.  Most of the time I play through these ideas in my head and don&#8217;t do anything with them.  It&#8217;s often just an exercise in learning and understanding.  I&#8217;ll read up on something and then try to think about how it works, what I could use it for and so forth.</p>
<p>Occasionally though I&#8217;ll feel compelled to actually write some code to test out the idea.  It&#8217;s good to prototype things.  It&#8217;s particularly handy for testing out new tech without the constraints of an existing system.</p>
<p>The latest idea that&#8217;s been running around my head has been <a href="http://en.wikipedia.org/wiki/Triplestore">triplestores</a>.  I&#8217;ve still yet to need to use one, but wanted to get a better understanding of how they work and what they can be used for.  Having spent a large number of years in the SQL database world, it seems like a good idea to try out some alternatives &#8211; if only to make sure that I&#8217;m not shoe-horning an SQL database into something purely because I know how they work.</p>
<p>So rather than do the sane thing and download a triplestore and start playing around with it, I decided to write my own.  Obviously I don&#8217;t have unlimited time so it had to be simple.  As of such I decided an in-memory store would still let me learn a fair bit, without being too onerous.  Over the past few weeks I&#8217;ve been working on this triplestore and it&#8217;s now at a point where it&#8217;s largely functional:</p>
<p><a href="https://github.com/lilspikey/mini-sparql">https://github.com/lilspikey/mini-sparql</a></p>
<p>To be honest writing this has been almost more of an exercise &#8211; a <a href="http://codekata.pragprog.com/">coding kata</a>.</p>
<p>A few key points of the implementation:</p>
<ul>
<li><a href="http://pypi.python.org/pypi/pyparsing/">PyParsing</a> for the parsing <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a></li>
<li>Lots of generator functions to make evaluation lazy</li>
<li>Interactive prompt for running SPARQL queries</li>
<li>Load triple data from file/stdin (as triples of data in simplified turtle format)</li>
</ul>
<p>As the data is all stored in memory it&#8217;s no good as a persistence store, but for quickly inspecting some triple data it works pretty well.  Simple point the minisparql.py script at a file containing triple data and away you go:</p>
<pre><code>
$ python minisparql.py birds.ttl
sparql> SELECT ?name WHERE { ?id name ?name . ?id color red }
name
'Robin'
</code></pre>
<h3>PyParsing</h3>
<p>PyParsing is a great project for writing recursive descent parsers.  It makes use of operator overloading to allow you to (mostly) write readable grammars.  You can also specify what objects you want to be returned from parsing &#8211; so it&#8217;s quite easy to parse some code and get back a list of objects that can then execute the code.</p>
<p>It also includes quite a few extra batteries.  One of the most powerful is <a href="http://packages.python.org/pyparsing/pyparsing.pyparsing-module.html#operatorPrecedence">operatorPrecedence</a>, which makes it a piece of cake to create the classic arithmetic style expressions we all know and love.  For example, the operatorPrecedence call in minisparql looks like:</p>
<pre><code>
expr=Forward()
# code removed for clarity
expr << operatorPrecedence(baseExpr,[
        (oneOf('!'), 1, opAssoc.RIGHT, _unaryOpAction),
        (oneOf('+ -'), 1, opAssoc.RIGHT, _unaryOpAction),
        (oneOf('* /'), 2, opAssoc.LEFT, _binOpAction),
        (oneOf('+ -'), 2, opAssoc.LEFT, _binOpAction),
        (oneOf('<= >= < >'), 2, opAssoc.LEFT, _binOpAction),
        (oneOf('= !='), 2, opAssoc.LEFT, _binOpAction),
        ('&#038;&#038;', 2, opAssoc.LEFT, _binOpAction),
        ('||', 2, opAssoc.LEFT, _binOpAction),
    ])
</code></pre>
<p>This handles grouping the various operators appropriately.  So rather than parsing:</p>
<pre><code>5 * 2 + 3 + 2 * 4</code></pre>
<p>And getting just a list of the individual elements you instead get a properly nested parse tree, that is equivalent to:</p>
<pre><code>((5 * 2) + 3) + (2 * 4)</code></pre>
<p>Where each binary operator is only operating on two other expressions (just as you would expect under classic C operator precedence).</p>
<p>This meant that implementing <a href="http://www.w3.org/TR/rdf-sparql-query/#tests">FILTER expressions</a> was pretty straightforward.</p>
<h3>Generators</h3>
<p><a href="http://www.python.org/dev/peps/pep-0255/">Generator functions</a> are one of my favourite features in Python.  I was completely blown away by David Beazley&#8217;s <a href="http://www.dabeaz.com/generators/">Generator Tricks for Systems Programmers</a>.  He starts off with fairly simple examples of generators and shows how they can be combined, much like piped commands in Unix, to create extremely powerful constructs.  Therefore it was obvious to me that generators were a good fit for minisparql.</p>
<p>The code for the regular, optional and union joins became pretty straightforward using generators.  For example the union join looked like:</p>
<pre><code>
    def match(self, solution):
        for m in self.pattern1.match(solution):
            yield m
        for m in self.pattern2.match(solution):
            yield m
</code></pre>
<p>This simply returns the result of one query, followed by the results of another.  The great thing about this is that if we only evaluate the first few values we might not even need to evaluate the second query.  The better aspect though is that you can start getting results straight away.  A more classical approach would entail building up a list of results:</p>
<pre><code>
    def match(self, solution):
        matches = []
        for m in self.pattern1.match(solution):
            matches.append(m)
        for m in self.pattern2.match(solution):
            matches.append(m)
        return matches
</code></pre>
<p>This code would always execute both queries &#8211; even if it wasn&#8217;t strictly necessary.  To my eye the generator code is much clearer as well.  <code>yield</code> stands out very well, in much the same way as <code>return</code> does.  It&#8217;s certainly much clearer that <code>matches.append(m)</code> which does not immediately make it clear that data is being returned/yielded from the function.</p>
<p>Anyway, so here&#8217;s my silly little bit of exploration.  I&#8217;ve learnt a fair bit and got to play with a some different ideas.</p>
<p>If I was to take this any further I&#8217;d probably want to add some sort of disk-based backend.  That way it might be useful for small/medium-sized SPARQL/RDF datasets for simple apps.  Much like <a href="http://www.sqlite.org/">SQLite</a> for SQL databases or <a href="http://pypi.python.org/pypi/Whoosh/">Whoosh</a> for full-text search.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2011/06/05/a-little-sparql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django User Profiles and select_related optimisation</title>
		<link>http://www.psychicorigami.com/2011/02/12/django-user-profiles-and-select_related-optimisation/</link>
		<comments>http://www.psychicorigami.com/2011/02/12/django-user-profiles-and-select_related-optimisation/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 19:01:03 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=416</guid>
		<description><![CDATA[If you want to associate extra information with a user account in Django you need to create a separate &#8220;User Profile&#8221; model. To get the profile for a given User object one simply calls get_profile. This is a nice easy way of handling things and helps keep the User model in Django simple. However it [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to associate extra information with a user account in Django you need to create <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users">a separate &#8220;User Profile&#8221; model</a>.  To get the profile for a given User object one simply calls <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_profile">get_profile</a>.  This is a nice easy way of handling things and helps keep the User model in Django simple.  However it does have a downside &#8211; fetching the user and user profile requires two database queries.  That&#8217;s not so bad when we&#8217;re selecting just one user and profile, but when we are displaying a list of users we&#8217;d end up doing one query for the users and another n-queries for the profiles &#8211; the classic <a href="http://www.pbell.com/index.cfm/2006/9/17/Understanding-the-n1-query-problem">n+1 query problem</a>!</p>
<p>To reduce the number of queries to just one we can use <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related">select_related</a>.  Prior to Django 1.2 <code>select_related</code> did not support the reverse direction of a <code>OneToOneField</code>, so we couldn&#8217;t actually use it with the user and user profile models.  Luckily that&#8217;s no longer a problem.</p>
<p>If we are clever we can setup the user profile so it stills works with <code>get_profile</code> and does not create an extra query.</p>
<p><code>get_profile</code> looks like this:</p>
<pre><code>
def get_profile(self):
        if not hasattr(self, '_profile_cache'):
            # ...
            # query to get profile and store it in _profile_cache on instance
            # so we don't need to look it up again later
            # ...
        return self._profile_cache
</code></pre>
<p>So if <code>select_related</code> stores the profile object in <code>_profile_cache</code> then <code>get_profile</code> will not need to do any more querying.</p>
<p>To do this we&#8217;d define the user profile model like this:</p>
<pre><code>
class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='_profile_cache')
    # ...
    # other model fields
    # ...
</code></pre>
<p>The key thing is that we have set <code>related_name</code> on the <code>OneToOneField</code> to be <code>'_profile_cache'</code>.  The <code>related_name</code> defines the attribute on the *other* model (User in this case) and is what we need to refer to when we use <code>select_related</code>.</p>
<p>Querying for all user instances and user profiles at the same time would look like:</p>
<pre><code>
User.objects.selected_related('_profile_cache')
</code></pre>
<p>The only downside is that this does change the behaviour of <code>get_profile</code> slightly.  Previously if no profile existed for a given user a <code>DoesNotExist</code> exception is raised.  With this approach <code>get_profile</code> instead returns <code>None</code>.  So you&#8217;re code will need to handle this.  On the upside repeated calls to <code>get_profile</code>, when no profile exists, won&#8217;t re-query the database.</p>
<p>The other minor problem is that we are relying on the name of a private attribute on the User model (that little pesky underscore indicates it&#8217;s not officially for public consumption).  Theoretically the attribute name could change in a future version of Django.  To mitigate against the name changing I&#8217;d personally just store the name in a variable or on the profile model as a class attribute and reference that whenever you need it, so at least there&#8217;s only one place to make any change.  Apart from that this only requires a minor modification to your user profile model and the use of <code>select_related</code>, so it&#8217;s not a massively invasive optimisation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2011/02/12/django-user-profiles-and-select_related-optimisation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Blinking Halloween Spider Eyes Hats using PICAXE 08m chips</title>
		<link>http://www.psychicorigami.com/2010/11/01/blinking-halloween-spider-eyes-hats-using-picaxe-08m-chips/</link>
		<comments>http://www.psychicorigami.com/2010/11/01/blinking-halloween-spider-eyes-hats-using-picaxe-08m-chips/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 10:00:54 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Picaxe]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=397</guid>
		<description><![CDATA[For some reason I got seized by the idea of creating some electronics for our Halloween costumes this year. In previous years I have gone as far as dying my hair green for Halloween, but that is just an evening&#8217;s work. This year we were having a more sedate affair &#8211; it being our first [...]]]></description>
			<content:encoded><![CDATA[<p>For some reason I got seized by the idea of creating some electronics for our Halloween costumes this year.  In previous years I have gone as far as dying my hair green for Halloween, but that is just an evening&#8217;s work.  This year we were having a more sedate affair &#8211; it being our first Halloween as parents.</p>
<p>We settled on making spider costumes.  Basically black clothing, with extra arms made out of tights.  I then decided that as spiders have eight eyes that making some hats with six extra eyes would make sense.  After initially thinking I would just hook up some LEDs straight to a battery I decided to massively complicate matters by and try to make them blink periodically (at random).</p>
<p>So for this act of over-complication I chose to use the <a href="http://www.psychicorigami.com/2010/09/18/programming-a-picaxe-08m-chip/">PICAXE 08m microprocessor</a>.  The core circuit (minus ability to program) is essentially just 3AA batteries, the chip itself and two resistors &#8211; so at least for a circuit involving a microprocessor wasn&#8217;t that byzantine.  That is kind of the point of a microprocessor though.  To the end-user it hides it&#8217;s internal complexity away.  I don&#8217;t really need to know how many hundreds or thousands of transistors it contains internally.  I only need to think about how it fits into my circuit.</p>
<p>I chose to have six LEDs to create pairs of &#8220;eyes&#8221; that would blink in tandem.  This meant the PICAXE chip would turn three output pins on and off at random intervals.  With a 4.5V power supply two LEDs wouldn&#8217;t need a massive current limiting resistor &#8211; <a href="http://led.linear1.org/led.wiz">100Ohm would be sufficient</a>.  So the circuit consists of the 08m chip, two resistors (10KOhm and 22KOhm) to pull-down the serial-in pin, a 100nF capacitor to even the power supply, six LEDs and three 100Ohm current limiting resistors:</p>
<p><center><img src="http://www.psychicorigami.com/wp-content/uploads/2010/10/eyes_bb.png" alt="" title="Blinking eyes circuit" width="674" height="457" class="alignnone size-full wp-image-401" /></center></p>
<p>It&#8217;s not actually that complex a circuit, but spending several hours soldering it up (twice) for a couple of hours at a party might have been overkill.  Still it was good practice.  I also got to try out fitting everything into some project boxes and generally making things look &#8220;proper&#8221;.</p>
<p><center><br />
<a href="http://www.flickr.com/photos/lilspikey/5128210681/" title="Underside of circuit by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4124/5128210681_999ac15ab6.jpg" width="500" height="375" alt="Underside of circuit" /></a></p>
<p><a href="http://www.flickr.com/photos/lilspikey/5126790308/" title="Finished soldering the LED eyes by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4125/5126790308_b96ab6cef1.jpg" width="500" height="375" alt="Finished soldering the LED eyes" /></a></p>
<p><a href="http://www.flickr.com/photos/lilspikey/5126787432/" title="Making sure it all fits in project box by lilspikey, on Flickr"><img src="http://farm2.static.flickr.com/1057/5126787432_cf8b312723.jpg" width="500" height="375" alt="Making sure it all fits in project box" /></a><br />
</center></p>
<p>I used perfboard for the finished circuit, with some holes enlarged to accept screws for the project box.  I also added some extra holes so I could loop the power and LED wires through.  This helped to make the connections nice and sturdy.</p>
<p>The chips were programmed using a different circuit, with the serial adapter attached and were then removed from their sockets and inserted into the soldered circuits.  The two hats had slightly different programs uploaded to tweak the speed and random nature of the blinking (so they wouldn&#8217;t be too similar).  <a href="http://github.com/lilspikey/picaxe08m/blob/master/eyes.bas">The code</a> is viewable at my <a href="http://github.com/lilspikey/picaxe08m">picaxe08m repository</a> on github (as well as a <a href="http://fritzing.org/">Fritzing</a> file for <a href="http://github.com/lilspikey/picaxe08m/blob/master/eyes.fz">the circuit</a>).  I did encounter a <a href="http://www.picaxeforum.co.uk/archive/index.php/t-11785.html">bug in the PICAXE compiler</a> whilst writing this code.  When I started using subroutines (and the <code>gosub</code> call) <a href="http://www.rev-ed.co.uk/picaxe/software.htm">MacAXEPad</a> would suddenly say &#8220;Hardware not found&#8221; when attempting to upload.  Apparently this problem only affects the Mac version of AXEPad.  Luckily there was an easy fix &#8211; simply adding a dummy sub-routine at the end of the file:</p>
<pre>
<code>interrupt: return</code>
</pre>
<p><center><br />
<a href="http://www.flickr.com/photos/lilspikey/5126799756/" title="The Eye Hat by lilspikey, on Flickr"><img src="http://farm2.static.flickr.com/1057/5126799756_9d73aa69db.jpg" width="500" height="375" alt="The Eye Hat" /></a><br />
</center></p>
<p>The finished result looked a bit goofy, but it did work.  The main problem though was that it only really worked when the light was low.  Not a bad problem for halloween I guess:</p>
<p><center><br />
<object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=a6e15d460c&#038;photo_id=5126825058"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=a6e15d460c&#038;photo_id=5126825058" height="300" width="400"></embed></object><br />
</center></p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/11/01/blinking-halloween-spider-eyes-hats-using-picaxe-08m-chips/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;Ultimate&#8221; Arduino Doorbell &#8211; part 2 (Software)</title>
		<link>http://www.psychicorigami.com/2010/10/16/ultimate-arduino-doorbell-part-2-software/</link>
		<comments>http://www.psychicorigami.com/2010/10/16/ultimate-arduino-doorbell-part-2-software/#comments</comments>
		<pubDate>Sat, 16 Oct 2010 18:45:00 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Application]]></category>
		<category><![CDATA[Arduino]]></category>
		<category><![CDATA[chumby]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=380</guid>
		<description><![CDATA[As mentioned in the previous post about my arduino doorbell I wanted to get the doorbell and my Chumby talking. As the Chumby runs Linux, is on the network and is able to run a recent version of Python (2.6) it seemed like it would be pretty easy to get it to send Growl notifications [...]]]></description>
			<content:encoded><![CDATA[<p>As mentioned in the <a href="http://www.psychicorigami.com/2010/09/06/ultimate-arduino-doorbell-part-1-hardware/">previous post about my arduino doorbell</a> I wanted to get the doorbell and my <a href="http://www.chumby.com/">Chumby</a> talking.</p>
<p>As the Chumby runs Linux, is on the network and is able to run a recent version of Python (2.6) it seemed like it would be pretty easy to get it to send <a href="http://growl.info/">Growl</a> notifications to the local network.</p>
<p><center><img src="http://www.psychicorigami.com/wp-content/uploads/2010/10/growl-doorbell.png" alt="" title="growl doorbell notification" width="421" height="117" class="alignnone size-full wp-image-381" /></center></p>
<p>This did indeed prove fairly easy and involved three main activities:</p>
<ul>
<li>Listening to the serial port for the doorbell to ring</li>
<li>Using <a href="http://www.apple.com/support/bonjour/">Bonjour (formally Rendezvous)</a>/<a href="http://www.zeroconf.org/">Zeroconf</a> to find computers on the network</li>
<li>Sending network Growl notifications to those computers</li>
</ul>
<p>Getting <a href="http://www.psychicorigami.com/2010/06/26/chumby-to-arduino-communication-using-pyserial/">Python and PySerial running on the Chumby</a> is pretty easy.  The Chumby simply listens for the doorbell to send the string &#8216;DING DONG&#8217; and can then react as needed.</p>
<pre><code>
def listen_on_serial_port(port, network):
    ser = serial.Serial(port, 9600, timeout=1)
    try:
        while True:
            line = ser.readline()
            if line is not None:
                line = line.strip()
            if line == 'DING DONG':
                network.send_notification()
    finally:
        if ser:
            ser.close()
</code></pre>
<p><code>port</code> is the string representing the serial port (e.g. <code>/dev/ttyUSB0</code>). <code>network</code> is an object that handles the network notifications (see below).</p>
<p>The network object (an instance of <code>Network</code>) has two jobs.  Firstly to find computers on the network (using PicoRendezvous &#8211; now called <a href="http://www.taoofmac.com/projects/picobonjour">PicoBonjour</a>) and secondly to send network growl notifications to those computers.</p>
<p>A background thread periodically calls <code>Network.find</code>, which uses multicast DNS (Bonjour/Zeroconf) to find the IP addresses of computers to notify:</p>
<pre><code>
class Network(object):
    title = 'Ding-Dong'
    description = 'Someone is at the door'
    password = None

    def __init__(self):
        self.growl_ips = []
        self.gntp_ips = []

    def _rendezvous(self, service):
        pr = PicoRendezvous()
        pr.replies = []
        return pr.query(service)

    def find(self):
        self.growl_ips = self._rendezvous('_growl._tcp.local.')
        self.gntp_ips  = self._rendezvous('_gntp._tcp.local.')
        def start(self):
        import threading
        t = threading.Thread(target=self._run)
        t.setDaemon(True)
        t.start()

    def _run(self):
        while True:
            self.find()
            time.sleep(30.0)
</code></pre>
<p><code>_growl._tcp.local.</code> are computers that can handle Growl UDP packets and <code>_gntp._tcp.local.</code> those that can handle the newer <a href="http://www.growlforwindows.com/gfw/help/gntp.aspx">GNTP protocol</a>.  Currently the former will be Mac OS X computers (running Growl) and the latter Windows computers (running <a href="http://www.growlforwindows.com/">Growl for Windows</a>).</p>
<p>I had to <a href="http://github.com/lilspikey/doorbell/commit/33bbfa13cbd81691b5dcac2a48b84aea38a4c0f0">tweak PicoRendezvous slightly</a> to work round a bug on the Chumby version of Python, where <code>socket.gethostname</code> was returning the string <code>'(None)'</code>, but otherwise this worked ok.</p>
<p>When the doorbell activates <a href="http://www.taoofmac.com/projects/netgrowl">netgrowl</a> is used to send Growl UDP packets to the IP addresses in <code>growl_ips</code> and the <a href="http://github.com/kfdm/gntp">Python gntp library</a> to notify those IP addresses in <code>gntp_ips</code> (but not those duplicated in <code>growl_ips</code>).  For some reason my Macbook was appearing in both lists of IP addresses, so I made sure that the <code>growl_ips</code> took precedence.</p>
<pre><code>
    def send_growl_notification(self):
        growl_ips = self.growl_ips

        reg = GrowlRegistrationPacket(password=self.password)
        reg.addNotification()

        notify = GrowlNotificationPacket(title=self.title,
                    description=self.description,
                    sticky=True, password=self.password)
        for ip in growl_ips:
            addr = (ip, GROWL_UDP_PORT)
            s = socket(AF_INET, SOCK_DGRAM)
            s.sendto(reg.payload(), addr)
            s.sendto(notify.payload(), addr)

    def send_gntp_notification(self):
        growl_ips = self.growl_ips
        gntp_ips  = self.gntp_ips

        # don't send to gntp if we can use growl
        gntp_ips = [ip for ip in gntp_ips if (ip not in growl_ips)]

        for ip in gntp_ips:
            growl = GrowlNotifier(
                applicationName = 'Doorbell',
                notifications = ['doorbell'],
                defaultNotifications = ['doorbell'],
                hostname = ip,
                password = self.password,
            )
            result = growl.register()
            if not result:
                continue
            result = growl.notify(
                noteType = 'doorbell',
                title = self.title,
                description = self.description,
                sticky = True,
            )

    def send_notification(self):
        '''
        send notification over the network
        '''
        self.send_growl_notification()
        self.send_gntp_notification()
</code></pre>
<p>The code is pretty simple and will need some more tweaking.  The notification has failed for some reason a couple of times, but does usually seem to work.  I&#8217;ll need to start logging the doorbell activity to see what&#8217;s going on, but I suspect the Bonjour/Zeroconf is sometimes finding no computers.  If so I&#8217;ll want to keep the previous found addresses hanging around for a little longer &#8211; just in case it&#8217;s a temporary glitch.</p>
<p>You can see the full code in my <a href="http://github.com/lilspikey/doorbell">doorbell repository</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/10/16/ultimate-arduino-doorbell-part-2-software/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming a Picaxe 08m chip</title>
		<link>http://www.psychicorigami.com/2010/09/18/programming-a-picaxe-08m-chip/</link>
		<comments>http://www.psychicorigami.com/2010/09/18/programming-a-picaxe-08m-chip/#comments</comments>
		<pubDate>Sat, 18 Sep 2010 12:43:06 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Picaxe]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=367</guid>
		<description><![CDATA[After I got my Arduino I felt the urge to brush up on my general electronics knowledge. The last time I&#8217;d really played with any circuits was back in about 1994 when I was studying my Technology GCSE &#8211; which now is quite a long time ago. So I picked up a copy of Make: [...]]]></description>
			<content:encoded><![CDATA[<p>After I got my Arduino I felt the urge to brush up on my general electronics knowledge.  The last time I&#8217;d really played with any circuits was back in about 1994 when I was studying my Technology GCSE &#8211; which now is quite a long time ago.  So I picked up a copy of <a href="http://www.amazon.co.uk/Make-Electronics-Learning-Through-Discovery/dp/0596153740/">Make: Electronics</a> and started reading through it.  Sadly I was a bit lazy and just read through the book, rather than actually building many of the circuits suggested.  It did come in handy for tips on soldering and I do intend to go back and make some of the circuits &#8211; I just got a bit distracted by a <a href="http://www.flickr.com/photos/lilspikey/4888528727/">new arrival</a>.  However the last chapter covered microcontrollers and in particular the <a href="http://www.rev-ed.co.uk/picaxe/">Picaxe 08m</a> chip.  This really piqued my interest!</p>
<p>The Picaxe 08m is a PIC chip with a pre-installed boot-loader that allows programming the chip via a serial port.  This is similar to the way that the Arduino has an AVR chip with a pre-installed boot-loader.  There&#8217;s also some software for the Picaxe for handling the programming, a bit like the Arduino IDE.</p>
<p>The 08m is massively less powerful than an Arduino.  It has 512 *bytes* of program storage and only 14 *bytes* of variable RAM.  However it has 5 outputs/4 inputs and can run a single servo.  In fact I could have used it for the logic part of my <a href="http://www.psychicorigami.com/2010/09/06/ultimate-arduino-doorbell-part-1-hardware/">Arduino doorbell</a>.  It&#8217;s not quite as friendly to get started with as an Arduino though.  You need to wire up a simple circuit before you can get going.  In fact I actually had to solder together a <a href="http://www.techsupplies.co.uk/epages/Store.sf/en_GB/?ObjectPath=/Shops/Store.TechSupplies/Products/AXE021">prototyping board</a>, as I didn&#8217;t have much luck trying to used a breadboard.  The circuit needed isn&#8217;t that complex (assuming you use 3AA batteries for power).  The cost of the 08m chip is less that £2.  The proto-board is £2, so altogether you can have a simple usable microprocessor for less than £4.  It&#8217;s also small and doesn&#8217;t use much power.  So for projects where an Arduino is overkill it&#8217;s perfect.</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4979486393/" title="Soldered picaxe 08m prototype board by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4089/4979486393_02b7d3a824.jpg" width="500" height="375" alt="Soldered picaxe 08m prototype board" /></a></center></p>
<p>To make testing out circuits easier I also added a female header to the board, so I could plug in breadboard jumper cables (in the same way as one does with an Arduino Duemilanove):</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4993297869/" title="Picaxe 08m prototype board with header attached by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4108/4993297869_d8966889ce.jpg" width="500" height="375" alt="Picaxe 08m prototype board with header attached" /></a></center></p>
<p>To verify everything worked I wrote the &#8220;hello world&#8221; program of microcontroller world, a program that simply blinks an LED (by turning pin 1 on and off):</p>
<p><code>
<pre>
main:
	high 1
	pause 1000
	low 1
	pause 1000
	goto main
</pre>
<p></code></p>
<p>That&#8217;s Picaxe BASIC by the way.  Maybe not as pretty as C, but for a processor with only 14 byte sized variables it&#8217;s more than enough.</p>
<p>Then I wired up an LED into the prototype board, along with a small current limiting resistor:</p>
<p><center><img src="http://www.psychicorigami.com/wp-content/uploads/2010/09/blink_bb.png" alt="" title="Blink Circuit" width="526" height="588" class="alignnone size-full wp-image-369" /></center></p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4993898236/" title="Picaxe 08m prototype board + header blinking LED by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4152/4993898236_3327281a2e.jpg" width="500" height="375" alt="Picaxe 08m prototype board + header blinking LED" /></a></center></p>
<p>Using the Mac version of <a href="http://www.rev-ed.co.uk/picaxe/software.htm">AXEPad</a> and the Picaxe USB serial cable (which has a stereo socket at one end) I uploaded the program to the 08m chip and saw the LED blinking once every second.  I&#8217;ve recorded a <a href="http://www.flickr.com/photos/lilspikey/4997041076/in/photostream/">video of the programming</a>, which should show how straightforward it is:</p>
<p><center><object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=091517541a&#038;photo_id=4997041076"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=091517541a&#038;photo_id=4997041076" height="300" width="400"></embed></object></center></p>
<p>I&#8217;ve got a few projects in mind that are actually space/weight constrained and one in particular that might put the parts involved into extreme peril, so having the option of using a very small and cheap microcontroller is very appealing.  I&#8217;ll reserve the Arduino now for projects that need it&#8217;s extra power and amazing flexibility.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/09/18/programming-a-picaxe-08m-chip/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8220;Ultimate&#8221; Arduino Doorbell &#8211; part 1 (Hardware)</title>
		<link>http://www.psychicorigami.com/2010/09/06/ultimate-arduino-doorbell-part-1-hardware/</link>
		<comments>http://www.psychicorigami.com/2010/09/06/ultimate-arduino-doorbell-part-1-hardware/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 17:30:53 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Craft]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=346</guid>
		<description><![CDATA[After a first couple of small Arduino projects I felt the need to make something a bit more useful and permanent. I had seen Roo Reynolds talking about hacking his doorbell to get it onto Twitter and as our doorbell is a bit rubbish I thought this seemed like a good project. His hack only [...]]]></description>
			<content:encoded><![CDATA[<p>After a <a href="http://www.psychicorigami.com/2010/05/26/my-first-arduino-project-morse-code/">first</a> <a href="http://www.psychicorigami.com/2010/06/13/arduino-tone-generatortheremin/">couple</a> of small <a href="http://www.arduino.cc/">Arduino</a> projects I felt the need to make something a bit more useful and permanent.</p>
<p>I had seen Roo Reynolds talking about <a href="http://rooreynolds.com/2008/05/14/hacking-the-doorbell/">hacking his doorbell</a> to get it onto <a href="http://twitter.com/">Twitter</a> and as our doorbell is a bit rubbish I thought this seemed like a good project.  His hack only updated Twitter, so there was no direct physical sign that the doorbell had been rung.  Given that our current doorbell is pretty rubbish anyway (it should ring, but just makes a rattling sound), I decided to start off with the physical/audible side of things and then later move on to pushing notifications out to laptops on the local network or beyond&#8230;</p>
<p>I&#8217;ve been <a href="http://www.flickr.com/photos/lilspikey/sets/72157624576532196/">documenting my progress on Flickr</a> now for a while.</p>
<h3>Take apart wireless doorbell</h3>
<p>Following Roo&#8217;s approach, I picked up a cheap wireless doorbell from Tesco for about £9 and took it apart:</p>
<p><center><object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=5f4e19d9bc&#038;photo_id=4752349287"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=5f4e19d9bc&#038;photo_id=4752349287" height="300" width="400"></embed></object></center></p>
<p>I was able to verify that I could turn an LED on/off with the doorbell at this stage, so I knew I could use that as a signal in the Arduino.  Using a multimeter also let me figure out some more details about the voltage and current used to power the speaker:</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4752984700/" title="Testing wireless doorbell with multi-meter by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4143/4752984700_126d5f59e0.jpg" width="500" height="375" alt="Testing wireless doorbell with multi-meter" /></a></center></p>
<p>This was about 3.1 V and 75mA output.  That&#8217;s a few milliamps more than the Arduino  can tolerate, so I knew I had to make sure I put a resistor (22KOhm) in between the doorbell and the Arduino.  The doorbell would also need to draw power from the Arduino, but luckily the Arduino has a separate 3V output, so that wasn&#8217;t an issue.</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4788279184/" title="Testing connecting Arduino to doorbell by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4121/4788279184_2ab296c772.jpg" width="500" height="375" alt="Testing connecting Arduino to doorbell" /></a></center></p>
<p>From there I verified that when the doorbell was activated I could read a drop in voltage from the wire on the doorbell labelled &#8220;SPI&#8221;.  At this point I had the input for my Arduino.</p>
<h3>Servos and prototypes</h3>
<p>The next step was to provide some sort of audible output.  Originally I had thought about just adding a buzzer, but fancied something a bit more old-fashioned.  I figured it&#8217;d be good fun if the nice 21st century tech of the Arduino used some rather more ancient technology to create sound &#8211; a bell.</p>
<p>Using a <a href="http://www.oomlout.co.uk/servo-micro-p-195.html">micro servo</a> from <a href="http://www.oomlout.co.uk/">Oomlout</a> I created a couple of prototypes.</p>
<p>I made a pretty simple circuit to hook up the servo, doorbell and arduino:</p>
<p><center><a href="http://www.psychicorigami.com/wp-content/uploads/2010/08/doorbell-circuit_bb.png"><img src="http://www.psychicorigami.com/wp-content/uploads/2010/08/doorbell-circuit_bb-300x234.png" alt="" title="doorbell-circuit_bb" class="alignnone size-medium wp-image-355" /></a></center></p>
<p>The first prototype used some lego and a bell from a Christmas ornament:</p>
<p><center><object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=53bdf364c4&#038;photo_id=4791359380"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=53bdf364c4&#038;photo_id=4791359380" height="300" width="400"></embed></object></center></p>
<p>This worked, but the servo was probably louder than the bell!</p>
<p>Next I got hold of a small brass bell from a music shop.  Luckily the top unscrewed and would let me easily attached it to a piece of lego.  So another prototype was created using the small brass bell:</p>
<p><center><object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=bc47ae4dda&#038;photo_id=4816173880"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=bc47ae4dda&#038;photo_id=4816173880" height="300" width="400"></embed></object></center></p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4815509199/" title="Prototype doorbell with brass bell by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4094/4815509199_86bf9619ab.jpg" width="375" height="500" alt="Prototype doorbell with brass bell" /></a></center></p>
<p>This worked much better!</p>
<p>The bell is about 100g in weight, which isn&#8217;t massive, but when it&#8217;s flung around the lego prototype would tend to move too.  Not so good when this will live on the kitchen window sill.  So I&#8217;d need something sturdier for the finished version.</p>
<h3>A little soldering</h3>
<p>As well as trying out a better bell I also made the circuit for the bell and servo more permanent, by soldering everything up on a piece of stripboard.  I also used a few headers, so most of the circuit would plug into the Arduino &#8211; like a rudimentary shield.  The wire to the pin controlling the servo, was left to be plugged in separately.  I hadn&#8217;t soldered anything since school, so I ended up swearing quite a bit trying to do this.  For me it was probably the trickiest part of the whole exercise, but it did work in the end.  Just glad I had a multi-meter with a continuity mode to find the short-circuits &#8211; a knife worked well to clear up some of those.</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4804125867/" title="Stripboard soldering by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4101/4804125867_6332e767a1.jpg" width="500" height="375" alt="Stripboard soldering" /></a></center></p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4809442783/" title="Full soldered doorbell + arduino by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4138/4809442783_47187ef64e.jpg" width="500" height="375" alt="Full soldered doorbell + arduino" /></a></center></p>
<h3>Woodwork</h3>
<p>I next turned to my (t)rusty woodwork skills to create a sturdier version.  First off some pieces of wood to mount the Arduino, doorbell circuit and servo:</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4830629857/" title="Arduino and doorbell mounted on wood block by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4137/4830629857_ee660268cb.jpg" width="375" height="500" alt="Arduino and doorbell mounted on wood block" /></a></center></p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4830623385/" title="Servo mounted in wooden block by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4140/4830623385_1e39e364c1.jpg" width="500" height="375" alt="Servo mounted in wooden block" /></a></center></p>
<p>Next came the base and first part of the bell moving arm:</p>
<p><center><object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=91d599f22c&#038;photo_id=4885839014"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=91d599f22c&#038;photo_id=4885839014" height="300" width="400"></embed></object></center></p>
<p>Then I added the top piece of the arm as well as the picture wire to make the bell swing properly:</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4890557080/" title="Closeup of bell innards by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4079/4890557080_c5bf59a7d0.jpg" width="375" height="500" alt="Closeup of bell innards" /></a></center></p>
<p>At this point everything worked as expected:</p>
<p><center><object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=118f68d3a7&#038;photo_id=4889121194"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=118f68d3a7&#038;photo_id=4889121194" height="300" width="400"></embed></object></center></p>
<h3>Tidying up</h3>
<p>After the sawing and sanding was finished there was still some general tidying up to do.</p>
<p>Once I&#8217;d taped down the servo wire and antena wire with electrical tape I needed to deal with the movement of the whole piece when the arm swings out.  First I got hold of some <a href="http://sugru.com/">Sugru</a> and made some small rubberised feet to prevent the bell sliding around:</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4934949688/" title="Sugru rubber feet on bell by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4143/4934949688_8fbb5ce2f4.jpg" width="375" height="500" alt="Sugru rubber feet on bell" /></a></center></p>
<p>The next task was to add a counter weight so the bell wouldn&#8217;t tip over.  For this I made two piles of fifteen pennies, which I wrapped in electrical tape and taped to the ledge on the reverse side from the Arduino:</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4957542998/" title="Counter weights on back/front of doorbell by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4110/4957542998_bc4d7e1b74.jpg" width="375" height="500" alt="Counter weights on back/front of doorbell" /></a></center></p>
<p>Eventually these will be covered up and will probably actually make up part of the internal structure of the outer decoration.  This should also mean they&#8217;ll end up being attached better.  For now though electrical tape has proved sufficient.</p>
<p>One final tweak involved inserting some small nylon washers either side of the arm:</p>
<p><center><a href="http://www.flickr.com/photos/lilspikey/4957545726/" title="Washer and tidier wire by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4150/4957545726_6ca9f5a433.jpg" width="500" height="375" alt="Washer and tidier wire" /></a></center></p>
<p>This was done to help make the movement of the arm more consistent and slightly smoother.  Previously I was finding that the arm would shift position slightly, which sometimes caused problems for the servo.</p>
<h3>Deployment</h3>
<p>With the hardware finished I then set about actually getting it all up and running as our real doorbell.  So imagine my horror when upon placing the doorbell on our kitchen window sill and connecting the power everything went haywire and the arm just constantly moved!  After some tweaking of the code and kitchen-side debugging I realised that I really should make use of the Arduino&#8217;s <a href="http://www.arduino.cc/en/Tutorial/DigitalPins">internal pullup resistors</a> for the doorbell pin.  Up until that point I had left it &#8220;floating&#8221;.  When powered by the USB this rarely drifted to zero, so I thought it was working fine.  However on mains power it regularly dropped quite low, making the Arduino think the button had been pressed, triggering the servo.  Configured the pullup resistor and tweaking the activation threshold (as it was now higher than zero) sorted out this problem perfectly:</p>
<p><center><object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=71377" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="flashvars" value="intl_lang=en-us&#038;photo_secret=643bb81e07&#038;photo_id=4957539834"></param><param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=71377"></param><param name="bgcolor" value="#000000"></param><param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=71377" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&#038;photo_secret=643bb81e07&#038;photo_id=4957539834" height="300" width="400"></embed></object></center></p>
<h3>Conclusion</h3>
<p>So we now have a slightly Heath Robinson doorbell.  It works better that our old one.  There&#8217;s also plenty of scope for making it do more too.  In fact phase two will be mostly about connecting the doorbell to my <a href="http://www.chumby.com/">Chumby</a> to get it communicating with the local network.</p>
<p>Check out my <a href="http://github.com/lilspikey/doorbell">doorbell git repository</a> on github for the code, as well as a <a href="http://fritzing.org/">fritzing</a> circuit file.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/09/06/ultimate-arduino-doorbell-part-1-hardware/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Kite Physics</title>
		<link>http://www.psychicorigami.com/2010/07/16/kite-physics/</link>
		<comments>http://www.psychicorigami.com/2010/07/16/kite-physics/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 22:35:01 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Application]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=324</guid>
		<description><![CDATA[I&#8217;ve finally managed to finish the Kite Physics Demo I started back in October: Kite Physics Demo It&#8217;s more of a plaything than anything else. It did give me a chance to try out writing some physics code again, something I don&#8217;t get much of a chance to do during web development. Though of course [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve finally managed to finish the Kite Physics Demo I started <a href="http://www.psychicorigami.com/2009/10/03/kite-physics-demo/">back in October</a>:</p>
<p><center><br />
<a href="http://www.psychicorigami.com/kite/"><img class="alignnone size-full wp-image-325" title="kite physics" src="http://www.psychicorigami.com/wp-content/uploads/2010/07/kite-physics.jpg" alt="" width="480" height="480" /><br />
Kite Physics Demo<br />
</a><br />
</center></p>
<p>It&#8217;s more of a plaything than anything else.  It did give me a chance to try out writing some physics code again, something I don&#8217;t get much of a chance to do during web development.  Though of course advances in Javascript speed and the <a href="https://developer.mozilla.org/en/canvas_tutorial">Canvas tag</a> may change that in the future.</p>
<p>Originally I made use of the keyboard to control the figure and the kite, but I switched to using the mouse as it makes interacting with the scene more pleasing.  There&#8217;s a certain joy to being able to grab the kite to move it around or shift the wind direction by nudging a cloud.</p>
<p>It&#8217;s all written in Java, using <a href="http://maven.apache.org/">maven</a> to build and package.  The code is available in my <a href="http://github.com/lilspikey/kite">kite repo on guthub</a>.</p>
<p>There&#8217;s about one third of a physics engine in the code.  There&#8217;s no real collision detection for example.  Most of the physics code is for handling constraints and basic forces.  For the constraints I made use of the Gauss-Seidel technique, as outlined in <a href="http://www.teknikus.dk/tj/gdc2001.htm">Advanced Character Physics by Thomas Jakobsen</a>.  This was quite a revelation to me.  Previously I&#8217;d experimented with <a href="http://chrishecker.com/Rigid_Body_Dynamics">rigid body dynamics</a> (see my <a href="http://littlespikeyland.com/racinggame/">2D racing game</a> circa 2001), but the Gauss-Seidel method seemed much more intuitive.  I found it much easier to think of bodies made up of points connected by lines.  The &#8220;physics&#8221; naturally emerges from the way the bodies are then constructed.</p>
<p>The core physics code (in the <code>com.psychicorigami.physics.*</code> package) is fairly well structured.  There a bit of compiler placation to (theoretically) allow for the same code to work for 2D and 3D physics.  I&#8217;ve only actually implemented the 2D side of things, but have tried to use generics to make room for 3D too.  When everything is points and lines, moving from 2D to 3D is not that tricky.  Whereas for rigid body dynamics this can mean quite a big change in representation.</p>
<p>The code in the default package is used for the specifics of the demo itself, so is a bit messy really.  Lots of tweaking and prodding was needed to get things how I wanted.</p>
<p>The physics for the kite and wind interaction were aided massively by this <a href="http://www.grc.nasa.gov/WWW/K-12/airplane/kitefor.html">guide to forces on a kite</a>.  Particularly useful for understanding how to tweak the rigging, centre of gravity and centre of pressure of the kite to make it behave in a pleasing &#8211; if not entirely realistic &#8211; manner.</p>
<p>At some point I hope to revisit the physics code here.  I&#8217;ve always had a wish to create something like <a href="http://www.karlsims.com/">Karl Sims</a> &#8220;blocky creatures&#8221;, but lacked the specific technical knowledge.  Know that I have a technique for simulating complex constraints in an intuitive manner maybe I&#8217;ll manage it yet.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/07/16/kite-physics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>watch-cp.py</title>
		<link>http://www.psychicorigami.com/2010/07/06/watch-cp-py/</link>
		<comments>http://www.psychicorigami.com/2010/07/06/watch-cp-py/#comments</comments>
		<pubDate>Tue, 06 Jul 2010 20:53:42 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Application]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=315</guid>
		<description><![CDATA[During software development it&#8217;s key to minimize the time between editing code and seeing the results of a change. During web-development the constant tweaking of CSS/HTML/Javascript etc means you&#8217;re always reloading the browser to see changes. At work I do a lot of Java web development, which normally involves compiling code, packaging into a .war [...]]]></description>
			<content:encoded><![CDATA[<p>During software development it&#8217;s key to minimize the time between editing code and seeing the results of a change.  During web-development the constant tweaking of CSS/HTML/Javascript etc means you&#8217;re always reloading the browser to see changes.</p>
<p>At work I do a lot of Java web development, which normally involves compiling code, packaging into a .war file and deploying it to <a href="http://tomcat.apache.org/">Tomcat</a> (running locally).  I make use of the <a href="http://mojo.codehaus.org/tomcat-maven-plugin/">maven tomcat plugin</a>, so it&#8217;s just a case of calling <code>maven tomcat:redeploy</code>.  However it still takes tens of seconds (or more if there are tests to run).  For quick tweaks of css it&#8217;s nice to be able to short-circuit this process.</p>
<p>Tomcat unpacks the .war file to another directory after the app has been deployed.  All the .jsp pages, css and javascript files can be edited in this directory and changes can be seen immediately.  However getting into the habit of editing these files within this directory is usually a bad idea, as the files will get overwritten at the next deployment.</p>
<p>We&#8217;ve been using <a href="http://compass-style.org/">compass</a> lately for css and it has a handy command:</p>
<pre>
<code>
    compass watch
</code>
</pre>
<p>That monitors .sass files for changes, then re-compiles them to css as they change, so you can see changes quickly (without needing to manually run compass each time).</p>
<p>So I thought I could do something similar for the editable files within the war file.  So I created <a href="http://gist.github.com/379197">watch-cp.py</a>.  It simply monitors a set of files and/or directories for changes and copies over files that have changed to a source file or directory.  To provide a bit of feedback it prints out when it spots a changed file, but beyond that it&#8217;s pretty brute-force in it&#8217;s approach.</p>
<p><code>watch-cp.py</code> works in a very similar way to the <code>cp</code> command, but without as many options.  For example:</p>
<pre>
<code>
    # recursively copy files from src/main/webapp to tomcat
    watch-cp.py -r src/main/webapp/* ~/tomcat/webapps/mywebapp
</code>
</pre>
<p>This is great as it means I can edit my sass files, have them compiled to css by compass, then copied over to tomcat without needing to intervene.  It takes a second sometimes, but it&#8217;s fast enough for the most part.</p>
<p>Feel free to fork the <a href="http://gist.github.com/379197">gist of watch-cp.py</a> on github.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/07/06/watch-cp-py/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iPhone Brighton Buses webapp/javascript front-end</title>
		<link>http://www.psychicorigami.com/2010/07/04/iphone-brighton-buses-webappjavascript-front-end/</link>
		<comments>http://www.psychicorigami.com/2010/07/04/iphone-brighton-buses-webappjavascript-front-end/#comments</comments>
		<pubDate>Sun, 04 Jul 2010 19:23:37 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Application]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=285</guid>
		<description><![CDATA[Here in Brighton a good number of the bus stops have electronic boards, that tell you when the next buses are due. The data for these boards is available online and even provides data for stops that don&#8217;t have the electronic boards. In fact there&#8217;s an free iPhone app available, so you can get the [...]]]></description>
			<content:encoded><![CDATA[<p>Here in Brighton a good number of the bus stops have electronic boards, that tell you when the next buses are due.  The data for these boards is <a href="http://buses.co.uk/">available online</a> and even provides data for stops that don&#8217;t have the electronic boards.  In fact there&#8217;s an <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=323501858&#038;mt=8">free iPhone app</a> available, so you can get the data easily on the move.</p>
<p><center><br />
<a href="http://www.flickr.com/photos/lilspikey/4743549060/" title="Brighton Station (Stop B) by lilspikey, on Flickr"><img src="http://farm5.static.flickr.com/4123/4743549060_97a885c3cc.jpg" width="500" height="375" alt="Brighton Station (Stop B)"></a><br />
</center></p>
<p>After playing around with <a href="http://www.psychicorigami.com/2009/07/10/an-iphone-friendly-local-storage-backed-offline-todo-list-webapp/">iPhone javascript apps</a>, I thought it would be interesting to try and create a javascript app for the bus times.  I had some specific ideas about how I wanted the app to work.  I was also keen on trying out some more &#8220;HTML 5&#8243; tech.  Plus I do like things to be (at least in principle) cross-platform, so this has a chance of working ok on <a href="http://www.android.com/">Android</a> phones (though I&#8217;ve not tested it on one).</p>
<p>There are still a few rough edges, but you can try out the app yourself at:</p>
<ul>
<li><a href="http://buses.psychicorigami.com/">http://buses.psychicorigami.com/</a></li>
</ul>
<p>It will prompt you to add a stop.  If you type in the text field, you&#8217;ll get a list of stops that match.  If your browser supports geo-location, you&#8217;ll also see a &#8220;Find nearby&#8221; button, which will list the nearest few stops.</p>
<p>I had the pleasure of demoing this app at the <a href="http://asyncjs.com/showntell/">Async Javascript show&#8217;n'tell</a> last month.  I quickly outlined how it worked, which involves the following:</p>
<ul>
<li><a href="http://developer.apple.com/safari/library/documentation/iphone/conceptual/safarijsdatabaseguide/OfflineApplicationCache/OfflineApplicationCache.html">Offline App Cache</a> &#8211; to make startup quick (key when you don&#8217;t want to miss your bus)</li>
<li><a href="https://developer.mozilla.org/en/dom/storage">Client-side Local Storage</a> &#8211; to record which bus stops you add</li>
<li><a href="http://www.w3.org/TR/geolocation-API/">Geo-location</a> &#8211; so you can find nearby stops</li>
<li><a href="http://jquery.com/">JQuery</a> &#8211; for front end</li>
<li><a href="http://bottle.paws.de/">Bottle.py</a> &#8211; for back end</li>
<li><a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> &#8211; for scraping bus times</li>
</ul>
<h3>Getting the data</h3>
<p>The buses.co.uk site has an API, which I used to scrape all of the bus stops in Brighton.  I chose to scrape the update data from the website itself though, as I couldn&#8217;t get the API to give me the combined services for each stop (so you can see when the next 7 and 81 are coming for example). There are typically two stops for each name &#8211; one either side of the road.  The updates are for both directions, so I actually merged the stops together &#8211; which makes searching easier.</p>
<p>All of the stop data was stored in a single <a href="http://www.sqlite.org/">SQLite</a> database &#8211; mostly for convenience.  The database is used in a read-only method in the actual running app.  I&#8217;m sure I could use something a bit better, particularly when it comes to the distance queries.  Currently, as there are a relatively small number of stops I&#8217;m using a brute force method to find the nearest stops, but I&#8217;m sure with the use of a proper <a href="http://en.wikipedia.org/wiki/Spatial_index">spatial index</a> this could be done a lot more efficiently.  If this was scaled up to work for all stops in the UK, then that would be a necessity.</p>
<h3>Geo-location</h3>
<p>Initially the geo-location was pretty straightforward &#8211; I simply used the <code> getCurrentPosition</code> function and I got a latitude and longitude back.  Testing in Firefox and Safari on the mac gave fairly reasonable results.  However on the iPhone itself I started to notice it wasn&#8217;t very accurate.  Sometimes it was out by several 100 metres, meaning that stops I was standing next to were sometimes not showing up at all!  I had noticed, in the past, that the built-in map app sometimes has a bit of &#8220;lag&#8221; in getting an accurate position.  So I switched to using <code> watchPosition</code> and polling for the position for several seconds.  This worked pretty well, as the initial result would only be vaguely in the right place and then after a few seconds the position would become more accurate and the listing of nearby stops would start to look more sensible.</p>
<h3>Look and feel</h3>
<p>Originally I&#8217;d planned to mimic the look and feel of the iPhone&#8217;s built-in weather app.  The app is built around a similar concept &#8211; you search for bus stops and add them to a list of stops that you can flick through.  I tried to get a nice animated sliding action working, but kept on running into trouble on the device itself.  In Safari and Firefox the animation all worked ok, but I suspect there&#8217;s an issue on the iPhone when you are dragging an area that limits redrawing.  In the end I had to ditch the flip/swipe gesture too &#8211; interfering with the touch events again seemed to cause some rendering issues on occasion.  So instead simply clicking on the left or right of the timetable moves between pages.  It&#8217;s a slightly less complicated way of doing things, so there&#8217;s less that can go wrong really.</p>
<p><center><br />
<a href="http://www.flickr.com/photos/lilspikey/2720488882/" title="Old Brighton No. 5 Bus by lilspikey, on Flickr"><img src="http://farm4.static.flickr.com/3255/2720488882_d425545223.jpg" width="500" height="375" alt="Old Brighton No. 5 Bus"></a><br />
</center></p>
<h3>Deployment</h3>
<p>As this was a nice simple app (on the back-end at least), I decided to take a little time to create a <a href="http://docs.fabfile.org/">Fabric</a> file to control deployment.  The app is hosted on Webfaction, where I have already setup key-based login for ssh.  The app is deployed using <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a> with a daemon process, so that one merely needs to copy over the new code, then &#8220;touch&#8221; the .wsgi file restart the daemon process.  Not exactly tricky to do, but making it a one-button process saves making any mistakes.</p>
<p>To trigger the deployment I run <a href="http://github.com/lilspikey/buses/blob/master/fabfile.py">my fab file</a> like this:</p>
<pre>
<code>
fab --user=lilspikey --hosts=lilspikey.webfactional.com deploy:webapps/buses/app/
</code>
</pre>
<p>I actually have that in a shell script, that isn&#8217;t checked into git, so that the deployment specific username, host name and remote directory aren&#8217;t checked into source control.  If I wasn&#8217;t using key-based login, I&#8217;d need to specify a password and I definitely wouldn&#8217;t want to check that into git!</p>
<h3>Source code</h3>
<p>You can get the source code on github in my <a href="http://github.com/lilspikey/buses">buses repository</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/07/04/iphone-brighton-buses-webappjavascript-front-end/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Chumby to Arduino communication using PySerial</title>
		<link>http://www.psychicorigami.com/2010/06/26/chumby-to-arduino-communication-using-pyserial/</link>
		<comments>http://www.psychicorigami.com/2010/06/26/chumby-to-arduino-communication-using-pyserial/#comments</comments>
		<pubDate>Sat, 26 Jun 2010 20:52:03 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[chumby]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.psychicorigami.com/?p=278</guid>
		<description><![CDATA[So here are a few notes on getting a Chumby to talk to an Arduino using PySerial (and Python). It&#8217;s pretty easy, but I&#8217;ll document it to make it obvious. As the Chumby is sometimes a bit slow with a few of these steps, it&#8217;s good to know it will work in the end. First [...]]]></description>
			<content:encoded><![CDATA[<p>So here are a few notes on getting a <a href="http://www.chumby.com/">Chumby</a> to talk to an <a href="http://www.arduino.cc/">Arduino</a> using <a href="http://pyserial.sourceforge.net/">PySerial</a> (and <a href="http://www.python.org/">Python</a>).  It&#8217;s pretty easy, but I&#8217;ll document it to make it obvious.  As the Chumby is sometimes a bit slow with a few of these steps, it&#8217;s good to know it will work in the end.</p>
<p>First you&#8217;ll want <a href="http://wiki.chumby.com/mediawiki/index.php/Python">Python on the Chumby</a>.  At the time the latest version already compiled for the Chumby is Python 2.6, so it&#8217;s pretty up-to-date.</p>
<p>Once you&#8217;ve got Python installed and on a USB stick you&#8217;ll also want to download PySerial &#8211; I picked the latest version <a href="http://sourceforge.net/projects/pyserial/files/pyserial/2.5-rc2/pyserial-2.5-rc2.tar.gz/download">PySerial-2.5-rc2</a>.</p>
<p>With PySerial expanded and on the USB stick (alongside Python) you&#8217;ll want to put the USB stick in the Chumby and connect to it <a href="http://wiki.chumby.com/mediawiki/index.php/Chumby_tricks#Hidden_screen_in_Control_Panel">via SSH</a>.</p>
<p>Change to the directory for the USB stick (e.g. <code>cd /mnt/usb</code>).</p>
<p>You should see (at least) two directories, one for Python and one for PySerial:</p>
<pre>
<code>
chumby:/mnt/usb-EC5C-3D0A# ls -l
drwxr-xr-x    6 root     root         4096 Jun 26 21:15 pyserial-2.5-rc2
drwxrwxrwx    4 root     root         4096 Jan 10 13:51 python2.6-chumby
</code>
</pre>
<p>You&#8217;re first instinct may be to try and install PySerial via the usual call to <code>python setup.py install</code>.  However this appears not to work.</p>
<p>All is not lost though &#8211; just manually copy the relevant directory (serial) from PySerial to the python site-packages directory, e.g.:</p>
<pre>
<code>
cp -r pyserial-2.5-rc2/serial python2.6-chumby/lib/python2.6/site-packages/
</code>
</pre>
<p>Know to check that&#8217;s worked open a python prompt and try to import the serial library:</p>
<pre>
<code>
chumby:/mnt/usb-EC5C-3D0A# python2.6-chumby/bin/python
Python 2.6.2 (r262:71600, May 23 2009, 22:28:43)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>>
</code>
</pre>
<p>If you don&#8217;t see any errors (as above) then everything has installed ok.</p>
<p>Next step is to try out connecting an Arduino.</p>
<p>So first off you&#8217;ll want to ensure the Arduino has a program that can read from the serial port &#8211; to show that everything is working ok.  In my case I picked my <a href="http://www.psychicorigami.com/2010/05/26/my-first-arduino-project-morse-code/">Morse Code program</a>.  This will read bytes from the serial port and toggle the built-in LED (on pin 13), so it&#8217;s handy for verifying the serial port is working.</p>
<p>So now you have a program loaded on the Arduino, connect it to the Chumby.  The Arduino should get enough power from the Chumby to start up ok.</p>
<p>You need to work out which serial port the Arduino is using on the Chumby.  List the tty&#8217;s in /dev and pick the most likely looking one (should have USB in it&#8217;s name):</p>
<pre>
<code>
chumby:/mnt/usb-EC5C-3D0A# ls /dev/tty*
/dev/tty      /dev/ttyS00   /dev/ttyS02   /dev/ttyS1    /dev/ttyS3
/dev/ttyS0    /dev/ttyS01   /dev/ttyS03   /dev/ttyS2    /dev/ttyUSB0
</code>
</pre>
<p>On my Chumby the serial port was <code>/dev/ttyUSB0</code>.</p>
<p>Now open up a python prompt again and try talking to the Arduino.  You&#8217;ll need to configure the baud-rate of the serial port to match the program on the Chumby.  In my case this was 9600.</p>
<pre>
<code>

chumby:/mnt/usb-EC5C-3D0A# python2.6-chumby/bin/python
Python 2.6.2 (r262:71600, May 23 2009, 22:28:43)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
>>> ser.write('sos')
3
</code>
</pre>
<p>If you are using the same morse code program you should see the LED blink out &#8216;DOT-DOT-DOT DASH-DASH-DASH DOT-DOT-DOT&#8217; &#8211; confirming that the serial port works.</p>
<p>This is really quite handy, as the Chumby is a small low-power Linux server.  Coupled with Python this means it&#8217;s really easy to get any Arduino based project online, without needing a &#8220;normal&#8221; computer constantly running.  Not quite as self-contained as using an <a href="http://www.arduino.cc/en/Main/ArduinoEthernetShield">Ethernet Shield</a>, but the Chumby is fairly small, so it and an Arduino will easily sit on a window ledge (for example).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.psychicorigami.com/2010/06/26/chumby-to-arduino-communication-using-pyserial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

