Some Bits: Nelson's log

11 posts in October 2021

A simple systemd unit file

I wrote my first systemd unit file today. It’s a thing that runs code to import stats from Starlink’s GRPC into InfluxDB using this Python code. Nothing remarkable about this but it’s the first time I’ve ever used systemd like this.

[Unit]
Description=Starlink GRPC monitor
After=influxdb.service
StartLimitIntervalSec=5
StartLimitBurst=5

[Service]
User=nelson
ExecStart=/usr/local/src/starlink-grpc-tools/collect.sh
Restart=always

[Install]
WantedBy=multi-user.target

OK, the remarkable thing is Restart=always. I was having trouble with the script crashing after running a long time. OTOH it turns out it was crashing because Starlink’s protocol changed and the code had to be updated; no number of restarts would fix that. That’s what those StartLimits are for; if it fails to start 5 times in 5 seconds then systemd gives up trying.

Also I’m naughty and run this as myself, not some dedicated system user.

Hugo theme from scratch: the absolute minimum

Update 2023: see Eric Murphy’s take on a starter theme.

In this post I build up an absolutely minimum working Hugo theme for my blog based on the files generated by hugo new theme. The result isn’t a blog I’d publish, but it’s a useful start in understanding how Hugo works.

I’m still wrestling with learning Hugo. Clearly the simple thing is to use someone else’s theme. But I need something custom and specific and also I want to understand what Hugo is doing. So I’m making my own. It’s slow going. There’s no great examples to crib from (all the “minimal blog” themes I could find are elaborate things that include lots of styling and extra features.)

One useful resources is the lookup order page buried deep in the Hugo docs. It explains the basics of how theme template files are used. The best part is where it says “The examples below look long and complex.” Yes, yes they do. But then it also then tells you that in fact there’s 4 templates that are most important: baseof.html,. list.html, single.html, and index.html. Most of my notes here are going to focus on those files.

One useful thing to know about is partial templates. These are HTML snippets intended to be included in other HTML templates. They’re kind of like subroutines, but for templates.

I’m going to follow this tutorial on creating a Hugo theme. It adds some extra stuff (some partial templates for inclusion, CSS, Javascript, a menu) but at its core are those 4 files listed above. I’m going to skip the parts I don’t want and document what happens along the way.

This whole process started with Hugo’s quickstart. I did that first and got my blog working with someone else’s theme. Then I removed the other themes I was using and created my own.

Content

I’ve seeded my blog with a bunch of content (1771 posts) in directories like content/weblog/tech/good/ and content/weblog/politics/. I’ve tested this content works OK with other people’s themes. My blog has several top level directories: politics, tech, culture, etc. For simplicity I put all these directories not directly under content/ but in a single subdirectory (weblog/). This results in a /weblog/ in the URL I’d rather not have but it renders the whole blog in one giant list. With subdirs I was getting one list per top level category. I think this has to do with Hugo Sections, something I don’t understand yet.

config.toml

Before you create a theme you need to configure a blog. I did this in the quickstart.

baseURL = 'https://www.somebits.com/'
languageCode = 'en-us'
title = "Some Bits: Nelson's Weblog"
theme = "nelson"

“theme” is the name of a directory under themes/ we’ll create in a minute. Note the baseURL matters: it’s going to be hardcoded in a lot of output files. (Although Hugo seems pretty good about supporting relative URLs where possible.) I made a mistake at first and had it set to https://www.somebits.com/weblog/; but that causes duplication of /weblog/weblog/in the URLs given the section setup I did.

An empty skeleton theme

Step 1 is running hugo new theme nelson. This creates a skeleton theme. There’s 11 files that creates but they have very little in them. In particular index.html, list.html, and single.html are all empty. baseof.html does have some HTML boilerplate with a <html> tag and inclusion of some partials for page headers and footers; those partials are also generated as empty files. There are no template files for XML or RSS.

