Logging driving time with Tasker, Toggl and a bluetooth radio

As a dedicated follower of the Church of Cortex, I have been getting into the idea of time tracking. I track my weight and exercise, and tracking how I spend my life seems like a good logical next step. The idea being to figure out how much time I spend doing any given thing, and then reviewing the data will make it easier to improve my life.

One thing I wanted to track is time I spend driving around in my car. I’ve been driving more recently, and I want to know how much so I can plan what my next vehicle will be. Long story short, I’ve figured out a way, and below are the boring technical details.

My desired result was to log the amount of time I spend driving into time tracking service Toggl, as I’m already using that for a few other things and if I can get 100% of my time tracked in one app then so much the better. So I needed to figure out how to do that automatically.

My first thought was that my phone could log this; it connects to my car stereo via bluetooth every time the engine starts. That’s my data input. I couldn’t rely on automation stalwart IFTTT, partly because they don’t support Toggl integration at the moment, and partly because I’ve found their bluetooth and wifi triggers to be fairly unreliable. Nor could I rely on premium automation alternative Zapier, because there’s no way to trigger anything based on a bluetooth connection in Zapier.

Next up was Tasker, an Android automation app that I’ve had for donkeys years. It’s not pretty, and it’s more complicated than I’d like, but it gets things done. Even Tasker didn’t have a Toggl integration, but it does have enough flexibility that I could make use of Toggl’s API. Fortunately, someone else has already done a lot of the dirty work; HHrebus on GitHub has built tasker-toggl, a complete interpretation of Toggl’s API in files you can import into Tasker. I wasn’t able to get his code to work myself, but I learned enough in the process to assemble the below guide.

So, with no further ado: how to start and end a Toggl timer with a tasker profile.

Before you start with any of the complicated bits, you need to prep Toggl to receive your timers. You need your API token, which you can get by clicking your name in the bottom left corner of the web app, then scrolling to the bottom of the Profile Settings menu. Also, you need to link your timers to either a Workspace, a Project, or a Task. The guide below is for a Project, because that makes the most sense here, but you should be able to figure out how to change my steps if you’d rather link to one of the others. I’ve set up a Project called “Driving”. Once you’ve set up your project, you need to get the Project ID number, which annoyingly you cannot get from Toggl’s web UI. So it’s time to make first use of that API token and do the following to firstly get the list of Workspaces, then get the list of Projects associated with that workspace.

curl -v -u 1971800d4d82861d8f2c1651fea4d212:api_token \ #put your api key in here
	-X GET https://www.toggl.com/api/v8/workspaces  #this gets a list of your workspaces

curl -v -u 1971800d4d82861d8f2c1651fea4d212:api_token \ #put your api key in here too
	-X GET https://www.toggl.com/api/v8/workspaces/777/projects #put your project ID here

The second command will list all Projects in that workspace. Copy the ID of the Project you want your timers to track to somewhere safe. I’d recommend saving your Toggl API token into a Tasker global variable, that way you can use it in other places without having to type it out repeatedly. To see your Tasker global variables, hit the menu icon on the top right and then Preferences, and untick “Beginner Mode” in the UI tab. You’ll now see “VARS” as an option next to Profiles, Tasks and Scenes. Go to the VARS tab, hit plus and add a variable called %TOGGL_TOKEN. Press the blank space to the right of your variable and enter your API token.

The only other bit of prep to do is to install RESTask from the Play Store. This is a Tasker plugin that makes interfacing with REST APIs like Toggl’s easier to deal with. Now you’re ready to create your Tasker Tasks.

Originally I tried using the “Start a Time Entry” and “Stop a Time Entry” functions, but this early version often didn’t connect as my phone was dropping out of a wifi network as I drove away. So when my phone connects at the start, I’m only going to log the time to a variable. Then, when the phone disconnects, I log the full time entry in one easily repeatable request.

So my first task, Toggl-driveStart, is a single step; a JavaScriptlet (Plus sign > Code > JavaScriptlet) with the following code:

var d = new Date();
setGlobal("DRIVE_START_STRING", d.toISOString());

All the rest of the settings I left as default. It’s such a basic script that if it comes across any errors then I have more serious problems than the script. All it does is get the current date and time, and saves it, as a text string in the ISO 8601 date format, to a Tasker global variable until we need it when the drive ends.

