Creating a HomeKit Driveway Sensor

It’s one of the quirks of the house that I live in is that I cannot easily see the end of the driveway from inside the house. This means it’s hard to tell when someone might have arrived, whether expected or unexpected. The Guardline Wireless Driveway Alarm has been a good solution to that problem, as it gives us a nice, loud, BING when its beam is crossed. It’s not perfect — deer and even neighborhood cats occasionally set it off — but I’m happier with it than I was without it.

Having other home automation projects I’ve undertaken using HomeKit (more on that another time), I decided that it would be nice to know if the alarm goes off when I’m not at home. My first inclination was to connect it to a Raspberry Pi, since I have those lying around, and I’ve used them successfully for other home proijects. The Guardline has relay connections, and I wondered if I could wire it up to a Pi and read the change in state from a GPIO pin. Clearly if the answer was no, I wouldn’t be writing this.

It turns out to be fairly simple. I chose to wire the Normal Closed contact to a pin on the Pi (GPIO board pin 37), the sensor pin and the common to a ground pin.

Guardline relay contacts wired to Raspberry pi

From there I could detect events on the sensor pin:

def motion_detected(pin):
    print("Motion detected!")

sensor_pin = 37

GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(
    self.sensor_pin,
    GPIO.BOTH,
    callback=motion_detected
)

Once I knew that I was getting state change, I built a simple HomeKit accessory using HAP-Python:

import logging

import RPi.GPIO as GPIO

from pyhap.accessory import Accessory
from pyhap.const import CATEGORY_SENSOR


logger = logging.getLogger(__name__)