You can go ahead and build a Hugo blog with just this skeleton theme but not much happens. In particular no HTML is generated, despite Hugo saying 4 pages were created. But Hugo will create some XML. Two identical RSS 2.0 files under index.html and public/index.xml, both containing all 1771 blog posts entirely. My whole blog in one XML file! Also two empty RSS 2.0 files for “recent content in tags” and “recent content in categories”. Finally a sitemap.xml with 1775 URLs in it, presumably my individual posts and a few index pages. All in all it looks like Hugo has some default blog XML generation. That’s handy but I’m surprised those aren’t implemented with a generated template file. They can be overridden though.

You can also try to load URLs by running “hugo serve”. The suggested URL http://localhost:1313/ contains an empty <pre> block and nothing else. There is no .html file for this in the static blog, nor anything in the templates, so I guess this is something the Hugo server does. http://localhost:1313/index.xml does load and gives back the RSS contents that were generated. Useful URLs for individual posts like http://localhost:1313/weblog/tech/electrify/ from the sitemap give 404s; they weren’t generated, afterall.

Formatting single blog posts

So how to get posts rendering? The absolute simplest thing is to put any content at all in single.html. I put 3 bytes in that file; “Yo\n”. Rerunning hugo results in 1775 pages being created, 1776 files. The 4 XML files from before, the sitemap, and all 1771 blog posts. Nice! Every blog post is at the expected URL and all have the content “Yo”. Note that the HTML in baseof.html did not appear, that’s a little strange.

The next step is to make single.html a little more complex.
{{ define "main" }} Yo {{ end }}
Regenerating with this also creates 1776 files that all say “Yo”. But now the “Yo” is sandwiched inside the HTML template matter in baseof.html. So that’s a bit magic; apparently Hugo does something different depending on whether that “main” block is defined in the page template or not. (Note that the “main” section is used by baseof.html). Almost all the docs for templates always suggest defining a “main”, so that’s the ordinary thing, and it is shorthand for “slot this into baseof.html”. I wonder if this is explicitly coded behavior or if rendering baseof.html fails with no “main” defined.

Finally I replaced my single.html with a useful template that shows post content:

{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ .Content }}
{{ end }}

Regenerating with that and I get something that’s starting to look like a real blog. Each post gets a title and the post content. Nice!

It’s worth noting at this point that Hugo’s preference for “pretty” URLs means that all your blog posts are in files named “index.html” in subdirectories named after the post filename. Ie, you get a tech/electrify/index.html, not tech/electrify.html. This behavior is configurable.

This was all more confusing than necessary; when I first generated my new theme I could not understand where my posts had gone. If it were me I’d make the new theme command generate something like my last single.html, not an empty file which then means don’t generate pages at all. But then maybe that would confuse people trying to use Hugo for something other than a blog.

Lists of blog posts

Having gotten single posts working it’s time to visit lists. Starting as before, I put just “Hi\n” in list.html and regenerate. Unsurprisingly, this creates a file with just “Hi\n” in three places: weblog/index.html, tags/index.html, and categories/index.html. Putting the “Hi” inside a {{ define "main" }} gets it to use the baseof.html template, just like single posts did.

Moving on to an actual useful list, I took a page out of the tutorial I’m following and put this in list.html

{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ range .Pages.ByPublishDate.Reverse }}
<p> <a href="{{ .RelPermalink }}">{{ .Title }}</a> </p>
{{ end }}
{{ end }}

And voila! Now http://localhost:1313/weblog/ loads with a list of all 1771 posts. As the template suggests, each post is rendered inside its own <p> tag with a Title and a relative link (no hostname) to the Post. It’s like I have a real blog now! Well, the basics.

The magic is thanks to that {{ range }} in the template. The range Hugo function is incredibly important, it’s the hidden loop in templates. It stands for “iterate over this whole collection of things and insert stuff one by one”. Range. I read Hugo docs for hours before I found this key concept.

Gestalt

We’re not done yet but I’m going to declare victory with this ultra minimal blog. In summary, all that was necessary was the create a new theme template, then put some very basic stuff in single.html and list.html. There’s plenty more to do. The tags/index.html and categories/index.html files are still empty; I’d like categories to be populated by directory name. I’d also like to generate monthly archive pages. Could do with some pagination too, not to mention more formatting and breadcrumb navigation. But now at least I understand how to render a list of blog posts in Hugo. And I’ve got it rendering a useful top level list.