My second task, Toggl-driveStop, is where the business gets done. The first action is another JavaScriptlet as follows:

var drive_stop_date = new Date();
var drive_stop_string = drive_stop_date.toISOString();
var drive_start_date = new Date(global('DRIVE_START_STRING'));
var_drive_len = (drive_stop_date - drive_start_date) / 1000;
var request_body = '{"time_entry":{"description":"Driving","duration":';
request_body += drive_len;
request_body += ',"start":"';
request_body += global('DRIVE_START_STRING');
request_body += ',"stop":"';
request_body += drive_stop_string;
request_body += '","pid":123456789l,"created_with":"tasker"}}';

To break down the first four lines:

  1. Get the drive stop date and time
  2. Convert the drive stop datetime to the same ISO 8601 format as before
  3. Retrieve the drive start ISO datetime from the global variable and convert it back into a date
  4. Get the duration of the drive in seconds by taking the stop date away from the start date. Then dividing by 1000 because that duration defaults to milliseconds.

I need both dates as ISO strings because Toggl uses those as Start and Stop times. I needed the dates as JavaScript dates to get the duration, which Toggl also requires. Note that Duration doesn’t need to match the exact time between the start and stop time. All the lines after that are building up the request_body variable which is what we’re going to send off to Toggl. Make sure you enter your Project ID after “pid”.

The second action is then a RESTask REST call (Plus sign > Plugin > RESTask). You need to set up the RESTask as follows:

Configuration:

Settings tab

Request Type: Post

Host: https://www.toggl.com/api/v8/time_entries

Basic Auth Username: %TOGGL_TOKEN

Basic Auth Password: api_token

Timeout: 30

Enable custom body: ticked

Custom Body: %request_body

Headers tab

Add one header

Name: Content-Type

Value: application/json

Leave the rest as default, then hit save. The only other thing to do in the RESTask is to tick “Continue Task After Error”. This allows us to plan for a failed connection and keep retrying until it works.

Action 3 is an If (Plus > Task > If”). The condition you want is %rtcode (the RESTask HTTP status code output variable) Doesn’t Equal (NEQ) 200. Basically, if the RESTask isn’t successful.

Action 4 is a Wait (Plus > Task > Wait). I’ve set mine to 30 seconds, but if you’re concerned about constant retries draining your battery you can set this higher.

Action 5 is a Goto (Plus > Task > Goto). The Type is “Action Number”, and you’re pointing it at Action #2, our RESTask.

Action 6 is an End If (Plus > Task > End If).

Action 7 is a Variable Clear (Plus > Variables > Variable Clear) clearing %DRIVE_START_STRING to make sure we don’t end up with some weird situation where your drive start time gets stuck.

That brings us to the end of the tasks. Then you just need to associate them with a profile. Go to the profiles tab, hit plus, and if you’re copying my method of using a BlueTooth connection, then choose State > Net > BT Connected as your trigger. Make sure you put your stereo’s BT name in the Name box, otherwise this will be triggered by every BlueTooth connection. Add Toggl-driveStart as your first task. Then press and hold on Toggl-driveStart until a menu appears letting you Add Exit Task. Hit that and choose your Toggl-driveStop task.

And there you have it. A Tasker task for logging driving stats. it’s not 100% accurate – the BlueTooth stereo takes a good minute or two to get connected to my phone after the engine starts. But it gets pretty close!

Gains

This blog post is late, because I was putting it off. I was putting it off because, despite naming the project SLIMJIM, I’ve put on weight over the last six months. I was hoping for a turnaround that has not come, giving me a positive to write up. That said, I’ve dug into the data and think I’ve found a bright side.

My average weight chart, which looks like someone who can’t keep the weight off

My weight is now hovering around 86KG. It’s been stable there for about two months, after slowly rising from the point at which I last wrote. I chalked this up to not eating right over the summer holidays, then Christmas. But that didn’t feel quite right. Since adopting Tycho the Miniature Schnauzer at the end of October, I’ve been walking a hell of a lot more, 30% more year on year according to my Fitbit activity data. My diet contains more takeaways and pies than this time last year, but I’m still well up on the fruit and veg compared to pre-SLIMJIM. I couldn’t explain it.

