Sunday, 28 January 2024
My Apps, 2024
Monday, 23 October 2023
Markdown (and Mermaid) on Blogger in 2023
Sunday, 28 November 2021
Importing/capturing digital video (DV) for FREE on a Mac in 2021
Like many others, I have a giant box of Mini DV video cassettes from 10+ years ago that I fairly-urgently need to get onto a more long-term-safe medium. As it's a pretty tedious job I have tended to do this in batches, when I can be bothered getting all the necessary bits together. Fortunately my trusty 2012 MacBook Pro has Thunderbolt ports that with just a couple of cheap adapters, can connect to the 4-pin Firewire port of my still-functional Panasonic NV-GS27 camcorder and do the job.
But while the hardware is willing, sometimes the software is not. It's all too easy to get on the upgrade treadmill and forget about applications you only use once every couple of years. In the past I used Vidi, which was minimal but $0, and thus excellent. But it won't work on 64-bit MacOS and appears unmaintained so I needed something new.
All I needed was something that could capture the raw data from each cassette and dump it into a .dv file that I can stash away on a hard drive.After a very dismaying tour through Google and YouTube made me think I'd either need to pay for a software package, or kludge something together using libdc1394 (which would be massive overkill) I finally found what I needed by searching Github directly: vrecord by AMIA Open Source.
vrecord works beautifully on my Catalina (OSX 10.15) MacBook Pro - follow the Basic Usage guide and you'll be capturing those precious memories in no time.
Sunday, 13 September 2020
Micro-optimisation #9725: Checkout the mainline
Very soon (October 1, 2020) Github will be making main the default branch of all new repositories instead of master. While you make the transition over to the new naming convention, it's handy to have an abstraction over the top for frequently-issued commands. For me, git checkout master is one of my faves, so much so that I've already aliased it to gcm. Which actually makes this easier - main and master start with the same letter...
Now when I issue the gcm command, it'll check if main exists, and if not, try master and remind me that this repo needs to be migrated. Here's the script
~/bin/checkout-main-or-master.sh:
#!/bin/bash
# Try main, else master and warn about outdated branch name
MAIN_BRANCH=`git branch -l | grep main`
if [[ ! -z ${MAIN_BRANCH} ]]; then
git checkout main
else
echo "No main branch found, using master... please fix this repo!"
git checkout master
fi
I run it using this alias:
alias gcm='~/bin/checkout-main-or-master.sh'
So a typical execution looks like this:
mymac:foo john$ gcm No main branch found, using master... please fix this repo! Switched to branch 'master' Your branch is up to date with 'origin/master'. mymac:foo john$
Monday, 24 August 2020
Micro-optimisation #6587: Git push to Github
I've said it before; sometimes the best automations are the tiny ones that save a few knob-twirls, keystrokes or (as in this case) a drag-copy-paste, each and every day.
It's just a tiny thing, but I like it when a workflow gets streamlined. If you work on a modern Github-hosted codebase with a Pull-Request-based flow, you'll spend more than a few seconds a week looking at this kind of output, which happens the first time you try to git push to a remote that doesn't have your branch:
mymac:foo john$ git push
fatal: The current branch red-text has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin red-text
mymac:foo john$ git push --set-upstream origin red-text
Counting objects: 24, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (16/16), done.
Writing objects: 100% (24/24), 2.79 KiB | 953.00 KiB/s, done.
Total 24 (delta 9), reused 0 (delta 0)
remote: Resolving deltas: 100% (9/9), completed with 9 local objects.
remote:
remote: Create a pull request for 'red-text' on GitHub by visiting:
remote: https://github.com/my-org/foo/pull/new/red-text
remote:
To https://github.com/my-org/foo.git
* [new branch] red-text -> red-text
Branch 'red-text' set up to track remote branch 'red-text' from 'origin'.
The desired workflow is clear and simple:
- Push and set the upstream as suggested
- Grab the suggested PR URL
- Use the Mac open command to launch a new browser window for that URL
#!/bin/bash
# Try and push, catch the suggested action if there is one:
SUGG=`git push --porcelain 2>&1 | grep "git push --set-upstream origin"`
if [[ ! -z ${SUGG} ]]; then
echo "Doing suggested: ${SUGG}"
URL=`${SUGG} --porcelain 2>&1 | grep remote | grep new | grep -o "https.*"`
if [[ ! -z ${URL} ]]; then
echo "Opening URL ${URL}"
open $URL
else
echo "No PR URL found, doing nothing"
fi
fi
I run it using this alias:
alias gpgh='~/bin/push-to-github.sh'
So a typical execution looks like this:
mymac:foo john$ gpgh Doing suggested: git push --set-upstream origin mybranch Opening URL https://github.com/my-org/someproject/pull/new/mybranch mymac:foo john$
Sunday, 17 May 2020
Home Automation In The Small; Part 2
Continuing on the theme of home automation in the small, here's another tiny but pleasing hack that leverages the Chromecast and Yamaha receiver bindings in OpenHAB.
To conclude a happy Spotify listening session, we like to tell the Google Home to "stop the music and turn off the Living Room TV" - "Living Room TV" being the name of the Chromecast attached to HDMI2 of the Yamaha receiver.
While this does stop the music and turn off the television, the amplifier remains powered up. Probably another weird HDMI control thing. It's just a small detail, but power wastage annoys me, so here's the fix.
The trick with this one is ensuring we catch the correct state transition; namely, that the Chromecast's running "app" is the Backdrop and the state is "idling". If those conditions are true, but the amp is still listening to HDMI2, there's obviously nothing else interesting being routed through the amp so it's safe to shut it down. Note that the type of LivingRoomTV_Idling.state is an OnOffType so we don't compare to "ON", it has to be ON (i.e. it's an enumerated value) - some fun Java legacy there ...
rules/chromecast-powerdown.rules
rule "Ensure Yamaha amp turns off when Chromecast does"
when
Item LivingRoomTV_App changed
then
logInfo("RULE.CCP", "Chromecast app: " + LivingRoomTV_App.state)
logInfo("RULE.CCP", "Chromecast idle: " + LivingRoomTV_Idling.state)
logInfo("RULE.CCP", "Yamaha input: " + Yamaha_Input.state )
if (LivingRoomTV_App.state == "Backdrop") {
if (LivingRoomTV_Idling.state == ON) {
if (Yamaha_Input.state == "HDMI2") {
logInfo("RULE.CCP", "Forcing Yamaha to power off")
Yamaha_Power.sendCommand("OFF")
}
}
}
end
Sunday, 26 April 2020
Home Automation In The Small
When you say "Home Automation" to many people they picture some kind of futuristic Iron-Man-esque fully-automatic robot home, but often, the best things are really very small. Tiny optimisations that make things just a little bit nicer - like my "Family Helper" that remembers things for us. It's not for everyone, and it's not going to change the world, but it's been good for us.
In that vein, here's another little optimisation that streamlines out a little annoyance we've had since getting a Google Chromecast Ultra. We love being able to ask the Google Home to play something on Spotify, and with the Chromecast plugged directly into the back of my Yamaha AV receiver via HDMI, it sounds fantastic too. There's just one snag, and fixing it means walking over to the AV receiver and changing the input to HDMI2 ("Chromecast") manually, which (#firstworldproblems) kinda undoes the pleasure of being able to use voice commands.
It comes down to the HDMI CEC protocol, which is how the AV receiver is able to turn on the TV, and how the Chromecast turns on the AV receiver. It's cool, handy, and most of the time it works well. However, when all the involved devices are in standby/idle mode, and a voice command to play music on Spotify is issued, here's what seems to be happening:
| Time | Chromecast | AV receiver | Television |
|---|---|---|---|
| 0 | OFF | OFF | OFF |
| 1 | Woken via network | ||
| 2 | Sends CEC "ON" to AVR | ||
| 3 | Wakes | ||
| 4 | Switches to HDMI2 | ||
| 5 | AV stream starts | ||
| 6 | Detects video | ||
| 7 | Sends CEC "ON" to TV | ||
| 8 | Wakes | ||
| 9 | Routes video to TV | ||
| 10 | "Burps" via analog audio out | ||
| 11 | Hears the burp on AV4 | ||
| 12 | Switches to AV4 |
Yes, my TV (a Sony Bravia from 2009) does NOT have HDMI ARC (Audio Return Channel) which may or may not address this. However, I'm totally happy with this TV (not-"smart" TVs actually seem superior to so-called "smart" TVs in many ways).
The net effect is you get a few seconds of music from the Chromecast, before the accompanying video (i.e. the album art image that the Chromecast Spotify app displays) causes the TV to wake up, which makes the amp change to it, which then silences the music. It's extremely annoying, especially when a small child has requested a song, and they have to semi-randomly twiddle the amp's INPUT knob until they get back to the Chromecast input.
But, using the power of the Chromecast and Yamaha Receiver OpenHAB bindings, and OpenHAB's scripting and transformation abilities, I've been able to "fix" this little issue, such that there is less than a second of interrupted sound in the above scenario.
The approach
The basic approach to solve this issue is:
- When the Chromecast switches to the Spotify app
- Start polling (every second) the Yamaha amp
- If the amp input changes from HDMI2, force it back
- Once 30s has elapsed or the input has been forced back, stop polling
Easy right? Of course, there are some smaller issues along the way that need to be solved, namely:
- The Yamaha amp already has a polling frequency (10 minutes) which should be restored
- There's no way to (easily) change the polling frequency
The solution
Transformation
First of all, we need to write a JavaScript transform function, because in order to change the Yamaha polling frequency, we'll need to download the Item's configuration as JSON, alter it, then upload it back into the Item:
transform/replaceRefreshInterval.js
(function(newRefreshValuePipeJsonString) {
var logger = Java.type("org.slf4j.LoggerFactory").getLogger("rri");
logger.warn("JS got " + newRefreshValuePipeJsonString);
var parts = newRefreshValuePipeJsonString.split('|');
logger.warn("JS parts: " + parts.length);
var newRefreshInterval = parts[0];
logger.warn("JS new refresh interval: " + newRefreshInterval);
var entireJsonString = parts[1];
logger.warn("JS JSON: " + entireJsonString);
var entireThing = JSON.parse(entireJsonString);
var config = entireThing.configuration;
logger.warn("JS config:" + JSON.stringify(config, null, 2));
// Remove the huge and noisy album art thing:
config.albumUrl = "";
config.refreshInterval = newRefreshInterval;
logger.warn("JS modded config:" + JSON.stringify(config, null, 2));
return JSON.stringify(config);
})(input)
Apologies for the verbose logging, but this is a tricky thing to debug. The signature of an OpenHAB JS transform is effectively (string) => string so if you need to get multiple arguments in there, you've got to come up with a string encoding scheme - I've gone with pipe-separation, and more than half of the function is thus spent extracting the args back out again!
Basically this function takes in [new refresh interval in seconds]|[existing Yamaha item config JSON], does the replacement of the necessary field, and returns the new config JSON, ready to be uploaded back to OpenHAB.
Logic
Some preconditions:
- A Chromecast Thing is set up in OpenHAB
- With #appName channel configured as item LivingRoomTV_App
- A Yamaha AVReceiver Thing is set up in OpenHAB
- With (main zone) #power channel configured as item Yamaha_Power and
- (Main zone) #input channel configured as item Yamaha_Input
rules/chromecast.rules
val AMP_THING_TYPE="yamahareceiver:yamahaAV"
val AMP_ID="5f9ec1b3_ed59_1900_4530_00a0dea54f93"
val AMP_THING_ID= AMP_THING_TYPE + ":" + AMP_ID
val AMP_URL = "http://localhost:8080/rest/things/" + AMP_THING_ID
var Timer yamahaWatchTimer = null
rule "Ensure AVR is on HDMI2 when Chromecast starts playing music"
when
Item LivingRoomTV_App changed
then
logInfo("RULE.CCAST", "Chromecast app is: " + LivingRoomTV_App.state)
if(yamahaWatchTimer !== null) {
logInfo("RULE.CCAST", "Yamaha is already being watched - ignoring")
return;
}
if (LivingRoomTV_App.state == "Spotify") {
logInfo("RULE.CCAST", "Forcing Yamaha to power on")
Yamaha_Power.sendCommand("ON")
// Fetch the Yamaha thing's configuration:
var yamahaThingJson = sendHttpGetRequest(AMP_URL)
logInfo("RULE.CCAST", "Existing config is: " + yamahaThingJson)
// Replace the refresh interval field with 1 second:
var newYamahaConfig = transform(
"JS",
"replaceRefreshInterval.js",
"1|" + yamahaThingJson
)
logInfo("RULE.CCAST", "New config is: " + newYamahaConfig)
// PUT it back using things/config:
sendHttpPutRequest(
AMP_URL + "/config",
"application/json",
newYamahaConfig.toString())
logInfo("RULE.CCAST", "Forcing Yamaha to HDMI2")
Yamaha_Input.sendCommand("HDMI2")
logInfo("RULE.CCAST", "Forced Yamaha to HDMI2")
logInfo("RULE.CCAST", "Will now watch the Yamaha for the next 30")
logInfo("RULE.CCAST", "sec & force it back to HDMI2 if it wavers")
val DateTimeType ceasePollingTime = now.plusMillis(30000)
yamahaWatchTimer = createTimer(now, [ |
if(now < ceasePollingTime){
Yamaha_Input.sendCommand("REFRESH")
logInfo("RULE.CCAST", "Yamaha input: " + Yamaha_Input.state)
if (Yamaha_Input.state.toString() != "HDMI2") {
logInfo("RULE.CCAST", "Force PUSH")
Yamaha_Input.sendCommand("HDMI2")
}
yamahaWatchTimer.reschedule(now.plusMillis(1000))
}
else {
logInfo("RULE.CCAST", "Polling time has expired.")
logInfo("RULE.CCAST", "Will not self-schedule again.")
var revertedYamahaConfig = transform(
"JS", "replaceRefreshInterval.js",
"600|" + yamahaThingJson
)
sendHttpPutRequest(
AMP_URL + "/config",
"application/json",
revertedYamahaConfig.toString()
)
logInfo("RULE.CCAST", "Yamaha polling reverted to 10 minutes.")
yamahaWatchTimer = null
}
])
}
end
Some things to note. This uses the "self-triggering-timer" pattern outlined in the OpenHAB community forums, reads the configuration of a Thing using the REST interface as described here, and is written in the XTend dialect which is documented here.
Thursday, 27 February 2020
The Open-Topped Box
I'd always thought that my Preferred Working Arrangement™ was the classic "Developer In A Box" - keep them insulated from all possible sources of "noise", politics or distraction, feed them work to be done (and coffee) and results come out. It turns out that's not quite true. There's actually an even better arrangement; The Open-Topped Box.
I coined the phrase during a one-on-one with my boss; I was praising the way we'd been all working to see what was coming up next, and agreeing on priorities and how best to get maximum return for the lowest effort.
In a company-wide meeting, we'd been shown a 2-dimensional graph plotting (developer) effort versus (overall company) reward, something I'd never seen before (I don't know if it has a formal name or inventor):
You can intuitively see where you'd like every project or feature to sit ...
On the next slide it had been populated with various possible future initiatives marked appropriately; something like this:
The Big Boss then spent a good amount of time explaining his (very astute) reasoning of the potential business value of each proposed feature, and then delegated where necessary to get explanation of the development effort involved. In the end, it made it crystal clear why (to use the example chart above) Project E made the most sense to run with - providing the (equal-) most business value at the (equal-) lowest effort.
Although we were completely free to challenge the placement of anything on the two-dimensional chart, we couldn't fault it, and instead came away feeling both informed and energised for the next development push. So by all means keep your devs in a box; but let them see what's coming down next.
Friday, 22 November 2019
Micro-optimisations
I finally got around to setting up some aliases for git commands that I issue many, many times a day. Can't believe it's taken me this long to do it. I've also placed them in a file in my Dropbox so I'll always be able to add them to any machine I work on regularly.
alias gs="git status" alias gcm="git checkout master" alias gp="git pull" alias gd="git diff" alias gcam="git commit -am"
Although I have a few other oft-used and favourite git commands, namely:
- git push - to push code to the server
- git merge master - to merge the code from master with code on this branch
- git checkout - - to switch to the previously-used branch (analogous to cd -)
This actually harks back to my first ever job as a professional engineer; we were using the mighty and fearsome ClearCase version control system, and I was tempted to shortcut some of the arcane commands required, but my manager (very wisely) cautioned similarly against aliasing away complexity. Don't underestimate the power of repetition for both muscle- and conventional memory!
Sunday, 8 September 2019
I like to watch
Remember how computers were supposed to do the work, so people had time to think?
Do you ever catch yourself operating in a tight loop, something like:
10 Edit file 20 Invoke [some process] on file 30 Read output of [some process] 40 GOTO 10Feels a bit mechanical, no? Annoying having to switch from the text editor to your terminal window, yes?
Let's break down what's actually happening in your meatspace loop*:
10 Edit file in text editor 15 Save file (e.g. Ctrl-S) 17 Change active window to Terminal (e.g. Cmd/Alt+Tab) 20 Press [up-arrow] once to recall the last command 22 Visually confirm it's the expected command 25 Hit [Enter] to execute the command 30 Wait for the command to complete 35 Interpret the output of the command 40 Cmd/Alt+Tab back to the editor 45 GOTO 10That's even more blatant! Most of the work is telling the computer what to do next, even though it's exactly the same as the last iteration.
(*) Props to anyone recognising the BASIC line-numbering reference 😂
Wouldn't something like this be better?
10 Edit file in text editor 15 Save file (e.g. Ctrl-S) 20 Swivel eyeballs to terminal window 30 Wait for the command to complete 35 Interpret the output of the command 40 Swivel eyeballs back to editor 45 GOTO 10
It can be better
If you've got npm on your system somewhere it's as simple as:
$ npm install -g watchand arranging your UI windows suitably. Having multiple monitors is awesome for this. Now by invoking:
$ watch '[processing command with arguments]' dir1 dir2 ... dirNyou have the machine on your side. As soon as you save any file in dir1, dir2 etc, the command will be run for you. Here are some examples:
Validate a CircleCI build configuration
You're editing the circleci/config.yml of a CircleCI continuously-integrated project. These YAML files are notoriously tricky to get right (whitespace matters...🙄) - so you can get the circleci command-line tool to check your work each time you save the file:$ brew install circleci $ watch 'circleci config validate' .circleci
Validate a Terraform configuration
You're working on a Terraform infrastructure-as-code configuration. These .TF files can have complex interrelationships - so you can get the terraform command-line tool to check your work each time you save the file:$ brew install terraform $ watch 'terraform validate' .
Auto-word-count an entire directory of files
You're working on a collection of files that will eventually be collated together into a single document. There's a word-limit applicable to this end result. How about running wc to give you a word-count whenever you save any file in the working directory?:$ watch 'wc -w *.txt' .
Power tip
Sometimes, the command in your watch expression is so quick (and/or its output so terse), you can't tell whether you're seeing the most-recent output. One way of solving this is to prefix the time-of-day to the output - a quick swivel of the eyeballs to the system clock will confirm which execution you're looking at:
$ watch 'echo `date '+%X'` `terraform validate`' .
> Watching .
13:31:59 Success! The configuration is valid.
13:32:23 Success! The configuration is valid.
13:34:41 Success! The configuration is valid.