The main thing I learned in this exercise is what Hugo does by default with very little templating. It renders every content item through the single.html template (and usually, baseof.html). It also renders list.html for the basic list of all blog posts; it’s up to you to use the range function to build and render that list. As an aside Hugo is also doing some basic RSS and Sitemap creation for you. And that’s it!

Update: there’s some thoughtful discussion about this post on Lobsters.

Hugo frustrations

I’m trying to port my blog to Hugo. It’s not going well. The problem is Hugo is complicated. And nothing out of the box does quite what I want (admittedly, my blog is pretty special snowflake stuff). So now I’m diving in trying to learn how to create my own custom theme, control pages generated for indices, etc. It’s a mess.

What doesn’t help is Hugo is incredibly complicated. Right now I’m struggling to learn Go’s template language, which is the basis of Hugo templates. It’s confusing and gross and I don’t want to learn yet another ad hoc programming language. It’s really confusing because I still don’t have the gestalt of how all Hugo fits together. Like at its core there’s some thing that reads a bunch of content blobs and renders those to HTML along with some list pages of things. Where is that simple structure expressed? Somewhere, but I still don’t quite get it.

Not helping things at all is weird magic. I kept trying things in a simple shortcode and getting the result ZgotmplZ inserted. WTF is that? It looks like a mangled C++ class name or something. No, turns out that’s Go Templates saying “you have used a thing in an unsafe context”. So that’s super confusing. Now I have to learn what contexts are, what safe means in this context, and how to make unsafe things safe. If it’s even possible.

Maybe I should give Jekyll a shot. I already tried Pelican and didn’t love it.

Finding files with weird encodings

I’m working on (finally) converting my Blosxom blog to something modern, probably Hugo. One problem I have is that I was bad and wrote blog posts in different encodings. (These probably render wrong on my blog nowadays). Here’s a Linux command line to find all files that are not ASCII or UTF-8:

find . -print0 | 
  xargs -0 file -i |
  egrep -v '(ascii|utf-8)'

The heavy lifting is done by file -i which prints out MIME types, including a guessed encoding.

I thought all my files were ASCII, UTF-8, or ISO-Latin-1. But in fact a few are CP1252 thanks to Windows “smart quotes”. CP1252 doesn’t seem to be identified by file; it shows up as charset=iso-8859-1. It is a strict superset of ISO-Latin-1 so in my Python code I’m just going to pretend all the files that aren’t ASCII or UTF-8 are in CP1252.

Black paper experiments

One of the dramatic effects you can do with a plotter is printing in bright inks on black paper. The ink has to be opaque for this to work well; you want to completely hide the black paper below it. Here’s some experiments with some new pens.

Three kinds of ink in the top sample: Uniball Signo 1mm, a Pentel brush in the middle that totally didn’t work, and Kuretake ZIG Metallic Calligraphy pens. Most all of these look good on black paper. The Uniball Signo is a pretty solid low cost choice, a rollerball. The white ink is clumpy though, you can sort of see it in the top left sample. Uniball Signo Silver works better; that’s what I used for the plot at bottom.

Photographing black paper is tricky. The above image is straight from my Pixel 3. Shooting in full sun was clearly a mistake. Needless to say it looks more like black in real life, and the lines pop pretty nicely.

White ink is particularly problematic: see here or here for example. That second post is from someone using Rotring Isograph Pens, fancy technical pens you fill yourself with drawing ink. That lets you choose from a wide variety of ink colors; Rotring sells 5 including (unusually) a white. Some folks use fountain pens for fancy white ink, too (including I think the first post.) There’s even a White Ink product experiment going on right now: Wink.

But I’m not messing with liquid ink yet. For cartridges see this plot featuring a Pentel hybrid gel pen. Or this one with a Sakura Gelly Roll. The silver Uniball Signo I used here works pretty well but the white is not reliable.

Fixing irrigation: all valves stuck open