The other shoe dropped earlier this week, when the thought crossed my mind that I was seeing “19%” a lot more in the body fat alert on my Fitbit Aria. It has always been an occasional thing as the reading seems to fluctuate quite a bit, but I usually showed 20-21%. I ripped the data out of Fitbit’s webapp and assembled myself a spreadsheet, which always makes me feel better. This one doubly so, as it showed that I’m not getting fatter. The mass I’m gaining must be muscle, I guess? From the walking and the Milo of Croton-style puplifting I’ve been doing.

Fat not exactly rising, everything else on the rise.

On the one hand, this is a big relief. I’m not gaining fat. I’m gaining muscle, which feels like it has to be a positive. But swole was not the goal. My previous weight targets were informed by my assumption that as a fairly normal non-athlete, getting my BMI into the “healthy” window of 69 to 83KG was the right move. Now I’m getting healthier while my BMI is rising back to the middle of the “overweight” category? That doesn’t feel right.

Don’t be fooled by the sleepy look, he’s an excellent calorie-burning assistant

It’s difficult to decide where I should go from here. That lean mass chart doesn’t look like it’s levelling off yet, and as Tycho gets bigger and can handle longer walks I can’t imagine that my activity levels are going to drop as we go into spring. I think I’m going to try and lower my body fat weight (currently around 17KG), and hopefully this will offset my MASSIVE GAINZ.

85.2KG – 20.4% body fat – 25.7 BMI

 

PROJECT SLIMJIM Q3 update

I haven’t blogged in months. Poor effort on my part. Here’s an update to my weight loss rate: it’s begun to abate. In the first month of this year I averaged -1.3KG every week. In the following two months, -0.5KG/week. Today, looking  back over the last three months, I’ve lost a solitary kilogram, based on my weekly average weight.

A chart showing weight loss from 84KG to 83KG.
The line does go in the right direction, so that’s something.

Given that I’m not exactly dieting now, this was probably to be expected. Not that I’ve returned to old eating habits. Avocado on brown toast is the new SI unit of breakfast. Meal Prep Sunday is a lifestyle I’ve tried to join, in an attempt to save cooking time as well as enforce a healthier diet, and that’s been interesting if not entirely successful. Cooking six meals at once is a time saver, but many foods aren’t at their best being cooked, frozen, defrosted and then microwaved. Experimentation continues.

I’m not exactly where I wanted to be. My target for this point was 80KG, which I have missed. But it’s hard to feel too bad, because while this morning I weigh 82.9KG, that’s an unusual peak following a weekend of wedding canapes, contrasting the dramatic trough of 83.0KG I recorded in April and quickly rose back above. That 80KG target will be retained for the next three months, and hopefully in October I’ll be able to report that I’ve hit it. Fingers crossed, eh?

82.9KG – 20.8% body fat – 25.1BMI

 

Continued Adventures in Losing

It’s been 10 weeks since I last blogged about my weight. At that point, I was four weeks in and had dropped my first six or so kilograms. I’d had it surprisingly easy; my average weekly weight (probably the most useful statistic the Fitbit Aria provides) was dropping by an average 1.3 KG a week. Since then, things have been more frustrating. I’m still losing weight, but at a much lower rate than I was before; 0.5 KG (1 and a bit pounds) a week .

I suppose the easy wins couldn’t keep coming. I’d burned off the fat that had only really appeared in the preceding six months. Now I’m working on losing the fat I’ve worn for many years. But it’s coming off, slowly. My methods are much the same as before – I’ve barely touched cheese since Christmas (is this really living?) and white bread has been a similarly rare treat. But I can’t complain too much – part of the reason for the slowdown has been a sudden glut of reasons to go out for a meal.

A chart showing how much weight I've lost.
More wiggling, but a continuing downward trend.

The trigger for this self-congratulatory post was me hitting my next target, 83.1 KG. Not just 12 KG less than the highest weight I recorded, 83.1 KG is the borderline between a “Healthy” BMI and an “Overweight” BMI for someone of my height. Which means if anyone calls me tubso now, I can throw that back in their factually-inaccurate faces. It also means that by the time you read this, I’ll have had my breakfast. Unless it weighed less than 100g (unlikely) I’ll have fallen back into the “Overweight” category, and I have no recourse against anyone calling me a fatty. So, the weight loss must continue for a while yet.

