Automatic context detection for Taskwarrior

Translations: br
Aug 24, 2020

One of the main ideas of GTD is to have a context associated with each task, so that it is very easy to see which tasks can be done in your current context. I organize my tasks with Taskwarrior, so to make it work with contexts, when adding a new task I need to assign a context to it and also update the current context whenever it changes. There are different types of context, but the easiest to automate are the spatial ones, that is, which tasks I can do where I'm at right now.

Assigning a task to a context is as simple as adding a tag to it. I have three different places I'm normally at, so I either add a @rep, @sp or @uni tag depending on where the task can be done.

To update the current context though I'd need to manually tell Taskwarrior where I'm at right now every time I go to any other place. For example, I'd need to type task context uni every time I went to the university. This is not only very boring but also error-prone: more than once it took me a couple seconds to understand why some tasks were missing.

As any other little problem in life, this can be solved with a little scripting. So that's why I wrote a python script to automatically detect and set the current context for Taskwarrior.

Python script

The idea is very simple: I'm almost always connected to the WiFi, since it connects automatically, and each location has specific WiFi network names, so I just need to get the current WiFi SSID and set the corresponding context.

That is what the following python script does (aside from sending a notification with notify-send):

import subprocess

contexts = {
    'rep': ["rep wifi 1", "rep wifi 2", "rep wifi 3"],
    'sp':  ["sp wifi 1", "sp wifi 2"],
    'uni': ["eduroam"]

def get_context(wifi):
    for context in contexts:
        if wifi in contexts[context]:
            return context
    return None

def get_current_context():
    wifi_cmd =["iwgetid", "-r"], text=True, capture_output=True)
    wifi = wifi_cmd.stdout.split('\n')[0]
    return get_context(wifi)

def set_current_context():
    context = get_current_context()
    if context:["notify-send", "Taskwarrior context",
                       f"Setting context to <b>{context}</b>"])["task", "context", context])
    else:["notify-send", "-u", "critical", "Taskwarrior context",
                       "Failure to detect context"])["task", "context", "none"])

Note: The WiFi names for the rep and sp contexts were redacted to avoid exposure.

Systemd service

Since when I go from one place to the other I always suspend, hibernate or shutdown my notebook, that script only needs to be run after resuming or turning the computer on, which is exactly what the following systemd service is for:

Description=Set taskwarrior context NetworkManager-wait-online.service NetworkManager-wait-online.service

ExecStartPre=/usr/bin/sleep 30


Details about this service file:

  • The network-online and wait-online services supposedly make it wait for NetworkManager to connect to a network before executing, but from my tests that wasn't enough, so I ended up adding a 30 second delay as can be seen in ExecStartPre.
  • The hibernate and suspend targets make it run after the computer resumes or turns on.
  • The DISPLAY, XAUTHORITY and DBUS_SESSION_BUS_ADDRESS environment variables allow the notification to appear.
  • taskwarrior-update_context basically calls set_current_context() from the python script.

And that's it! With those two pieces, after I move between two locations and open my notebook the Taskwarrior context is automatically updated, showing me only the tasks relevant to the place I'm at.

Extra: Previous script

As a side note, before that python script, I made a bash script. Even though running a command in bash is way cleaner than python's, I really despise bash's syntax. I also find it awful to need to define a array_contains function (which I copied from some StackOverflow answer). Anyway, here's the bash script if you're curious:

wifi="$(iwgetid -r)"

declare -a rep=("rep wifi 1" "rep wifi 2" "rep wifi 3")
declare -a sp=("sp wifi 1" "sp wifi 2")
declare -a uni=("eduroam")

array_contains () {
    local array="$1[@]"
    local seeking=$2
    local in=1
    for element in "${!array}"; do
        if [[ $element == $seeking ]]; then
    return $in

array_contains rep "$wifi" && context=rep
array_contains sp "$wifi" && context=sp
array_contains uni "$wifi" && context=uni

if [ -z "$context" ];then
    notify-send -u critical "Taskwarrior context" "Failure to detect context"
    task context none >/dev/null 2>&1
    notify-send "Taskwarrior context" "Setting context to <b>$context</b>"
    task context $context >/dev/null 2>&1