Some Bits: Nelson's log

Kaiterra Laser Egg monitor in Telegraf

I have a CO2 sensor, a Kaiterra Laser Egg. Home Assistant has support for getting data from it but I don’t much like HASS UI. Or data retention; I was hoping it had stored a year of data but I learned the little sqlite database has a 10 day expiration. Oops. Anyway I decided to roll my own collector using Telegraf, for InfluxDB and Grafana.

The Kaiterra doesn’t have any LAN API I could find. Instead the devices upload to the cloud and they have a decent API service. It’s mostly pretty straightforward REST. One trick is you have to find your device ID. I can’t find that in any UI anywhere, I finally got it by having Kaiterra mail me my data, the data dump included the device ID.

There’s an official Kaiterra Python client but it’s 2 years old and pretty wonky. It also uses an old API endpoint which among other janky things has invalid JSON (single quotes, ugh). So I just wrote my own code using urllib and json in Python. One goal here was to make this not depend on any virtual environment, so stock libraries only.

It’s 2021 and Python still has no built-in way to import the common ISO-8601 timestamps included in every JSON file, like 2012-04-23T18:25:43.511Z. Plenty of third party libraries to do it. There’s a datetime.datetime.fromisoformat but the joke is on us, it doesn’t support the trailing Z. There’s a years-long argument about why that’s OK, basically the Python authors don’t actually want to support all of ISO 8601 in the method named “from ISO format” nor do they recognize the value of parsing the most common text format in the world. Fortunately you can just chop the Z off and it’ll probably work.

I’m running this as a Telegraf exec agent, outputting data in Influx format. That’s mostly pretty easy with the wrinkle that they want unix-epoch-like timestamps only expressed in nanoseconds. So I’m appending 000000000 to my time outputs, lol.

laseregg rco2=480,rhumid=36.91,rpm10c=7,rpm25c=6,rtemp=24.9 1632448492000000000

I think it’d be possible to not write any Python code at all and use a cleverly configured Telegraf http agent with a JSON parser, but I didn’t want to try to debug that so I wrote Python code instead.

Anyway, here’s the telegraf config snippet and the python code. I’m still tweaking the Grafana layout and don’t feel like pasting a giant ugly wodge of Grafana config anyway.

[[inputs.exec]]
  interval = "50s"
  timeout = "10s"
  commands = [ "/usr/local/etc/laseregg-telegraf.py" ]
  data_format = "influx"
#!/usr/bin/python3.8
"""Telegraf / InfluxDB client to import data from a Kaiterra LaserEgg
Does not require any venv or external libraries. Does require Python 3.7 features.
"""

import urllib

api_key = YOUR API KEY HERE
device_id = YOUR UUID HERE
endpoint = 'https://api.kaiterra.com'

def urllib_client():
	"Simple HTTP request for Kaiterra Laser Egg data"
	import urllib.request, json, datetime

	url = f'{endpoint}/v1/devices/{device_id}/top?key={api_key}'
	expected_types = {'rco2': 'ppm', 'rhumid': '%', 'rpm10c': 'µg/m³', 'rpm25c': 'µg/m³', 'rtemp': 'C'}

	# Make the request
	req = urllib.request.urlopen(url)
	json_text = req.read()
	json_data = json.loads(json_text)

	# Parse the data into a simple Python struct
	record = {}
	record['ts'] = json_data['data'][0]['points'][0]['ts']
	for d in json_data['data']:
		assert d['units'] == expected_types[d['param']]
		point = d['points'][0]
		assert point['ts'] == record['ts']
		record[d['param']] = point['value']

# Convert ISO time with appended Z to Unix timestamp
	record['unix_ts'] = datetime.datetime.timestamp(datetime.datetime.fromisoformat(record['ts'][:-1]))
	return record

r = urllib_client()
values = ((f'{k}={r[k]}') for k in ('rco2', 'rhumid', 'rpm10c', 'rpm25c', 'rtemp'))
field_set = ','.join(values)
ts = int(r["unix_ts"])
print(f'laseregg {field_set} {ts}000000000')