I haven’t yet decided where I want my final weight to be. I’ll be setting my next target as 80 KG, which seems like a nice round figure (which is something I plan not to have lol rofl dietjokes), but after that I don’t know. At some point, I’ll have to do the really difficult thing; stop losing weight, but also not gain it back. Not quite yet, though.

83.0 KG – 21.1% body fat – BMI 25.0

 

Yet More Dell Docking

Dell’s dock didn’t work. The Belkin USB 3.0 hub did. For a while, at least. After a few months of fairly solid performance driving the 2x LG 34UC97 ultrawide monitors using 2x Plugable USB3.0 DP adapters, problems started to appear. One monitor wouldn’t come on.  Or the other wouldn’t come on. Or they’d flicker wildly when actual work was being done. The bosses declared them “unusable” and worked from a meeting room, rather than stare at the pile of failing technology in front of them. Shame upon my family name!

It looks like the issue is the Belkin dock, rather than the Plugable adapters. While these docks are happily pushing twin 1080p monitors elsewhere in the business, it seems that pushing two lots of 3440×1440 monitors is too much for the chipset. I’ve kept them, and at some point I’ll test them out to see if they’re properly wrecked or whether they can enjoy an easy retirement pushing the same twin 1080p as their comrades.

So it was back to online shopping, trying to find something that would do the job. I have to say, the market for USB 3.x docks is moving at a serious pace now. It seems like none of the options I checked out in January were really available six months ago. In the end I settled for the Kensington SD4600P, a dock that advertises as supporting dual 4K, via one DP port and one HDMI port. They’ve been working for nearly two months now with fairly minimal issues; occasionally the XPS15 forgets which monitors go where, but that is quickly solved.

They seem fairly nice units, however there is one thing I will note. Of two installations on the same Dell XPS 15s, one was significantly easier than the other. The easy one was just checking that the video drivers were up to date, and we were away. The other struggled to drive both monitors at the same time until a firmware update was performed. And something in the firmware update had a terrible effect on the laptop’s onboard graphics. The lower half of the screen flickered and froze constantly after the firmware update (which should only have affected the dock!) and nothing I tried would fix it. Eventually the boss needed to go, so I shut it off. When it was turned on the next morning, it was fine. I have no idea what happened there. I had tried turning it off and on again, but it appears the extended power-down was the answer.

Being a loser

As 2016 came to a close, I had a realisation. That realisation was “damn James, you are really fat”. I mean, I’ve always been soft around the edges, and there have been occasional gags about my size, but something in my brain has always gone “yeah, you could lose a bit of weight, it’s not that bad though, there’s plenty fatter than you!”.

That changed, just before New Year. I saw the way my t-shirt hung over my belly and I was actually repulsed. I had to do something about it. First, I bought a Fitbit Aria. The various readouts said one at a time please that at 15 stone I was either nearly obese (BMI 29.1, obese is 30), or actually obese (27.7% body fat, 25% is considered obese).

That was the trigger for me to actually start making changes to my life. To avoid building unnecessary suspense, the things I’ve done are starting to work.

That graph represents my first month of being healthy. You can applaud a bit now. Not too much, I’ve still got a long way to go. But I think I’ve earned a bit of approval. I now weigh less than 89KG (14 stone for imperial scum).

These are the things I have done that I think have probably helped:

  1. Buying the Aria and weighing in every morning (post-wee, pre-breakfast) and every evening (before bed). This A) reminds me that I am being healthy, and B) shows me my weight trend. The trend is far more interesting than any individual weigh-in. You can see a few big spikes in the graph above (representing New Year, a friend’s birthday, and a weekend at my mum’s), but none of those sudden jumps in weight depressed me, because I still had a downward trend. Honestly, the Fitbit has been pretty much the driving force for me not forgetting about my health entirely.
  2. Cooking healthy. I haven’t been starving myself. The BBC Good Food magazine has many good recipes. A few that aren’t on their website have been the most helpful. Specifically, a red pepper prawn curry and rice meal that neither me or Coralie could finish due to the sheer size of the thing, despite how delicious it is.
  3. Abandoning the breakfast of a lifetime. I’m no longer eating marmite on two slices of buttered white toast each day. It’s now an avocado on a slice of brown toast, with some hot sauce.
  4. Not eating all the cake that is omnipresent in our office. Seriously, it’s like someone robbed the Tesco bakery section and stashed it on desks near me. That’s been a real test of self-control.
  5. Not doing more exercise. I know I should, and I have tried a bit, but frankly it’s cold outside and it’s dark when I get home from work, so that will have to wait. This does mean that the weight I’ve lost has been from eating less, which has to be a good start, right?
  6. Dry January. Apart from one night off (many vodkas, drunken kebab) I’ve not had any booze since New Year. This is something I will need to account for starting in February.