More adventures in irrigation systems. We wired up a new controller (our third) for a few valves, programmed the system, and let it run. The next morning every irrigation valve was open, water running everywhere. We don’t have enough water pressure / well capacity to actually run that so more like things were trickling.

I think I found my answer on this web page. These valves are designed to close automatically if there’s no power. But if an air bubble gets trapped in the valve diaphragm it can get stuck open. I think many of my valves were in this state. The solution for that the pagesuggests is to manually open the valves (with the bleeder valve or by unscrewing the solenoid). I did that and I think managed to get all 23 valves to close.

How do air bubbles get in? The article talks about this happening after you’ve drained the system for winter and restarted it. In my case I think what might have happened is the new controller was programmed wrong (or clocks out of sync) so that two different high flow sprinklers were running at the same time. And that overwhelmed the water pressure and let some air in, but maybe only a little. The worst thing is this is a cascading failure; with valves stuck open there’s only going to keep being intermittent water pressure.

I asked two different irrigation experts if they could understand this, they were mystified. Both kept wanting to blame something electrical. Sort of makes sense; if your expertise is water and plants and dirt then the computers probably seem a little unpredictable. But all the controllers were literally off. Also 3 disconnected control systems, no way they would have all failed the same way at the same time. The only common connection was the water. Systems thinking helps here.

Now I have to carefully test all this before I trust it again; it’s not OK to leave town with an irrigation system that may fully fail open. I have the water supply turned on but all valves shut off and all controllers unplugged. Going to let that sit for 24 hours and verify it’s dry. Then watchfully turn controllers on again and run the valves manually and verify they turn off and on. Then turn on the programs again. Probably just the two old controllers first, verify that doesn’t break anything, then if that’s working re-enable the new controller last.

Distribution of 2d noise functions

So I’ve been using noise functions in my plotter art. One thing to be aware of with noise functions is the output distributions aren’t uniform. I don’t just mean the smooth variation of nearby points that you’re using a fancy noise function for, but even if you sample uniformly from a large space the values are still closer to a normal distribution than a uniform distribution. To put it more concretely; these noise functions all return values in the range [-1, 1]. (2d Perlin noise is [-0.7, 0.7] ish.) But results near 0 are more common than results near 1 and -1. See below for some histograms.

This isn’t necessarily bad. You can always scale the output up to a uniform distribution or whatever you want. Although that requires knowing what the original distribution actually is. Perlin noise looks like a real normal distribution but both Simplex and OpenSimplex noise have a weird boxy distribution where results are uniformish in the range of -0.5 to 0.5.

More than the usual caveats apply; this is sloppy code and I might have gotten it wrong. Histograms are for 1 million samples drawn from OpenSimplex and caseman’s Perlin and Simplex noise. 2d noise in each case; the coordinates were uniformly sampled in the range of [-100_000, 100_000]. (A small range because caseman’s code seems to be using 32 bit floats). I did not alter the scaling or octave parameters at all, library defaults. My code is in this gist.

Perlin noise
-0.95
-0.85
-0.75
-0.65
-0.55 ***
-0.45 ***********
-0.35 *****************
-0.25 *********************************
-0.15 *******************************************
-0.05 *************************************************
 0.05 **************************************************
 0.15 ********************************************
 0.25 **********************************
 0.35 ****************
 0.45 ***********
 0.55 ***
 0.65 *
 0.75
 0.85
 0.95
 
Simplex noise
-0.95
-0.85 *********
-0.75 **************
-0.65 *************************
-0.55 ************************************************
-0.45 *************************************************
-0.35 **********************************************
-0.25 **********************************************
-0.15 ***********************************************
-0.05 **********************************************
 0.05 ************************************************
 0.15 **************************************************
 0.25 ************************************************
 0.35 ************************************************
 0.45 **************************************************
 0.55 *************************************************
 0.65 ************************
 0.75 **************
 0.85 *********
 0.95
 
