Announcing Direach, a new WordPress theme aimed at readers

As I was discussing on the last episode of Worst Case Scenario, I’m a bit of a luddite when it comes to the web. I like reading, and I dislike anything that distracts me from that task. Fortunately the Safari web browser comes with a great Reader mode which strips all the cruft from a page and simply displays the text of the main article, nicely formatted for reading (Firefox has this feature too). I use it constantly.

I decided a few years ago that I wanted my own website to be as readable as the special Reader mode in my browser. Every four months or so I would check to see if anyone had created a WordPress theme that could do the job, but I was never able to find anything suitable. So I wrote my own!

Direach (from díreach in Irish, meaning direct) is the fruit of my efforts, and it is the theme running on this site today. It is my effort to create a WordPress theme that is reader-friendly and accessible.

Typography

Direach doesn’t download a custom font, it uses the Georgia typeface which is a serif font with a relatively large x-height. Created by Matthew Carter for Microsoft specifically for screen use, it is the same font used by Safari’s Reader mode and is installed on the vast majority of computers, phones and tablets. A default serif font is declared for operating systems that do not ship with this font. The default paragraph font on most browsers will render at 18px, increasing to 20px on wider screens. Elements that are not part of the main body of the page have a reduced font size.

Reduced clutter

Almost all WordPress sites have a header at the top containing the site title, subtitle, and the navigation menu. This can take up a large proportion of the screen, especially if the reader is on a mobile device. Direach shifts this content down to the bottom of the article when it is only showing a single post or page. For index pages and the home page, this content is placed at the top. All content is displayed in a single column, apart from two columns of ‘widgets’ at the bottom of the front page. On single item pages/posts, the site title is appended to the article heading.

Small and fast

Not only does Direach not load any external fonts, it doesn’t add any JavaScript either. The markup is relatively clean. Even on my fairly slow US-based shared host, it loads relatively quickly.

Accessibility

Direach is based on the Underscores base theme by Automattic, and so it has excellent support for screen readers.

Future developments

Direach is licenced as GPL v2 or later and the source is available on GitHub. There are a few issues I still need to address – the image in the masthead does not deliver a retina size for devices with high-density screens, despite poking around in the source of get_header_image_tag I couldn’t find a way to get it to emit srcset attributes, despite this functionality being added in version 4.4.0. I’m not 100% happy with the final design and there are still a few rough edges.

I may submit this theme to wordpress.org in the future after a bit of dog fooding, although I think the design may break one or two of WordPress’s theme guidelines.

Reflections

It took quite a bit of work getting Direach to this state, in particular to get the theme working with some of the weird cases in the WordPress test data set. At various stages I worried whether this theme is too stark – almost Brutalist in nature. I also worry that it gives this site a slightly-too-authoritative tone. But overall I’m happy with the results.

Installing

To install this theme on your own site, go to Direach’s home on GitHub and under Clone or Download choose Download ZIP (your browser may automatically decompress the theme, in which case you will have to recompress it). Upload this theme to your WordPress install via Appearance > Themes > Add New > Upload Theme. You can upload a custom image beside the site title under the Appearance tab of the admin interface.

Three podcasters fix a WordPress plugin bug (with chat logs)

On Worst Case Scenario, the podcast I host with Baz Taylor and Dave Sims, we use a WordPress plugin called Seriously Simple Podcasting to host our podcast feed. It’s a fantastic minimalist plugin with little bloat and works very well for us.

We also installed an add-on called Seriously Simple Stats which would give us download counts for each episode of the podcast.

However the plugin wasn’t showing the client information properly and this was annoying Dave.

Screen Shot 2016-07-20 at 20.12.17
The three of us poked at it at various points during the day, and despite not being WordPress experts (and in my case, being very far from a PHP expert), we managed to get it working.

Screen Shot 2016-07-20 at 19.49.28

Podcast app User agent Strings