Anyway, that’s enough patting myself on the back. I met my Q1 goal in the first month. That means now I have to go on and do more, because I’m not where I want to be yet. I’m not telling you what that final goal is, because I think not banging on about weight loss has helped me lose weight and keep friends, but when I do get there I’ll let you know.

88.6KG – 24.6% body fat – BMI 27.4

The Geek’s Garden Part 5: Climbing the Walls

Pre-apology: I have taken more than two months to complete this post. Please pretend that you’re reading this in late September so you don’t think about how slack I am with consistent blogging.

Before starting this project, I spent far too much time looking at pictures of vertical gardens, trying to discover how they’ve actually been done. This was frustrating, because some are from companies who want you to pay them to build a vertical garden, and the rest are regurgitated images from sources long since lost, talking in vague generalities about how nice green walls are. So, here’s exactly how I created mine.

The finished product.
The finished product.
  • Wall Hogger vertical planters
  • 3 metre, 30-35mm diameter bamboo from ukbamboo.com
  • Stainless steel S-shaped hooks large enough to hook over the bamboo poles
  • Wall mountable hooks. I used these, which are slightly too large. You should use these if you want to learn from my mistakes.
  • Screws to mount the hooks.

That’s all you need. My approach was as follows:

Step 1: Mount the hooks. The bamboo poles are really sturdy, they’ll only need supporting at either end. The hooks I listed are strong enough to support two of the bamboo poles each, so you only need n+1 of the hooks where n is the number of bamboo poles you need to support in a row.

Step 2: Rest the bamboo poles on the hooks. Tie them in place with twine if you want. I did that later.

Step 3: hang the s-shaped hooks off the bamboo. Again, these are strong enough to carry the weight of a pair of wall hoggers, so I’ve gotten away with n+1 hooks for a row of n wall hoggers.

Step 4: hang the wall hoggers off the hooks. Bear in mind that if you’re not instantly ready to plant in them, you will want to weight them down with some stones or something as they are prone to blowing around and falling off when they’re empty.

Another angle
Another angle

That’s it. Your vertical garden space is now ready for planting. So, let’s quickly run through the pros and cons of my incredibly basic approach.

PRO: This approach is really modular. You can scale it up or down depending on how much space you have. Different shaped wall hoggers are available, so you could fit this design in pretty much anywhere.

CON: The s-shaped hooks are prone to sliding along the pole, meaning the wall hoggers don’t hang flat to the fence. I’m mulling over the best solution to this- outdoor-grade elastic bands, maybe?

PRO: This is really easy to construct. Screw the hooks in and the rest is just hanging things in place.

SORT-OF-CON: This probably isn’t the absolute cheapest way of achieving this result. My total cost was about £235 before I even put any plants in. I have seen pictures of approaches that looked cheaper (e.g. using plastic guttering pipe for planters) but there did always seem to be a tradeoff of cost against ease of assembly. A lot of that cost was bamboo, which is incredibly cheap per metre but incurs a high shipping charge as it’s so awkward to move.

NOTE: Normal fences don’t like water. Do not use this design as-is if you have a normal fence. When Tim from Pro Build specced out my fence, he used specially treated timber which will not absorb water. If your fence is not made from this timber, you need to put some kind of water protection between the wall hoggers and the fence, otherwise your fence will get damp and rot incredibly quickly.

The Geek’s Garden Part 4: Getting a man in