OpenSimplex noise2d
-0.95
-0.85
-0.75 *****
-0.65 ***************
-0.55 **************************
-0.45 *****************************************
-0.35 **************************************************
-0.25 **************************************************
-0.15 *************************************************
-0.05 *************************************************
 0.05 **************************************************
 0.15 *************************************************
 0.25 *************************************************
 0.35 *************************************************
 0.45 ****************************************
 0.55 **************************
 0.65 ***************
 0.75 *****
 0.85
 0.95

Update: I asked about this on the Plotter Art Discord and someone suggested empirically measuring the distribution then doing a correction. They offered this matlab snippet:

p = randn(1000,1);
p2 = (p-min(p))/(max(p)-min(p));
x = sort(p2);
CDFp = linspace(0,1,numel(p2));
pUnif = interp1(x,CDFp,p2);

CO2 sensing and air circulation

Ever since I got a CO2 sensor I’ve been low-key interested in my CO2 level. Partly just because it’s interesting, partly because CO2 is related to cognitive ability (here and here), and partly theoretically because CO2 is a proxy for air circulation in general and thus, potentially, Covid prevention. That latter point is apparently making waves in schools.

Here’s some benchmark numbers for CO2 levels. These numbers are all ppm, parts per million. The important number is 420ppm, which is what you get outside right now.

Recent research has found a significant cognitive effect for all levels of CO2. Even going from 400 to 600 to 800ppm had a few percent impact on Stroop color/word test performance. Fresh air matters! (Corollary: global warming is directly making us all dumber.) Edit: this may not be the whole story, see this comment about 1960s submarine studies.

CO2 as a proxy to air circulation for disease prevention is a newer idea. Honestly it used to be too hard, but now that you can carry a $100 CO2 sensor with you (or in your kid’s backpack) it is much easier. It’s really not clear what the “right” level is. CDC’s 800ppm recommendation seems reasonable but also possibly challenging.

CO2 in my house in Grass Valley

My house is well sealed and insulated. I’ve learned that during the day CO2 at my desk gets to about 800ppm. The wacky thing is it doesn’t drop to 420 overnight, even if I’m in another part of the house sleeping peacefully.

Image
24 hours of CO2 with no one home.

I left the house at 11:30am, came back the next day. CO2 had just about returned to 420.

Anyways, now I open a window when I can. It doesn’t keep the CO2 down much at my desk while I’m in my office, but the air clears out pretty quickly when I’m away for a bit.

This is all for summer / fall. The air conditioner may be running and doesn’t seem to affect things. But the heater isn’t. I believe last winter I noticed the CO2 fell every night even with all the windows closed and I suspect that might have something to do with the heater or outside temperature, but I don’t have the data to back that up. I’ll know in a few months.

Home HVAC systems typically don’t have anything designed to supply fresh air. The air systems are closed to prevent having to condition outside air. Older houses are so drafty it’s not a big problem. But it is possibly a small problem for a new, well insulated house. I asked my HVAC guy and he said an outside air intake vent could be added for $2500 or so. Presumably it’s not open all the time (like a window), that has a significant cost in temperature and humidity.

Commercial buildings are designed to standards including air changes per hour. Nominally, an ACH of 1 means that all the air is replaced once an hour. ACH standards are 4 ACH at the low end to 20 or more for places that generate lots of pollution, like kitchens and paint shops. I’m not quite sure how to convert my CO2 information into ACH; this presentation suggests it’s possible but maybe a novel idea. Presumably there’s some sort of half-life calculation involved.

The main conclusion I draw from all this is it’s good to open a window now and again.

Python static blog generators

Once again contemplating moving my blog away from the ancient Blosxom setup I have. Static generators are clearly the way to go. Here’s what I found among Python options.

Pelican looks to be the most popular. Nikola is also compelling. Lektor may also be an option. Cactus and Hyde are abandonware.

I may also consider using Hugo. Go, not Python.

USB charging in 2021

USB charging is even more of a mess than ever before. I thought USB-C and USB Power Delivery was the be-all and end-all of charging. One common protocol, buy a charger that claims 45W and a USB-PD device would charge at 45W. Ha!