class GPIOSensor(Accessory):

    category = CATEGORY_SENSOR

    def __init__(self, *args, sensor_pin=3, **kwargs):
        super().__init__(*args, **kwargs)

        self.sensor_pin = int(sensor_pin)

        logger.debug('Setting up GPIO input')
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(self.sensor_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(
            self.sensor_pin,
            GPIO.BOTH,
            callback=self.__motion_detected
        )
        logger.debug('Subscribed GPIO events')

        serv_sensor = self.add_preload_service('MotionSensor')
        self.char_detected = serv_sensor.configure_char('MotionDetected')

    def __motion_detected(self, pin):
        logger.debug('Motion detected')
        sensor_state = GPIO.input(pin)
        self.char_detected.set_value(sensor_state)

    def stop(self):
        super().stop()
        GPIO.cleanup()

Which was easy enough to then run using the HAP-Python example. Once it’s set up in HomeKit, I get handy notifications like this:

HomeKit driveway sensor notification

Reading List for a Nuclear Crisis

My brief recommended reading list for a nuclear crisis, in order:

  1. The Making of the Atomic Bomb, by Richard Rhodes
  2. Hiroshima, by John Henessy
  3. One Minute to Midnight, by Michael Dobbs
  4. Essence of Decision: Explaining the Cuban Missile Crisis, by Graham Allison and Philip Zelikow
  5. Nagasaki: Life After Nuclear War, by Susan Southard

My also-brief recommended reading list for North Korea, in no particular order:

Ostracization

I’m finally reading through the Supreme Court’s Town of Greece, NY v. Galloway ruling, and it’s a dismaying and infuriating combination of disdain and ignorance toward non-Christians and atheists.

Should nonbelievers choose to exit the room during a prayer they find distasteful, their absence will not stand out as disrespectful or even noteworthy. And should they remain, their quiet acquiescence will not, in light of our traditions, be interpreted as an agreement with the words or ideas expressed. Neither choice represents an unconstitutional imposition as to mature adults, who “presumably” are “not readily susceptible to religious indoctrination or peer pressure.” Marsh, 463 U. S., at 7921

Clearly Justice Kennedy has never actually refused to bow his head during a prayer, much less left a room. He thinks that self-ostracization is a perfectly acceptable solution.

There are two very different sensations I’ve personally experienced during public prayers. First there’s the pronounced internal feeling of exclusion: everyone around me is participating in a ritual that I am not a part of, that I cannot be a part of because I simply cannot believe. I cannot accept the fundamental basis for the ritual. Second is the shrinking sensation when people around me notice that I haven’t participated.

Now, most of the time I’ve experienced this have been in situations I’ve had the option not to place myself in, where I had full awareness that there would likely be prayer (my experience has been Christian and Jewish). It was my choice to get a degree from a private college with a Catholic history, which had a prayer at the commencement ceremony that I was under no obligation to attend, for example.

However, if there is prayer at public, government functions that I must attend if I wish to exercise my democratic rights… that’s another matter altogether. Justice Kennedy, with the help of Justices Roberts, Alito, Thomas, and Scalia, has gutted the first two clauses of the First Amendment, condoning the ostracization of nonbelievers while insultingly suggesting self-ostracization as the solution.

Weaponization

For as long as I can remember my dad has had a wood shop and made odds and ends for family, friends, extended acquaintances, and the like. In Real Life™ he’s a pharmacist, but when he got home most evenings he would tinker around in the garage. I have in my house a stool and a toy chest he made for my kids, a trash can, and two cabinets he made for his sister and mother from glass and wood that came from his father’s pharmacy. He is like my great grandfather in this way. I have a grandfather clock and coffee table that my great grandfather made for my grandfather.

My childhood was spent in that environment… every Xmas my dad would make something out of wood to give to all our family, friends, neighbors, etc. It started off as ducks, a different style of duck every year. And the designs were his (and my mom’s). It was something that he created, from concept to final product, to give as a gift. It’s a process I’ve always admired, and frequently tried (and failed, I rush to add) to replicate. It’s not that something I have his talent for… in the physical world that is.

I presently write software for a living, and do so as a hobby as well. To a large degree I view the process as similar to that of my dad’s — the process of creating. I enjoy creating for my own edification, as well as to solve problems for others. It helps make my day job writing healthcare-related software rewarding, and gives it meaning. I’m not simply a code-monkey.

For me, programming is akin to a craft. I get enormous pleasure out of well-designed and elegantly written code (though I readily admit I’ve written plenty that isn’t). I am not, if you’ll humor the political science graduate student in me, alienated from the product my labor. I don’t think there has been a comparable collection of abstractions suitable for expressing the creative freedom that high-level software development offers us.


As children we have our parents, teachers, and various other adults reassure us that everybody makes mistakes from time to time. Some mistakes are worse than others, to be sure. In my dad’s woodcraft, mistakes become increasingly difficult to correct as a piece nears completion. But mistakes can also give a particular piece character, and make it unique. The mistake becomes a way to remind us that it was a human endeavor. To err, as Pope tell us, is human; as a work becomes art they can become sublime.

There is no comparable analogy to software development. Mistakes are colloquially known as “bugs.” They’re not usually thought of in so gentle a terms as “mistake” either — they’re failures. They are the chair that collapses entirely when you sit on it. They can take the form of errors in math, logic, or memory usage. They can be stupidly simple or complex, one-in-a-million cases. But no matter what, they are failures. They are failures precisely because they cause our functional expectations not to be met. That expectation could fail because software simply “crashes,” or it could put your data at risk by corrupting it or by allowing someone else to read it.

No programmer wants to be responsible for bugs, big or small, but all of us — every last one — have been. The advantage we have is that we can fix them, and compared to concrete creative activities, we can do it with relative ease. That is the real power of the abstractions atop which we work: their mutability. Of course, there are design processes that can help to eliminate bugs — NASA’s software design is famous and fastidious — but they work through the process of review. It’s not that the bugs aren’t necessarily introduced, it’s that they’re caught. Bugs can only be fixed if they’re caught… and if the person or persons who can fix them are informed.


The consequences I’m considering when I write code are the functionality for the user (who is often me — a lot of software I write is because I have a niche to fill) and the user’s data. Sometimes I am responsible for the transmission of user data across the Internet, and I leave what I can up to third-party software that is designed to keep it secure, and what I can’t I ensure I follow best-practices, test, and have the code reviewed. As far as I’m aware, I’ve never personally introduced a bug that put user data at risk of being stolen (which is what it is — theft). But as I mentioned above, all programmers are responsible for introducing some bugs somewhere.

President Obama has decided that when the National Security Agency discovers major flaws in Internet security, it should — in most circumstances — reveal them to assure that they will be fixed, rather than keep mum so that the flaws can be used in espionage or cyberattacks, senior administration officials said Saturday.

But Mr. Obama carved a broad exception for “a clear national security or law enforcement need,” the officials said, a loophole that is likely to allow the N.S.A. to continue to exploit security flaws both to crack encryption on the Internet and to design cyberweapons.1

The idea that it’s possible that a mistake I make — a bug I introduce — could put user data at risk is not a pleasant one. The idea that someone would exploit that bug without informing me that they’ve discovered it is even worse. The idea that governments (which potentially have passive access to networks) could do so is worst still. But the idea that my own government would do so rather than informing me of the flaw is truly the worst. And they’re conceptualizing it as a weapon.

I expect autocratic and totalitarian governments (Russia and China are quoted in the article) to behave like… well, autocratic and totalitarian governments. I do not expect my democratic (in theory) government, based on the rule of law, to behave like an autocratic or totalitarian government. One of the key features of totalitarianism is its ability to turn all facets of life into weapons to use against its people — that’s what makes it “total,” the mundane everyday experience of life is coopted by the state to further state power.


Not surprisingly, officials at the N.S.A. and at its military partner, the United States Cyber Command, warned that giving up the capability to exploit undisclosed vulnerabilities would amount to “unilateral disarmament” — a phrase taken from the battles over whether and how far to cut America’s nuclear arsenal.

“We don’t eliminate nuclear weapons until the Russians do,” one senior intelligence official said recently. “You are not going to see the Chinese give up on ‘zero days’ just because we do.“1

Richard Rhodes’s The Making of the Atomic Bomb makes painfully obvious that, from the beginning, physicists had some understanding of the devastatingly destructive power that a nuclear weapon could have. Shortly after the discovery of fission:

Fermi was standing at his panoramic office window high in the physics tower looking down the gray winter length of Manhattan Island, its streets alive as always with vendors and taxis and crowds. He cupped his hands as if he were holding a ball. “A little bomb like that,” he said simply, for once not lightly mocking, “and it would all disappear.”2

There were still unknowns, and most were shocked at the horrible magnificence of the Trinity test, to say nothing of the actual bombings of Japan. But they were under no illusions as to where their work would take them. Indeed, Niels Bohr saw the ultimate geopolitical outcome.

When nuclear weapons spread to other countries, as they certainly would, no one would be able any longer to win. A spasm of mutual destruction would be possible. But not war.3

Strategic nuclear weapons then can only be defensive in nature. A state possesses them to ensure that nuclear weapons are not used against that state. We don’t eliminate our nuclear weapons because that will remove the assurance that another state won’t use nuclear weapons on us. The value of possessing nuclear weapons, in other words, is that they remove the value of another state’s possession of nuclear weapons.

But software vulnerabilities aren’t the same as nuclear weapons. If an exploitable bug goes unreported in the quoted scenario, Russia, China, and the US are free to exploit it at will once they’ve discovered it. Reporting it and fixing it, however, removes the value of exploiting the bug for everyone, and improves the software for users. The nuclear analogy only works when it is inverted — the value for a given state of discovering an exploitable bug is that, by fixing it, you can remove its value for another state. Particularly when you’re considering software developed by citizens of the same state.


Technology and computers have incredible potential to radically change and simplify our lives; they frequently fail to live up to that potential, but it is there. It doesn’t have to create social revolution either, it can be fairly mundane. I recently experienced what I’d call technological bliss when using a piece of software called BackyardEOS to capture astrophotographs. The software was a pleasure to use, and it elevated the experience for me — which is what software should do.

This is a very personal essay because I take this very personally. The article in the New York Times that I’ve quoted from above filled me with both anger and despair. I’ve been working through both for the past couple of days, and this essay is an attempt to understand why. I would prefer any bugs discovered in any of my software to be reported to me, of course. But it’s more than that.

I don’t like the idea of mistakes I’ve made being weaponized. And it is clear from the direct quotes in that article that the NSA and Obama Administration view exploitable bugs in exactly this way: as weapons. I don’t set out to create weapons, I set out to create tools (usually for myself) that will make life just that tiny bit easier. Weaponization is a violent assault on a major part of my self-identity.

The nuclear weapons analogy makes the anger worse. The developers of nuclear weapons knew they were working on a weapon. There was also cutting-edge physics involved, but it was a weapons project with the end goal being a weapon that they were well aware would level a city.

I realize that my view of software as a “craft” might be considered naïve. I mean, afterall, software is the essential machinery of modern global capitalism — but in a way, that’s the point. As the book Flash Boys demonstrates, even in the context of the center of the global financial system, creative software development still requires human skill, human trial and error, and human ingenuity. It requires human craftmanship.

1

David Sanger, “Obama Lets N.S.A. Exploit Some Internet Flaws, Officials Say,” New York Times, April 12, 2014. 2: Richard Rhodes, “Chapter 9: An Extensive Burst”, in The Making of the Atomic Bomb (New York: Simon & Schuster, 2012). 3: Rhodes, “Chapter 17: The Evils of This Time”, in The Making of the Atomic Bomb.

Just Because You're Paranoid...

In his interview with Charlie Rose, President Obama is quoted saying:

…They’ll say … when you start looking at metadata, even if you don’t know the names, you can match it up … and you can yield all this information. All of that is true, except for the fact that for the government, under the program right now, to do that it would be illegal. We would not be allowed to do that.

Of course, telephone and internet metadata are useless to intelligence or law enforcement, that’s why their acquisitioncollection is (or, was) such a zealously guarded secret and why the reaction to their collection being made public was so ferocious. I mean, who wouldn’t be outraged at the revelation of a secret mass surveillance program of absolutely no intelligence value?

Telephone metadata is useless, as German politician Malte Spitz has demonstrated:

Malte Spitz’s telephone metadata

No useful information there at all. Your recurring travel habits, both everyday and out of the ordinary, are of no value, obviously. And that’s before you get to who and when you called and how long you talked.

And neither is your email metadata:

Jacob Goldstine’s email metadata

And it hardly matters that this information will be retained “not in perpetuity”. It wouldn’t be useful in the future, of course, even if the government has a reason to use it.

This is assuming — since Obama made the distinction between what is legal and what is illegal — everything about the program is legal. And we have no need to doubt that, do we?

I have created an eBook, in ePub format, of the United Nations’s Universal Declaration of Human Rights. Hopefully it can be useful as a reference to have handy. It includes both the full declaration as well as summaries of each of the articles.

  • Download UDHR.epub
  • Last Modified: March 29, 2013
  • For: Any ePub 3-capable eReaders (iBooks, Nook, Kobo)

The Orphaned Children of War

On the Natural History of Destruction, by W G Sebald.

Very few writers could approach this book’s subject matter and deliver such a powerful, methodical damnation of a generation. W G Sebald asks a simple question in the first essay: how is it that the near-total destruction of Germany by allied bombing in World War II has been so completely ignored by the survivors, and particularly by German culture and writers?

Although he never calls it by this term, the core of Sebald’s anger is directed at the moral relativism that is used to justify evading the topic: German crimes during the war were so horrible (and they were) that the wanton destruction of the entire nation was justified. Sebald is angry that the experience of living through such atrocities was so thoroughly repressed by the survivors that the memory was not passed on the future generations. Instead there seems to have been a near-unanimous cultural suicide. Sebald describes growing up feeling as if a secret were being kept from him, like a part of his identity as a German was being denied. It was an Etch-A-Sketch end to the past, without context or meaning.

Although Sebald doesn’t really mention it (his critique is aimed directly at the German people), American and British writers have had the moral courage to broach the subject, and it has given us fantastic and disturbing books like Slaughterhouse-5. These help us to center our moral compasses; we can recoil in horror at the firebombing of Dresden (and Tokyo) while fully maintaining our outrage at the Holocaust. The morality of the atomic bombings of Hiroshima and Nagasaki is still a heated subject for debate today.

It is this that Sebald finds lacking in German culture, and, in the remaining essays, he singles out writers who contributed to this collective evasion. It is not, as one so often sees it referred to, amnesia. Sebald is quietly, methodically angry, and his prose has never been better than it is in these essays.

Minima Moralia, by Theodor Adorno

I have created an eBook, in ePub format, of Theodor Adorno’s magnificent, haunting book, Minima Moralia, using the Creative Commons-licensed translation by Dennis Redmond.

This relatively small book (as Critical Theory texts go) consists of aphorisms, written during Adorno’s exile from Naziism and his return to post-World War II Germany. This form is especially well-suited to Adorno’s critique of the paradoxes, illusions, and alienation that constitutes modern civilization — a critique centered on culture. Most disturbingly, Adorno, in many of these aphorisms, connects aspects of modern society to the rise of totalitarianism. He does this with an unrivaled lucidity and skill for distillation of complex notions and observation — an abilitiy to, as Orwell phrased it, face unpleasant facts.

  • Download MinimaMoralia.epub
  • Last Modified: December 12, 2012
  • For: Any ePub 3-capable eReaders (iBooks, Nook, Kobo)

I have been disapointed by the formatting of the Gutenberg edition of Ulysses for some time now. It lacks chapter breaks, so the only navigation points are the three parts of the book. It makes it hard to pick out a favorite episode to read. There is also inconsistent emphasis, capitalization, margins, spacing, etc.

Therefore, I have created an ePub 2/3 edition of Ulysses that reproduces, as closely as I can digitally, the textual formatting and layout of the Orchises Press facsimile of the original Shakespeare and Company edition. It can be downloaded here.

I set out to make the most software-agnostic edition I could, first creating an ePub 3 file as close to spec as I was able, then adding support for ePub 2 readers. The Calibre reader and the latest version of iBooks display the formatting more or less as intended. The latest version of the Nook software reader does a decent enough job but does not preserve uppercase capitalization. The only dedicated eReader I have access to is a first-generation Nook, and it is consistent with the Nook software reader. The file can be converted to Mobi, using Calibre, for reading on the Kindle. A quick test of the Kindle software reader is decent — there are some issues with indentation. I do not know how it would look on a Kindle.

Anyway, this is, as Ulysses has always been, a work in progress. It was not my intention to make any changes to the text, so any errors that existed in the already-digital text are still there. I hope my humble, hand-crafted effort brings some enjoyment this Bloomsday.

  • Download Ulysses.epub
  • Last Modified: June 16, 2012
  • For: Any ePub 3-capable eReaders (iBooks, Nook, Kobo)

Sterilizing Human Rights in Europe

Today I encountered a campaign to end Sweden’s sterilization requirement for transgender individuals to have their preferred gender recognized (complete with poignant video). I would urge everyone, particularly anyone reading from Sweden or Europe, to sign the petition. I did a bit more digging, and found this astonishing paper from the Council of Europe.

Some countries require surgery leading to sterilisation before they legally recognise the new gender. It should be stressed that this requirement would also apply in the absence of a medical necessity or the applicant’s wish for such surgery.

Map of European Laws on Sterilization

That doesn’t include divorce and medical requirements for recognition and name change.

I would write more but I would have to pick my jaw up off of the keyboard. Forced sterilization is the sort of thing one associates with the darker days of European and American history.

Forced sterilization by the state has no place in the twenty-first century. Anywhere. For any reason. It’s an outrage to human dignity regardless of gender.