When I first started planning to turn our courtyard into something less horrible, I was young and idealistic and wanted to do everything myself. Then I spent hours watching tradesmen assembling fences and pavements on Youtube and realised that there isn’t room in our garden for me to learn by making mistakes. There’s nowhere to hide any errors, so everything has to be done well, first time. So I got a man in.

The finished product
The finished product

Finding tradesmen is a notoriously awful exercise, but Rated People has made that somewhat less painful, and it turned up Tim from Pro Build, who has been outstanding. The whole job was done within three weeks of him quoting on it. The only other guy who got around to quoting was saying he’d not be able to start until October!

Aerial shot
Aerial shot

Now that what I’d think of as the shell has been nicely finished, we can start putting actual garden stuff in. I’ve got a bunch of hardware arriving which I will run through as I start putting things together in the next blog post!

 

The Geek’s Garden Part 3: In which I don’t get my 15 minutes

I haven’t blogged about the Geek’s Garden project for nearly four months now. You might think this means I’ve been slacking. And you’d be mostly right! In my defence, there were extenuating circumstances, and there is now some progress.

Not long after I last blogged. Monty Don tweeted out a call for gardens and their gardeners to feature in the 2016 series of Big Dreams Small Spaces. Getting advice from Britain’s Favourite Gardener™ is not something to be sniffed at, so I applied. And they responded! I was quizzed heavily over the course of a few phone calls, and photos of the courtyard were exchanged. Then they asked me to postpone any work I was planning, on the basis that if they were going to film us, they’d want to show the transformation, which would be very undramatic if the work was halfway done.

That process started in mid April. In mid May, one of the Big Dreams Small Spaces team came out and recorded an audition tape, featuring me and Coralie standing in the garden, talking about our plans, and a few closeups of the mess that was the current state of affairs. The whole thing was quite surreal. I don’t think I’m made for telly. Apparently, neither did the BDSS team as two or three weeks later we got a call that said we weren’t going to be on the show. C’est la vie! I was mostly annoyed because I’d delayed doing any work in the garden by more than six weeks, so I was raring to get started. Then it rained all through June, which is not conducive weather for dragging soil through your house.

I finally restarted the process of extracting all the soil from the back of the garden, but progress was slow until I bought started buying HippoBags. They aren’t what I’d call cheap, but they take up less space than a skip and they’re way more efficient than driving down the tip over and over again in a small car.

DSC_0838
The state of things

 

That brings us up to the current position: most of the old paving slabs are up, the oven is still there but I’ve gotten rid of the copper piping, the spare tyre and nearly all the soil. I’ve had the first handyman round to quote us on re-paving (or decking, I’m really not sure which yet) and building the new fence to support the vertical garden. A lot of work which should have taken a lot less time. Still, lessons have been learned!

 

Aren't they nice? Look at that happy bumbler.
Aren’t they nice? Look at that happy bumbler.

I’ve finally made a decision on what to do with the western wall. I’ll be adding a two-seat arbour, running some trellis either side, and growing a climbing plant up the whole thing. On a visit to Kelmarsh Hall I saw them growing passiflora passion flowers which are lovely, but might not be suitably hardy. Time will tell whether I can get hold of some and keep them alive.

 

 

A Dell Docking Follow-Up

After the unbelievable faff of installing the Dell WD-15 docks, I thought I’d do a little follow up on the working solution I found for connecting a Dell XPS15 to two LG 34UC97 ultrawide monitors.

Unfortunately, the single connector for everything was a no-goer, but I did get everything down to two connections. The power connector is the first, the second is a USB connection to a Belkin USB 3.0 hub which is our standard laptop dock. Plugged into that USB hub are 2x Plugable USB 3.0 to DisplayPort adapters. These aren’t the cheapest, but they are rated for resolutions up to 4K, which covers the ultrawide’s 3440×1440, and they won’t need replacing if the bosses decide that they want to upgrade to 4K.

The solution isn’t as neat as I would have liked, as it leaves only one free USB port on the Belkin hub. Plus, the USB connection means the monitors are powered by the XPS 15’s integrated CPU graphics rather than the discrete Nvidia card, but the result is fine for office work and the odd video.

Only one driver was required for the Belkin dock, and after two weeks they have been been rock solid. Dell, take note.

Update 02/03/2017: this wasn’t the end of it. More here.