I bought a nifty little USB charging tester. It shows you in real time what the current voltage, amperage, and thus wattage of the charging current is. Finally a reliable way to tell what’s going on! Assuming the presence of the tester doesn’t disrupt the USB charging, that is.

The charger Amazon sent me is called a KWS-1902C, there’s a nice review here. It claims to support up to 150W, 4-30V, and 0-5A. The first look on the blog is from October 2018, for a sense of product age. I’m assuming it does not support USB 3.1 gen 2. But it may not need to, maybe it will do that with the right cable actually providing the E-marker chip. It apparently has a display bug if you go over 65.536W.

My Samsung Galaxy Tab S7+ (aka SM-T970) claims to support up to 45W of charging. But when I plug it in via USB-C to an Anker Power Port Atom III, advertised as a 60W charger, I only get 15W. 9V at 1.67A. Actually a little less than that, like 14.3W. I’ve tried two USB-C cables, also an A-to-C cable using the A port on the charger. Always 15W. So what’s going on?

First off, the Anker charging port is not actually 60W. It’s 45W. And that only at 20V. At 9V the max is 3A, or 27W. But still I’m only getting 15W.

Second, Samsung’s support for “fast charging” relies on a USB spec called “Programmable Power Supply” or PPS. That’s a newer thing where the device just requests an arbitrary voltage and amperage and the charger provides it. At least one other Samsung device wants to be charged at 10V and 4.5A. Samsung’s own 45W charger will do PPS up to 11V at 5A. But if it falls back to ordinary USB-PD 3.0 then it maxes out at 9V at 3A.

But that’s still 27W. I don’t know why the Anker charger is only putting out 15W. A failure to negotiate a higher amperage? Even basic USB PD 3.0 supports 9V/3A but I’m not getting it. Maybe the device deliberately charges itself slowly to preserve battery life? I haven’t tried charging from a dead battery.

My motherboard’s USB ports charge the tablet at 5V/1.5A. I believe that’s the minimum to be a USB-C port.

Back to PPS, Anker does make a couple of 65W PPS chargers but they seem to be newer and/or more expensive. This review suggests it’s capped at 3.25A so at 9V you’re limited to 29W. Every charger brand seems to have one or two PPS chargers but most chargers don’t support it.

How about charging other devices?

My Google Pixel 3 phone should support 5V/3A or 9V/2A. I get 9V at 1.2A. So that’s confusing. It’s variable too; 1.1-1.3A. I’m beginning to doubt the accuracy of my tester. Although again, maybe this is a battery preservation strategy? (Not USB, but wireless charging tops out at 10W.)

My PS5 controller can’t be charged by the Anker charger, there’s no orange light. The official specs say it can do 5.1V at 2.8A. When plugged in to the Anker charger I see it’s getting 5V and 0.1A, which is the basic USB 2.0 draw for a low power operating device. Plugged in to the PS5 in rest mode (with the meter) it does charge, at least the orange light is throbbing. But it’s still only 5V and 0.125A, very low power. So it may not be charging well. (Update: after six hours it was still looking like it was charging. Maybe the tester screwed it up?) Also I note the D- data line is at 2.76V; for most devices both D+ and D- have been at 0V when charging. Presumably that’s related to why the controller can’t be charged by the Anker charger, must be some odd protocol.

Bottom line: absolutely none of my devices are charging at the rated spec. Anker in general makes good products, so I’m not inclined to blame the charger. Although at least for the tablet it’s clear I need a PPS charger to get maximum charging.

I wonder if it’s my cable to blame. I’ve tried several decent cables, including an Amazon Basics cable. But they’re a couple of years old. Apparently the new hotness is USB-3.1 Gen 2, which has an active chip in the cable itself for negotiating USB-PD and supports 10Gbps data, 20V/5A charging. (Keyword: E-marker chip.) I am going to buy this one and see if it makes a difference. Amazon Basics makes one too. Not clear it will make a difference, from what I’ve read it only becomes important when you want to go over 5A.

Update: the new cable makes no difference.