Here are some user agent strings reported by one or two podcast apps:

  • “AppleCoreMedia/1.0.0.13F69 (iPhone; U; CPU OS 9_3_2 like Mac OS X; en_ie)” – native iOS podcast app, amongst other things
  • “Pocket Casts” a podcast app that is particularly popular on Android
  • “Overcast/1.0 Podcast Sync (x subscribers; feed-id=y; +http://overcast.fm/)” – from Marco Arment’s Overcast app, which helpfully tells you how many subscribers you have in the agent string
  • “iTunes/12.4.2 (Macintosh; OS X 10.11.5) AppleWebKit/601.6.17” – downloads from the Mac version of iTunes

Here’s the bit of the plugin that detects what client you’re using

if ( stripos( 'itunes', $user_agent ) !== false ) {

$referrer = 'itunes';

Hm. There was no entry for AppleCoreMediaPlayer, which was why downloads from the native podcast app were being detected as ‘Other’. But we tried downloading episodes from iTunes on the Mac and that was still recorded as Other.

In fact, apart from plays from the website, every client was being recorded as ‘Other’ – except for Pocket Casts. What was going on?

Screen Shot 2016-07-20 at 19.44.03When your needle and your haystack are the same size

Screen Shot 2016-07-20 at 19.46.40The stripos($haystack, $needle) function in PHP looks to see if a string $needle is in the string $haystack, if it is, it returns an integer with the position of $needle in $haystack, otherwise it returns false.

Absentmindedly, I typed ‘php’ in a mac terminal expecting to get an error, but instead getting a blank prompt, indicating I could type PHP code enclosed in <?php ?> and hit ctrl-D to make it run (why does OS X ship with PHP? I have no idea). I tried a smaller test case:

Screen Shot 2016-07-20 at 19.51.22

Those of you reading probably have the aha! moment by now, but it took a bit of probing from Baz before I got it:

Screen Shot 2016-07-20 at 19.52.53

And that was also the reason why Pocket Casts was showing up correctly – because the entirety of the user agent string is “Pocket Casts”!  Anyhow, changing the function around to read

if ( stripos( $user_agent , 'itunes' ) !== false ) {

$referrer = 'itunes';
and adding AppleCoreMedia to the list got everything working fine. Well almost.

Double hits from the iOS podcasts app

We then hit another problem:

Screen Shot 2016-07-20 at 19.57.11

Turns out any downloads from the iOS Podcasts app were being counted twice. It seems like Podcasts first sends a HEAD request for the mp3 file, presumably to get size information so it can populate the progress indicator, with the user agent “Podcasts/2.4”. The app then sends a normal GET request for the mp3 file with the AppleCoreMedia user agent mentioned earlier.

Screen Shot 2016-07-20 at 20.01.55

Being lazy I just added a return statement if we detected the Podcasts user agent:

if(stripos( $user_agent,'podcasts/' ) !== false ) {
 			return;
 		}

I submitted it as a pull request and the maintainer merged it within a few hours. It was fun chatting away with Baz and Dave on iMessage while we tried to fix it.

We need to stop this nonsense about teaching coding in primary school

Today there was a story in the Irish Times, headlined ‘Bruton wants lessons in coding for primary school pupils’, announcing that the Irish Minister for Education, Richard Bruton, was considering the introduction of programming into the national curriculum for primary schools.

I’m passionate about programming. I run a software company. I program in my spare time, for fun. I co-organised a hackathon in Limerick  with the sole purpose of programming for fun with other people for an entire day.  I am a host on a podcast with two other programmers where we talk about, among other things, programming. I’ve also spent some time teaching maths and science in secondary school. And I am convinced that the idea of teaching primary school children to program during the school day is nonsense.

The assertion by tech companies that they can’t find programmers is a myth

The Irish Times articles cites lobbying by some tech companies that they can’t find good people. This is a complete myth, a combination of (a) tech companies not wanting to pay programmers decent wages (b) tech companies being really bad at recruitment and (c) tech companies not being willing to take graduates on and help them develop appropriate modern programming skills. I recruited a graduate developer two years ago for my company Reg Point of Sale, and I came across countless IT graduates who still couldn’t find a job six months after graduating, because all the job adverts were looking for 2 years experience. If tech companies would spend their own money investing in people, rather than whining at the government to spend our money, they wouldn’t have a problem.

It’s also worth noting that even if the plaintive cries about a skills shortage from the tech industry were true, it’s not clear how teaching a bunch of eight year-olds how to write for loops would help.

Teaching programming would require a huge continued capital investment

Compulsory programming on the primary school curriculum would be incredibly expensive.  I’m sure some of these tech companies are salivating at the prospect of juicy hardware, software and support contracts, involving proprietary solutions that will obsolete quickly.

We will be teaching skills that will be obsolete by the time these kids graduate

Take the average ten year-old in primary school: the twelve years that will pass before this kid graduates from college is an aeon away in tech terms – especially in programming languages. The concept that a primary school kid could learn skills now that would be useful to the tech industry in twelve years time is not consistent with the rapid change associated with tech and programming.

We could actually end up with less people in tech

Consider a child who has a natural aptitude for problem solving and logical thinking that suggests they might enjoy programming. But what if the teacher doesn’t have a strong grasp of the material, or the myriad of other reasons why a young child might not have a good experience learning a difficult technical craft like programming. Suddenly this child gets it into their head that ‘programming is hard’ or ‘not for them’, even though if they had been exposed to it at a later age, they might have found some of the joy that some of us derive from programming.

We do need investment in primary education, but in things that are useful to a child’s development

If the Minister for Education has some spare cash burning a hole in his pocket, it’s not as if other priorities don’t exist – for example investing in teaching core literacy and numeracy in primary school which has only marginally improved in 35 years, or doing something to attacking the unconscionable difference in education outcomes for kids from poorer backgrounds compared to those from more comfortable backgrounds.

Programming is great and you should try it right now!

Adults have infinitely more problems that can be solved by simple computer programs than children do. So why don’t you pick up Learn Python the Hard Way, and if you get through that, start on Automate the Boring Stuff with Python. If you’re lucky you’ll experience an enormous thrill as the computer starts to do your bidding. Maybe the Minister himself might try his hand at a few if statements while considering whether to foist this stuff on our nation’s children.

I think programming is a great thing to learn. Just not for all primary school kids during the school day. I hope the Minister reconsiders his plan.

Irish Population change 2006-2016 by area

The preliminary Census 2016 results were released today. Exciting times for data nerds like me!

The CSO published changes showing population changes since the last census, showing that the population had grown everywhere in the country apart from small decreases in Mayo, Sligo and Donegal of -0.2%, -0.1% and -1.5% respectively. I thought it would be more interesting to look at population changes over two census periods, i.e. 2006-2016.

The table below shows population change in each area between 2006 and 2016. Limerick City was the only area to show a decrease, with the population changing by -2.5% compared to a national increase of 12.2%.

Table and CSV file link below. Note that the Limerick City boundaries correspond to the historical (pre-local authority merger) boundaries of the city, but includes the addition of the Limerick North Rural electoral division.

 

2006 2011 2016 Ch 06-16 %ch
Carlow 50349 54612 56875 6526 13.0%
Dublin City 506211 527612 553165 46954 9.3%
Dún Laoghaire-Rathdown 194038 206261 217274 23236 12.0%
Fingal 239992 273991 296214 56222 23.4%
South Dublin 246935 265205 278749 31814 12.9%
Kildare 186335 210312 222130 35795 19.2%
Kilkenny 87558 95419 99118 11560 13.2%
Laois 67059 80559 84732 17673 26.4%
Longford 34391 39000 40810 6419 18.7%
Louth 111267 122897 128375 17108 15.4%
Meath 162831 184135 194942 32111 19.7%
Offaly 70868 76687 78003 7135 10.1%
Westmeath 79346 86164 88396 9050 11.4%
Wexford 131749 145320 149605 17856 13.6%
Wicklow 126194 136640 142332 16138 12.8%
Clare 110950 117196 118627 7677 6.9%
Cork City 119418 119230 125622 6204 5.2%
Cork County 361877 399802 416574 54697 15.1%
Kerry 139835 145502 147554 7719 5.5%
Limerick City 59790 57106 58319 -1471 -2.5%
Limerick County 124265 134703 136856 12591 10.1%
North Tipperary 66023 70322 71370 5347 8.1%
South Tipperary 83221 88432 89071 5850 7.0%
Waterford City 45748 46732 48369 2621 5.7%
Waterford County 62213 67063 68032 5819 9.4%
Galway City 72414 75529 79504 7090 9.8%
Galway County 159256 175124 179048 19792 12.4%
Leitrim 28950 31798 31972 3022 10.4%
Mayo 123839 130638 130425 6586 5.3%
Roscommon 58768 64065 64436 5668 9.6%
Sligo 60894 65393 65357 4463 7.3%
Cavan 64003 73183 76092 12089 18.9%
Donegal 147264 161137 158755 11491 7.8%
Monaghan 55997 60483 61273 5276 9.4%
State 4239848 4588252 4757976 518128 12.2%

CSV file link

 

Supercalifragilis-HibernoCaledonia

HibernoCaledoniaLike others, I’ve spent the last week in shock over the UK’s vote to leave the EU. I was born and raised in Ireland but my parents are British, and I have lots family and friends over the water. I was just so gutted and saddened when the Leave result was announced early in the morning. In fact the next day I drove over to South Wales to exhibit my Reg point of sale app. Staying for a few days in a part of the UK knowing that the majority of people around me wanted to Leave was just depressing.

Over the last few days, Scottish First Minister Nicola Sturgeon has been making brave attempts to ‘keep Scotland in the EU’ – but even if there was another independence referendum, it’s difficult to see how Scotland can Remain. Spain will always veto any attempt to admit what they would view as a ‘sub-nation’ to the EU because of concerns about Catalonia’s independence ambitions. Meanwhile over in Ireland we are worried about an uncertain future.

But for those of you in these isles who are full of despondency: don’t worry. I have a plan.

(Your post-Brexit despondency will be lifted if you sing along with the headings. Trust me.)

A country that’s part-British but without the xenophobia

What if Ireland formed a union with Northern Ireland and Scotland, which would then enjoy continued membership of the EU by inheriting Ireland’s seat? We could be one nation together, with significantly devolved powers as currently exist in the Stormont, Holyrood administrations, complemented by a new devolved administration for Dublin. We’d have to have a new federal parliament for HibernoCaledonia, probably in Belfast.

With one stroke we could solve the political status of Northern Ireland. Unionists would not be smothered by a perfidious South intent on dismantling their culture. Nationalists would see a ‘nation once again’, just with an extra bit added on.

If we joined together we’d be bigger than Bulgaria

Population of the Republic of Ireland: 4.6m
Population of Northern Ireland: 1.8m
Population of Scotland: 5.3m

Total population of HibernoCaledonia: 11.7m

HibernoCaledonia would have a GDP of over $567bn, making us the 35th largest economy in the world by that measure. We would be the headquarters of some impressive international companies such as Ryanair and Royal Bank of Scotland, and the new country would be able to challenge for significant inward investment.  We would be the pro-European powerhouse of North-Western Europe, showing the world that internationalism and tolerance is still alive and well in these isles.

Supercalifragilis-HibernoCaledonia!

I know it sounds like a joke but I’m deadly serious. Our three countries face an immense threat with the prospect of Brexit. In our own ways, we would all benefit from the more pluralistic administration that a union would bring. It would put to bed once and for all the Northern Ireland question, which otherwise will continually threaten the peaceful future of the province. The Remain side were right, we are Stronger In. Let’s join our hands and work for a shared European future.

The Curious Tale of Limerick Marketing Company

IMG_2557Limerick Council announced recently that it had promoted its Communications Officer to be Head of Marketing, a pretty un-noteworthy story even by the sleepy standards of local news in a small city.

Yet the appointment marks the end of a sorry tale of money wasted, opportunities missed and the continuing damaging culture of secrecy that pervades Limerick Council.

One of the unintended consequences of Fine Gael’s commitment in 2011 to consolidate some state bodies was that it left a number of people with lucrative permanent public sector jobs needing to be redeployed. Part of Limerick Council’s response was to set up a number of companies (why the separate companies were needed was never explained: was it to support salary increases outside of the public sector pay freeze? I suspect we will never know), including the Limerick Marketing Company, which was launched with great fanfare and an announcement that the company would double visitor numbers in five years. The company’s two employees came from state agencies that were affected by Enda Kenny’s putsch on quangos.

This ‘company’ never published any details about its staff or its activities beyond a pretty bland statement of objectives on the Council’s website. Two and a half years later, due to restructuring in staff in the council, the need for the company has gone and the idea has been quietly forgotten (and presumably, the objective to double visitor numbers has died with it).

It’s difficult to criticise the marketing of Limerick that has taken place over the last three years because frankly there wasn’t that much of it. Sure there were a few articles in the local papers, which I’m sure provided gratification for the individuals involved, but there was very little national or international coverage, and so in the absence of any other evidence it seems like the objective of Limerick Marketing Company was “Let’s tell ourselves how great Limerick is, and we’ll hope someone outside the city notices”.

One of two flagship events of the Limerick Marketing Company was Riverfest, an event rightly criticised by Brian Leddin last year as an event that “reflects a city as sophisticated as a Supermacs outlet on a Saturday night”, and that was “lame and mediocre”. Brian’s full article is worth a read as he also highlights the inward looking approach to marketing our city.

The second event was acknowledged locally to be a complete disaster. The marketing company spent half of its annual budget underwriting a “rugby world club sevens” event, and a five-year contract was signed with a private company to underwrite this event. The Limerick Leader reported that the turnout was “paltry”, with only 300 people attending one of the events in Thomond Park, and a total subsidy of €200 for every ticket sold from the public purse.  The Leader termed Limerick Marketing Company’s justification for the event to be “self-serving drivel” – strong words for a local newspaper that is normally very supportive of local events.

The new marketing company was stitched in to the fifteen year socio-economic plan for Limerick (the “Limerick 2030 Plan”) – with nineteen specific actions assigned to it. Even though the marketing section of the 2030 plan was perhaps one of the weakest sections of the document (I described it as being “pretty terrible” in my submission to the plan), at least it published some initial steps that the Limerick Marketing Company could take. Out of nineteen actions I cannot find any evidence that any of them were completed, even though all actions were due to have been completed by the time the company ceased operations.

The one positive initiative that the Limerick Marketing Company was involved in was the ‘street ambassador programme’ that ran over the summer months. This wasn’t an initiative of the Company – it merely inherited responsibility for it. Once the company inherited the responsibility, it promptly scrapped the programme.

In fact there is no evidence that the company ever traded at all. The most recent returns of Limerick City & County Marketing Limited were made in April 2016, where the accounts showed no activity beyond the issuing of a share capital of €2. It was reported recently that the board of the company hasn’t met in the last two years.

It didn’t need to be like this. Between promoting a culture of openness, creativity, debate and vibrance; and targeting specific visitor niches where we can compete effectively; we really could have doubled visitor numbers in five years. Instead it feels like we will continue talking to ourselves, and the promises will continue to be forgotten.

Five reasons why you should buy my old post office van

1. The most patriotic vehicle you could buy

IMG_2518It’s 2016. One hundred years ago a bunch of lads took over a post office and announced to the world our nation’s great destiny. It is your patriotic duty to commemorate these great men and women and what better way to do it than drive around in a green post office van. As Pearse wrote “there are many things more horrible than bloodshed, and not owning a van is one of them”. Commemorate the historic anniversary of the minor disruption to our postal services with the Renault Kangoo Tiocfaidh Ár Lá Centenary Edition today, together with its unique 2016 numberplate. Never forget the sacrifice of our forefathers.

2. Profit from the great gay conspiracy to destroy Irish family values

DSCF6730
Remember last year when the gays got together and mounted a well-funded campaign to undermine traditional Irish Family Values? This is your chance to benefit from some of the trillions of euro that were pumped into this country to destroy marriage, which would have remained secret but for the courageous work of Breda O’Brien. Obviously I can’t detail the secret investments that were made into this van as part of The Great Liberal Conspiracy To Force Sodomy On The Good Irish People but trust me, the gays don’t do things by halves.

3. A bold fashion statement

IMG_2519Pre-distressed clothes are so in right now. Why should your van be any different? To ensure you retain that edgy look as you drive, and to echo the edgy tones of Greg Lauren’s Spring 2016 ready-to-wear collection as breathlessly described by Vogue Magazine, I have performed some scratch detailing on left hand side of the van so you can convey a contemporary aura to the world. Sneer at the rest of the drones with their boringly unblemished means of transport as you cruise around in this fabulous example of hand-crafted pret à porter.

4. You’re not buying a van, you’re buying freedom

In the great tradition of car marketing, here’s a photo of the van in the wilds of Kerry.
DSCF6646
Don’t you feel wild and dangerous after looking at that photo? Don’t you agree that owning this van will make you more attractive to whichever gender(s) you fancy? You’re special, you’re unique, you need this van.

5. Apparently I need an odd number of paragraphs if this is to go viral

155,000km, full Renault service history, taxed till December, tested till January. Selling because we need a 3-seater van now Sheila’s dad lives with us. I’m spectacularly bad at negotiating so you can probably buy it for a lot less than it’s worth.  Live the dream, buy my van.

Identifying Irish addresses by county

My friend Emmet called me with an interesting problem today. He had a spreadsheet with 28k rows. One of the columns was an address, sort of separated by commas. The address column was very inconsistent. Some ended in Ireland, others just had the county name, some used the form “County Limerick”, others “Co. Limerick”, and others still just “Limerick”. He needed to do some calculations by county so he needed to extract the county name for each row. As I learned doing the pubs research, Irish addresses are a pain!

I’d dealt with this sort of problem before (not with 28k rows mind!) when I used to work for national charities and it used to bug me terribly.

Emmet found a way to anonymise the data so he could send me a subset. I had a play around with a spreadsheet-based solution before breaking out the Python for a quick hack.

The script below reads in a file called “input.csv” and writes to a file called “output.csv” with the same data, but with the county name and a comma added to the start of each line (or Unknown if the script couldn’t work it out).

The script is case-insensitive, and matches the rightmost county on each line, so an address in Omeath, Co. Louth is correctly identified as being in Louth, and Dublin Rd., Athlone, Co. Westmeath matches Westmeath, not Dublin.

The script is fairly flexible about the structure of the input file, so the address data can be in different columns, or all in one.

Here’s the script:

###Usage: python parse-csv.py###
###Input file must be called input.csv###


#function definition: input_text is a string, all_ireland is a bool
def prepend_address_with_county(input_text,all_ireland):
    #prepare the county list
    counties_list = ['Carlow','Cavan','Clare','Cork','Donegal','Dublin','Galway','Kerry','Kildare','Kilkenny','Laois','Leitrim','Limerick','Longford','Louth','Mayo','Meath','Monaghan','Offaly','Roscommon','Sligo','Tipperary','Waterford','Westmeath','Wexford','Wicklow']
    #add on the six counties if we want all-Ireland
    if all_ireland == True:
        counties_list.extend(['Antrim','Armagh','Derry','Down','Fermanagh','Tyrone'])
    outfile = ''
    errorcount = 0
    linecount = 0
    #loop over each line
    for line in input_text:
        linecount += 1
        #keep track of the county we're going to feed in
        county_match = ''
        #let's keep track of the index of what we have found, we want the rightmost match
        old_find_index = 0
        #loop over all counties
        for county in counties_list:
            #look for the county, starting from the RHS
            # also convert to uppercase first
            find_index = line.upper().rfind(county.upper())
            #have we found anything? (find_index will be -1 if we haven't found anything)
            if find_index > old_find_index:
                #keep the county match
                county_match = county
                #update the rightmost index count
                old_find_index = find_index
        #have we got any matches?
        if old_find_index != 0:
            outfile += county_match+","+line
        else:
            outfile += "Unknown,"+line
            errorcount += 1
    return {"output":outfile,"errors":errorcount,"lines":linecount}




file = open("input.csv" ,'rU')
output_csv = open("output.csv",'w')
result_dict = prepend_address_with_county(file,True)
percentage_error = 100*result_dict["errors"]/result_dict["lines"]
print "%d lines processed, %d Unknown counties (%.2f%%)" % (result_dict["lines"], result_dict["errors"],percentage_error)
output_csv.write(result_dict["output"])

Escape to the pub with a Raspberry Pi, a pressure mat and push notifications

My father-in-law moved in with us two weeks ago. He is a lovely kind man in his late eighties and it’s a pleasure having him around.

He has Alzheimer’s and needs someone around him all the time during the day. We’re managing this OK while juggling the needs of the business. Unfortunately he can sometimes wake up in the middle of the night in a state of anxiety because he doesn’t know where he is.  This means that Sheila and I can’t get out to the local for a quick pint even after he’s gone to bed.

The mat of freedom, with the white cable on the top left going in to our bedroom
The mat of freedom, with the white cable on the top left going in to our bedroom

Enter the lazy programmer…

There’s nothing like the prospect of a pint to stir the motivations of a hacker!  I had a Raspberry Pi lying around the house. I’d been looking for an excuse to mess around with push notifications on the iPhone for a while, and I thought I could rig something up that would send a push notification to our phones if he left his bedroom during the night.

Internet of things mats

The pressure mat
The pressure mat

Our local electronics retailer Maplin sells a pressure mat – it’s a simple switch designed to be placed under a doormat. Hooking this up to a GPIO pin on the Pi would allow me to send a notification to our phones using Apple’s Push Notification Service. Here’s the general flow:

Pressure mat -> Raspberry Pi -> Apple Servers -> our phones

Not the most complicated of hacks by any means, but if it was going to allow us to get out for a pint it would be worth it.

Setting up the Pi

The Raspberry Pi beside the bed, with wires from the pressure mat connected to GND and GPIO pin 18 via an old telephone cable
The Raspberry Pi beside our bed, with wires from the pressure mat outside the door connected to GND and GPIO pin 18 via an old telephone cable

I bought the Pi two years ago with the aim of doing a bit of tinkering over Christmas, before realising that, although the Pi is an amazing platform at an amazing price, it’s still a Linux box and I didn’t want to be tinkering with .conf files to get things working over my Christmas holidays. But I’d been feeling vaguely guilty that this credit-card sized wonder was sitting gathering dust while kids a quarter of my age around the world were using it to achieve amazing things.

I downloaded the Raspbian Linux distribution from the Raspberry Pi website – choosing the Raspbian Jessie Lite distribution as I didn’t need any graphical niceties. I was hoping I could just boot up the Pi and get its IP address from the local network but ping 255.255.255.255 didn’t show anything up and my Apple AirPort Extreme router, although rock solid and wonderful in many ways, doesn’t show a list of ethernet clients, so I had to hook up a HDMI cable to finish the setup. Setting a static IP was a bit of a pain as the network stack changed significantly last year and most of the links I found had outdated information, but there’s a very comprehensive thread on StackExchange which explains what you need to do to dhcpd.conf (note to self, recent distros include a zeroconf implementation so you should be able to do something like ssh pi@rasbperrypi.local and it should get you in to a Pi with a fresh OS install)

Processing a push notification with an iOS device

This was actually the easiest bit of the whole process. Apple’s docs on push notifications are really good.

Here’s the entirety of the code of the iOS app, pretty much taken verbatim from Apple’s example code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // bitwise OR to include all notification types
    UIUserNotificationType types = (UIUserNotificationType) (UIUserNotificationTypeBadge |
                                                             UIUserNotificationTypeSound | UIUserNotificationTypeAlert);
    //register these notification types
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    // Register for remote notifications -- this will prompt the user to allow notifications
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    return YES;
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //triggered when user allows notifications
    //Log the token
    NSLog(@"device token: %@",deviceToken);
    // Also store the token in NSUserDefaults
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:deviceToken forKey:@"deviceToken"];
    [defaults synchronize];
}

I wrote the device token to NSUserDefaults in case I wanted to display it in the app, but I took the lazy way out and just printed it with an NSLog statement, so I could copy it into my Python script.

Sending a push notification with a Python script

Here’s my Python script that detects someone stepping on to the mat, and which sends a request to Apple’s APNS server:

import RPi.GPIO as GPIO
import time
import datetime
import socket
from apns import APNs, Frame, Payload

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# our pressure mat is connected to GPIO pin 18
button = 18

# setup the pin as input, and enable the pullup resister
# this means when the switch is pressed, it will read GND, i.e. False
GPIO.setup(button, GPIO.IN, GPIO.PUD_UP)

# insert the tokens you NSLogged from your iOS app here - long lines of hex
token_hex = ''
sheila_token = ''
# setting the payload here - we just want the default sound, and we don't care
# what the badge says so we'll just set it to 1 each time
payload = Payload(alert="Joe is on the move!", sound="default", badge=1)

# run in an infinite loop
while True:
    # if switch is pressed (reading False - see note on GPIO.setup() above)
    if GPIO.input(button) == False:
        #logging for debugging
        print str(datetime.datetime.now()), "button pressed"
        #create the push notification object
        apns = APNs(use_sandbox=True, cert_file='push-notification-cert.pem', key_file='push-notification-key.pem')
        time.sleep(1)
        # wrapping this in a try/except block as the script was occasionally
        # barfing on a socket error
        try:
            apns.gateway_server.send_notification(sheila_token, payload)
        except socket.error, (value, message):
            print str(datetime.datetime.now()),"Socket Error", message
            #recreate the apns object
            apns = APNs(use_sandbox=True, cert_file='push-notification-cert.pem', key_file='push-notification-key.pem')
        time.sleep(1)
        #we're done with Sheila's phone, now let's do the same for mine
        try:
            apns.gateway_server.send_notification(token_hex, payload)
        except socket.error, (value, message):
            print str(datetime.datetime.now()),"Socket Error", message
        time.sleep(10)

Apple recently changed their push notification protocol to a brand new version, which I tried to connect to using a Python HTTP/2 library called Hyper – it’s labelled as a ‘very early alpha’ and it may work very well but after a few hours of trying to create the HTTP/2 request I was still getting errors so I used a library that uses the old protocol called PyAPNS which worked fine although I had to insert a few sleep() statements to avoid some socket errors.  I also had to do some fandangling with the push notification certificate, splitting up the .p12 file into a certificate and key in Keychain Access to use with the script.

My Linux skills are a bit rusty so it took a while to remember to type screen then <CTRL-A> d to detach a separate terminal which would run even after I logged out of the SSH session.

It works!

Notification on my phone's lock screen when the mat is stepped on
Notification on my phone’s lock screen when the mat is stepped on

For all the ugly hacking, it seems to work! Sheila and I can nip down for a quick pint to our local knowing that we can quickly return home if her dad starts wandering.

Further work

I spliced in an old telephone cable to connect the pressure mat outside the door with the Raspberry Pi beside my bed. I was in a rush so I used sellotape! Aside from tidying that up into something a little less ugly, here’s the things I’d like to do next with the project

  1. Replace the Raspberry Pi with something like an ESP8266 module that could run off a battery, so I don’t need trailing wires. This post from Stavros Korokithakis shows how he recreated an Amazon Dash button using an ESP8266 looks promising.
  2. Using the ESP8266 would mean that I would have to handle the push notification logic on an external server, so that the ESP8266 would send a HTTP request to a Flask server which would send the request to Apple.
  3. Having the logic on the server means that I could log the data to a database, which means we could track how often the night interruptions were happening.
  4. which reminds me I should enter some logic so that the script only does push notifications and logging at night, sometimes when we’re going in and out of his room to do washing our phones go crazy!

Limerick City candidates answer my questions

I posted a list of all the candidates running in Limerick City, together with a list of questions. Only three candidates responded: James Gaffney, Jan O’Sullivan and Michael Noonan. Here are their answers.

James Gaffney, Green Party

1. How seriously should we take climate change, and what specific policy measures do you think we should take to combat climate change? I’m particularly interested in measures you think that might slow economic growth in the short term but which would have long-term positive effects for our country.

We are the first generation to feel the effects of Climate Change, and the last who can do anything meaningful about it.

The need to address long-term problems, such as climate change, is an overarching value of the Green Party. We support the enactment of national legislation to respond to climate change and transition to a low-carbon, climate-resilient economy. This will reduce our over-dependence on imported sources of fossil fuel energy. Global events related to extreme weather, such as storms and droughts, could compromise our food security and lead to increased immigration into Ireland by ‘climate refugees’.

By 2050, Ireland’s power, heat and transport systems should no longer rely on fossil fuels and our agricultural system should achieve carbon neutrality. This is technologically possible, and would result in greater employment, energy efficiency, security, an improved economy, and improved public health, in addition to contributing to a healthier climate
We need to establish ambitious but realistic binding national greenhouse gas emission reduction targets for 2030 and aim for 100% decarbonisation of the power system and an 80% overall reduction in national emissions by 2050

You mention measures that might slow economic growth in the short-term, however I believe that an Irish economy that is carbon-neutral will be a stronger one. The €5.7 billion a year that we spend on fossil fuels could be kept in our economy rather than going to oil-producing nations. We will also gain a competitive advantage from moving faster than other nations on climate change.

2. Our regional towns and cities are suffering. Here in Limerick we’ve seen our city as well as the villages in our county undermined by ribbon-development and one-off housing in the countryside. How do you think we should balance people’s desires to build where they want, with the need for better planning that avoids sprawl and strengthens our villages, towns and cities?

We need a National Spatial Plan with climate change as a foundation stone.  Any plan that relies on fossil fuels as the driver of an economy will see us falling behind, as the rest of the world switches to a cleaner renewable future. Any plan that thinks Ireland can set the course of our own destiny without an appreciation of global trends is fraught with risk.

In my manifesto I talk about the need for a Regional Authority which would have responsibility for leading on a spatial plan for the Mid-West that would focus on Limerick City as a destination for families and businesses.

The only plan that can succeed is a truly long term one.

Our new national plan puts proper spatial planning at its core. Where we think ahead and plan our public infrastructure so that people from all over Ireland can live and work where there are services and communities. Where we focus on what we can do best at home – in tourism, agri-food, energy, manufacturing and new digital services; where we restore the traditional values of banking to every part of the country so we support sustainable, well paid jobs.
Ours is an investment plan for the next generation.

This election debate is about much more than the fiscal space. It is about the public space.
Whoever is in power in the next Dáil will put resources into the areas that they value. So that’s the question people need to ask of themselves and of politicians as we near polling day.

3. Do you agree with tougher sentencing for criminals, or more rehabilitation? I’m particularly interested in your position on how we should approach drug addiction within the justice system.

We need an after prison support system, with one agency coordinating fully integrated supports for accommodation, education, employment.

We should increase crime preventative measures, e.g. increasing the age limit for the application of the Garda Youth Diversion to 18-24 year olds.

On drug addiction, I feel strongly that this is a medical issue, not a criminal justice issue.

Jan O’Sullivan, Labour Party

1. How seriously should we take climate change, and what specific policy measures do you think we should take to combat climate change? I’m particularly interested in measures you think that might slow economic growth in the short term but which would have long-term positive effects for our country.

I think climate change is one of the most serious issues facing the global population today. During my time as Minister for Trade and Overseas Development Aid I saw at first hand the damage it visits on some of the poorest communities on the planet. I was also proud to work with NGOs and Departmental officials to ensure that tackling climate change had a central role in our Overseas Development Aid policy.

Of course climate change is not just an issue that effects the developing world. Long-term analysis of data demonstrates that our climate is warming with all that this entails, including rising sea levels.

I fully support the climate change legislation that was passed (with all-party support) in the Oireachtas last December. The statutory frameworks established by that legislation (including five yearly national mitigation plans and five yearly national adaptation frameworks) will provide a clear roadmap on what we need to do to reduce greenhouse gas emissions and also the steps we need to take to plan for a changing climate.

The legislation will also establish the Climate Change Advisory Council on a statutory basis.
In relation to economic growth I don’t think the issue actually revolves around the rate of economic growth. I think that all activity needs to be sustainable and that smart, green solutions can ensure that economic growth and job creation can go hand-in-hand with good environmental practices.

2. Our regional towns and cities are suffering. Here in Limerick we’ve seen our city as well as the villages in our county undermined by ribbon-development and one-off housing in the countryside. How do you think we should balance people’s desires to build where they want, with the need for better planning that avoids sprawl and strengthens our villages, towns and cities?

The points you raise are very valid. Poor planning decisions can blight a community for decades, even generations.

Planning and development needs to be driven by a long-term vision for a community – not just the demands of one particular sector.

As a former Minister for Housing and Planning I think my track record shows I deliver on these principles.

I oversaw a process that dezoned land which could have accommodated more than 500,000 houses. This was done to limit urban sprawl and to ensure that future development is concentrated in our towns and villages.

Also, in my first nine months as Minister I used my powers under Section 31 of the Planning and Development Act on three occasions to overturn decisions contrary to good planning. The specific issues involved zoning for development on flood plains, in areas isolated from towns and zoning that threatened wildlife habitats. In the 10 years before I took office this power was only used eight times.

I also dedicated a significant amount of time and energy to tackling the legacy of unfinished housing developments across the country, a process that has resulted in a 75% reduction in the number of these estates over the past five years.

In my opinion that Development Plan is the most powerful tool to ensure proper planning and development. New planning legislation which is in the pipeline will establish a planning regulator which I fully support. In addition to its investigative functions the regulator will have an education role which I think is vital. At local authority level and in our communities we need to have the knowledge and tools to make locally-based, informed decisions about plans that will impact on our community for decades.

3. Do you agree with tougher sentencing for criminals, or more rehabilitation? I’m particularly interested in your position on how we should approach drug addiction within the justice system.

 

I support judicial discretion in sentencing. While sometimes this can be frustrating I acknowledge that judges hear all the facts of a case during trial and post-conviction details and I think that they are best placed to decide on the length of sentence.

I also fully support acknowledging the medical as well as the criminal aspect of addiction and that this needs to be tackled if individuals and communities are to get relief from the tragedy that alcohol and drug addiction can inflict.

In that regard I have supported my colleague Minister Aodhan O’Riordain’s efforts to establish safe facilities for those who are addicted to drugs where they can also come in contact with services that can assist them.

Michael Noonan, Fine Gael

1. How seriously should we take climate change, and what specific policy measures do you think we should take to combat climate change? I’m particularly interested in measures you think that might slow economic growth in the short term but which would have long-term positive effects for our country.

2. Our regional towns and cities are suffering. Here in Limerick we’ve seen our city as well as the villages in our county undermined by ribbon-development and one-off housing in the countryside. How do you think we should balance people’s desires to build where they want, with the need for better planning that avoids sprawl and strengthens our villages, towns and cities?

3. Do you agree with tougher sentencing for criminals, or more rehabilitation? I’m particularly interested in your position on how we should approach drug addiction within the justice system.

I attach a copy of the Fine Gael Election Manifesto which I trust clarifies the matters you have raised in your correspondence.