Update 2: there’s been some controversy over Google Pixel Pro 6 charging, see Google’s explanation. I just measured charging my phone at 30% battery and got 8.7V/2.14A, or 18.6W. Google says their max is 23W. I tend to leave the phone on my original Google wireless charging stand so don’t much care.

SourceSinkVoltsAmps
Anker Power Port Atom IIIGoogle Pixel 391.2
Anker Power Port Atom IIISamsung Galaxy Tab S7+91.67
Anker Power Port Atom IIIPS5 Controller50.1
PS5 Console (with meter)PS5 Controller50.125
Anker Power Port Atom IIIGoogle Pixel Pro 68.702.14

Syncthing status from the command line

I’ve written a little tool to show me the status of Syncthing on the command line. I now rely on it to get my files off of computers that will then be turned off and inaccessible. I didn’t have any way to know if it was really working. I don’t have a reliable outage monitoring system for all my personal tech crap. (I mean, who does? Hmm..)

Anyway this turned into a bit of a yak-shaving exercise. Syncthing does not really have a command line tool. There is a syncthing cli command (and formerly the syncthing-cli third party tool) but they don’t report the status I need. What syncthing does have is a very nice REST API for querying status, so I wrote a tool to check that.

The other tricky thing is defining what it means for syncthing to be synced. I’m not sure I got this right. The algorithm I’m using is it enumerates all folders and all remote devices and checks completion on each one. In practice folders seems to catch outgoing changes, remote devices catches incoming changes. It ends up being O(n) HTTP calls, not ideal, but here we are. It might be possible to get it down to 3; I didn’t quite understand how the bundling in rest/db/completion worked.

Anyway, the Python script below mostly works. I wonder if someone else has already done this and I reinvented the wheel? One last wrinkle; when to run this. I was originally thinking in MOTD (hence my earlier post) but for now I’m running it in .bash_login.

#!/usr/bin/env python3
"""
Status report for syncthing, suitable for including in /etc/motd.d. By Nelson Minar <nelson@monkey.org>

Note that this will show "completely synchronized" if a file was very recently created or altered and
syncthing is not yet aware the change has been made. See the scanning and fsnotify docs in Syncthing for details.
"""

import json, urllib.request, platform, itertools, sys
from pprint import pprint

"Configure the URL endpoint and API key based on hostname. API key is in Settings."
HOST = None
API_KEY = None
config_table = {
	'ub': ('http://127.0.0.1:8384', 'XXXXX'),
    'Nelson-Win10': ('http://127.0.0.1:2103', 'XXXXX')
}

def st_api(command):
	"Call the SyncThing REST API and return as JSON"
	req = urllib.request.Request(f'{HOST}/{command}')
	req.add_header('X-API-Key', API_KEY)
	resp = urllib.request.urlopen(req, timeout=2).read()
	return json.loads(resp)

def main():
	global HOST, API_KEY
	try:
		HOST, API_KEY = config_table[platform.node()]
	except:
		# Exit silently if we're not configured
		sys.exit(0)

	folder_report = []
	device_report = []
	try:
		# Explicit error handling for first REST connection. Others are YOLO.
		devices = st_api('rest/config/devices')
	except Exception as e:
		print(f'Syncthing: Error connecting to {HOST}.')
		sys.exit(0)

	# Check completion for all remote devices
	for device in devices:
		completion = st_api(f'rest/db/completion?device={device["deviceID"]}')
		device_report.append((device["name"], completion["completion"]))

	# Check completion for all folders
	for folder in st_api('rest/config/folders'):
		completion = st_api(f'rest/db/completion?folder={folder["id"]}')
		folder_report.append((folder["label"], completion["completion"]))

	# Show a short status message
	if all([c == 100 for n, c in itertools.chain(folder_report, device_report)]):
		print('Syncthing:', f'Completely synchronized.')
	else:
		incompletes = ((n, c) for n, c in itertools.chain(folder_report, device_report) if c != 100)
		print('Syncthing:', 'Incomplete.\n ', '\n  '.join(f'{n}: {c:.2f}%' for n, c in incompletes))
		print(f'Details at {HOST}')

if __name__ == '__main__':
	main()
	sys.exit(0)