Some Bits: Nelson's log

100 posts about home

Customizing Android TV (Sony Bravia)

I have a Sony Bravia TV running Android TV. It’s mostly quite nice, I like Android better than Roku or whatever weird TV vendor OSes are out there Plex works, Youtube works, that’s really all I care about. Unfortunately it’s also loaded with ads and various UI features I don’t want. Here’s some fixes.

Apps only mode

The first thing is very easy but new-to-me: apps-only-mode. Basically you tell it you just want the home screen to be a grid of apps to launch. Most of the other UI crap falls away. Unfortunately there’s still one big box at the top Google controls, right now it’s shilling Tubo and AppleTV and Google TV. But at least it’s down to the one box.

Disable Samba Interactive TV

A second simple improvement is to find “Samba Interactive TV” and turn it off. Mine was hiding under System, I think, unless it was Privacy. This is the “service” that watches what’s on your screen and tells advertisers what you are watching. It is spyware, disable it.

Hacking in Android debug mode

Android devices are nicely generic and there’s a lot of tweaking you can do if you’re willing to enable developer mode and connect through the debug system. I suspect there are many ways to skin this cat.

I used ATV Optimizer, a nice desktop GUI that gives you various menus to tweak things and take a snapshot, roll back, etc. It’s a little scary, I’m sure you can break the TV if you try hard enough, but the tool seems pretty usable.

Enabling debug access

The first thing is getting the TV to let your desktop connect in debug mode. For me I first had to enable developer mode. Then I had to turn on “USB debugging” and also “Wireless debugging”. The latter wouldn’t enable for me: turns out they really mean “wireless” and I had to unplug my ethernet and switch to WiFi. Finally I had to do a one-time pairing with a PIN. All this was a hassle that Claude helped me get through but in the end ATV Optimizer was able to connect.

Animation speed

The best optimization I made was a Tweak that sets the animation speed to 0.5. Which apparently means “twice as fast”. Suddenly the TV doesn’t feel awful and laggy. Why do UI designers create such slow animations? Argh!

Services

ATV Optimizer mostly is a tool that lets you disable various services running on your Android device. It gives you a list of what’s running in the background. I was pleasantly surprised how little junk my Sony TV had running, I ended up not feeling like I had to disable anything.

Launcher

A final step is to replace the stock Android TV launcher with something else. The good launchers don’t have any ads at all, just the stuff you want on screen. They also tend to be lower memory and CPU usage. ProjectIvy is popular and is what I picked. I think the main variance in these things is how you customize them.

I like ProjectIvy alright but in the end decided not to install it as my default launcher. Gonna stick with Google’s launcher in apps only mode first and see if that’s good enough. A broken launcher could cause real havoc so it’s not something to replace lightly.

Streaming Linux audio to a Sonos S1

My new Linux desktop has a neat trick: I can route the sound I’m hearing to my Sonos S1 speakers. It’s always annoyed me I couldn’t do that easily before.

The magic plumbing is PulseAudio, the Linux subsystem that handles media streams. (Or actually PipeWire, the replacement.) Basically it lets you pipe music (and video) around from program to program.

There’s a third party Sonos controller app for Linux called Noson. It has the ability to tell the Sonos unit to play audio from a network stream. It will then create a network stream for you that is listening to PulseAudio on your Linux box.

Once this is going the Sonos shows it is playing a track named “pulse.flac?acr=hostname:1400”. I don’t think hostname has to actually resolve for it to work.

The other trick is to get the audio going out to PulseAudio. For me the source I want to play is Plexamp. By default Plexamp is playing out my speakers. I used pavucontrol to re-route it, choosing “noson” instead of my usual sound card / speakers for the output. I think I could also have just set this in Plexamp: right now it’s being told to play to “System default” but I can choose where it goes inside the app.

The one downside to this setup is latency. Sonos wants to buffer a stream before playing it so anything I play is delayed about 10 seconds. Not awful but a little annoying.

I’m doing all this to get Plexamp to drive the speakers in my house. Plexamp is really cool, working off my music library and doing all sorts of advanced DJ and mood / genre matching tricks.

(As with anything these days, I figured all this out thanks to AI. Here’s a link to the conversation.)

Pipewire

Need to learn more about this! Here’s what qpwgraph shows me, you can also edit this like patch bays. coppwr is another tool that shows a similar view with more low level detail

Bidet, floor heater power usage

I got some upgrades in my bathroom: a Toto S5 Washlet bidet and a Schluter electric heated floor. They use power! Here’s how much.

The Toto uses 5–10W when idle. That powers a little light and a toilet seat heater (set to low). It peaks at about 500W for a minute or so when you are using heated water. We’re averaging about 0.25kWh a day for two of us, or just $0.10 a day. That seems very low!

A Toto C5 I have was about 0.08kWh a day. That model has a water tank, not instant heat, and no seat heater nor light.

The floor heater is set to turn on 7am-11am to 82°. It’s been 40-60° outside, the furnace heats the air inside to 68°. The bathroom is about 200 sq.ft. The heater draws a full 1300W for a couple of hours to bring the floor up to temperature, then 700Wh an hour to maintain the temperature for a couple more hours. Overall it’s about 3.5kWh a day, or about $1.50 a day. It doesn’t seem to heat the air in the room much so I think all this heat is wasted, not saving us furnace usage.

Speaker noise from Qi2 charger

Just solved a problem that was driving me crazy. My nice Presonus Eris powered speakers were making a scratchy noise, rhythmic clicking. A new problem but I’d recently changed a lot of stuff on my desktop setup so I couldn’t figure out what it was. ChatGPT led me down the garden path.

Finally figured out the culprit is my new Belkin Qi2 phone charger. The sound gets louder the closer it is to the speakers. Over about a foot away and the sound stops. Problem solved! It all makes sense: the Qi2 has strong magnets and is also putting out a lot of power for wireless charging.

There’s a lot of things that can cause this kind of analog circuit noise. The diagnostic that was most helpful was unplugging the audio inputs from the speakers: that verified the sound wasn’t related to my PC or the sound input. Beyond that it was just moving stuff around until the sound stopped.

I’ve got some ferrite chokes on order. In theory you put these around the power cables near the device and it will help soak up the interference. A little skeptical that makes sense with a USB-powered device but I’ll give it a shot.

Setting the stupid clock on my Viking VSOE530

I have a fancy oven with a stupid digital clock and twice a year I have to look up how to set the stupid time. The trick is which two magic buttons you have to hold down at once. Here’s the instructions

Setting the time-of-day:

  • Push and hold the “min/sec timer” and ‘bake time” buttons simultaneously.
  • Turn the “Set” knob until correct time is displayed on the digital clock.
  • Release hold from “min/sec timed’ and “bake time” buttons.
    The analog clock’s time will automatically set to match the digital clock.

There’s also elaborate instructions for synchronizing the analog clock hands to the digital clock. But usually they will sync themselves.

Daylight savings time is fucking stupid.

WattBox hacking

My new TV has an expensive power strip called a WattBox. It’s kinda neat, has an Internet interface and you can individually monitor and turn outlets off and on, also can accept a UPS status as input, etc. It’s overkill for me but it’s neat.

Also it has REALLY BRIGHT LEDs above each socket to indicate if power is on. Yes, the thing that’s designed to sit next to your TV shines bright lights. I was hoping I could dim the LED level via software but I can’t. So black stickers it is. But I did learn a bit about hacking it.

The key thing is to go to the support page and grab the API docs, It has a simple telnet interface: you type ?Firmware at it and it responds ?Firmware=2.3.0.2. There’s this simple control interface for most functions.

The product does also have a basic webapp interface and a fancy custom software tool called OvrC that doesn’t seem to be free. There’s also a bunch of open source wrappers for the API, including Home Assistant support. Would be nice if you really want to monitor or control the power.

I just want to turn the LEDs down. There doesn’t seem to be that ability. There are FaceplateLedLevel commands but that seems to apply to an accessory I don’t have installed. Mine reports a level of -1 and ?FaceplatePresent=0.

Sony Bravia A95L “Enhanced Mode” HDMI

I bought a fancy new OLED TV, a Sony Bravia A95L. It’s beautiful! And it should do 3840x2160 video (ie, 4K) at 60Hz with HDR10. With Variable Refresh Rate, no less! But I was having trouble with both my Playstation 5 and a gaming PC I have.

Long story short, the Sony Bravia has a configuration for each HDMI input called “Enhanced format”. You want to turn that on. By default it is off and video signals are limited to 30 FPS in HDR mode. I guess this is a compatibility / performance thing but it seems fine for me.

There’s all sorts of other things that can go wrong. Windows likes to default to 30 FPS sometimes. The cable can be the wrong kind. Etc. But this setting in the screen is a new one on me.

There’s a bunch of other settings in the screen input too. One thing I particularly like is you don’t have to enable “game mode” to disable a bunch of extra processing like motion smoothing, etc.

It really is a lovely display. HDR is a marvel.

Wine cabinet power + temperature

We bought a wine cabinet with a refrigeration unit to Grass Valley. It’s in our garage. Outside temps fluctuate 50-95, garage fluctuates about 60-80, and the wine cabinet keeps 55-59, well mostly.

Downside is it’s taking about 2kWh / day to keep it there, double that on hot days. Power costs about $0.50/kWh (I think?) so it’s costing $30-$60 to keep the wine cool in summer months.

The unit seems to come on for about 15 minutes, using 280W, then off for about 15 minutes. But total time on varies with temperature. When it’s not hot it stays 56-58, but on a hot day it’s varying 55-59.

Update: 118 kWh for the month of June. That’s roughly $50. Varies about 2x depending on how hot the day is. I’m considering insulating the garage doors.

Here’s a bunch of graphs for May:

Outdoor temperature (one month)

Cabinet Temperature (one hot week)

Power: month

Power (hot day)

Power (a hot afternoon hour)

Nest Thermostat Gen 2 charging without a C wire

Long story short: if you have an old Nest installed without a C wire, it may not charge when the heat is on.

My Nest Gen 2 from 2014 went offline yesterday with a low battery warning. So I had to learn about Nest battery charging. Some details...

I have a 20+ year old furnace (heat only) and old wiring. Here’s a reference on thermostat wiring. As shown above I only have three wires: R, W, and G. R is the power, it’s always at 24V. W is the heater control: connect it to R and the heater turns on. (Phind taught me how to hotwire my furnace!). G is the fan control, I think for turning the fan on without heat.

What’s missing there is the C wire. C is a common neutral, and if I had one I could charge the battery by drawing 100-200mA of current between R and C. Any modern house should have a C wire and any fancy thermostat really wants one.

Nest Gen 2 works without a C wire. The way it works is charging off W and R. But here’s the problem, it can’t charge while the heat is turned on. I think this explains my Nest’s problem with low charge, it’s been cold and the heater has been running a lot. (Even when it does charge, it only does so at 20mA, that’s very little power.) When the battery charge gets below 3.7V it will shut off the networking just to keep the thermostat running. That’s a nice feature, at least you still have heating!

The temporary fix for a charging problem is to pull the Nest off the wall and plug in a charger to the Micro USB port. This is very easy, the Nest is designed to be removable with a nice socket.

Not sure what the long term fix is. I called Nest Support and, to their credit, they had a detailed troubleshooting script even for my 10 year old product. We got as far as them asking me to turn off wifi (to rule out a networking power drain problem) and then charge the battery up to 3.9V via USB before calling them back. I haven’t done that.

I guess I’m hoping this problem will only happen rarely on very cold days and that the power saving mode is enough to keep the heat on for me. I don’t think this problem has happened before, at least not often. I’m planning on upgrading to a heat pump with cooling in the next year or two. At that point I’ll get new modern wiring and a new thermostat.

Battery voltages

My real question is whether after 10 years it would be expected that the Next Gen 2 battery might be worn out and no longer hold a charge. The Gen 2 has a sealed-in lithium battery. Online advice is 50/50 on whether it should last this long. Sadly the support team didn’t answer my direct question about longevity.

You can see the battery voltage in Settings / Technical Info / Power. I’ve seen the battery as low as 3.65V and still operating (but offline). The highest I’ve seen is 3.88V. I thought the support guy gave me a target voltage of 3.9V but now I wonder if that’s even possible. Google’s docs only say that over 3.7V is what you want. This community answer gives a normal range of 3.7-3.9V.

One “fun fact”: if WiFi is marginal, the radio will draw more power to stay connected. I wonder if that’s why support told me to turn off networking for testing.

Nest is a bad product

Google Nest makes bad products. Don’t buy Nest products. If you need a thermostat, buy an Ecobee or Sensi instead. I’ve had a lot of trouble with this Nest thermostat over the years. Like the time they shipped a firmware that broke battery charging and bricked all the thermostats until you took them off the wall and plugged them in to USB. Or all the times the servers are down. Or until I figured out how to turn off all the fancy learning features that don’t work very well and just use it as a $40 programmable thermostat.

To be fair, the Nest thermostat has mostly worked for 10 years. And the hardware is very nice. The real problem here is a thermostat should be a really simple and reliable device. It’s just a switch! It should be expected to last for 20+ years. I appreciate that Nest reinvented the product category, most HVAC thermostats are awful. They had real software and UI! But it just has never been quite as good as I hoped.

My particular problem at my house is the lack of a proper power supply. That’s not Nest’s fault. It’s impressive the device works at all without a C wire, most newer thermostats don’t. They also have an adapter kit you can add to work around the lack of a C wire.

Sunpower solar for 2024

I’ve had my house solar system in Grass Valley for three full years now. It’s working great, just as designed. Some quick data:

YearProduced (kWh)Used
20241559416543
20231537314688
202217700?16000?

2023 and 2024 data are from the MySunPower app. I don’t have full data for 2022 so the numbers are estimates from PG&E’s usage data. I suspect PG&E’s numbers are just larger than what MySunPower measures and have no way of knowing which is accurate. I should go back in a month when PG&E’s accounting has settled and try to collect the data from them.

Anyway, comparing 2023 and 2024 I generated about the same power both years. But I used 1855kWh more. 1336 of that is charging my car.

The car is new for 2024. I charged it another 679kWh in San Francisco, so a total of 2100kWh for the year. I was guessing it’d be about 3000kWh so that’s better than I expected.

Update: NEM true-up

Just got the surprise $700 electric bill, the true-up for the year. The bill is very difficult to read and I can’t make sense of it, but it’s roughly correct(ish) so I’ll go with it.

The actual charge for “NEM Electric charges” is $630.95 for 579.3 kWh. That doesn’t really square with the $695.26 for 121 kWh in the monthly breakdown.

SunPower bankruptcy

2024 is the year SunPower went bankrupt. A lot of operations seem to be continuing. But the mySunPower web application is broken now. Near as I can tell the SSL certificates expired, plus maybe some servers are down. No word on if it will be back. The mobile app is still up though, here are some screenshots from it.

Home security cameras: Eufy + Frigate

For years I’ve wanted some lightweight private home security cameras. I’m not too worried about security but it’s reassuring to be able to see video of the house when you’re not home.

I’ve come to really like Eufy cameras. The basic $30 indoor WiFi camera (plus a cheap microSD card) works great with their mobile app. Out of the box you get something that detects motion (including people vs animals) and stores video of events and alerts you on your phone. Also a quick live view browser. Firewall traversal works fine.

There’s no fee for all this service, the caveat being that you are live streaming video clips off of the camera’s storage in your house. There’s a cloud video storage option too if you’re worried about a clever thief disabling your camera (I am not). But what I like about this setup is Eufy isn’t storing video remotely at all. They’ve had a couple of privacy kerfuffles like not disclosing adequately that a still image is briefly uploaded to a cloud server if you have it taking snapshots and sending them to your phone. But they seem like well-meaning mistakes, not total failures (Wyze) or a not-private design by default (most consumer products).

Honestly the Eufy product is good enough on its own that may be all I need. The last piece I have to set up is geofencing so it doesn’t operate when we’re home. I think it supports everything I need (using your phone to detect when you’re home) but I haven’t used it yet.

Frigate

Still, what could one do with more software? Thanks to Aneel on Mastodon I learned about Frigate, an open source video recorder. It works with live continuous cameras and does fancy motion detection, etc and gives you a nice web display of live video and events. It seems quite sophisticated too with advanced, customizable detection algorithms, video area masking, etc. Also cool: it can use Intel QuickSync or a Coral TPU (!) for hardware acceleration of tasks.

I gave it a 15 minute try using a tteck script to install and run it on Proxmox. Got it up and running pretty quick although the hand-edited YAML file feels like a bit of a throwback. You enable an always-on RTSP feed from the Eufy camera and then configure Frigate to connect to it. The tteck scripts nicely set up Intel CPU acceleration for me already although I did have to do some extra bits to enable it and to enable recording.

It seems to work well. It’s a very nice product, the UI is impressive. Monitoring one camera the container is using 20% of a i7-12600k CPU and some tiny fraction of GPU. About 1GB of RAM. I imagine that multiplies with more cameras but this can run on a pretty low powered Intel machine.

I don’t know if I’m going to keep using Frigate or not. I still think the Eufy product does most of what I want. And I don’t love the idea of all this video using up WiFi bandwidth and CPU when nothing is happening. Makes me wonder if there’s some other open source software that can use the intermittent RTSP feed Eufy also offers only for motion events. But if I wanted to customize the object detection or do more fancy video analysis, Frigate definitely seems like a nice tool.

mqtt:
  enabled: false
cameras:
  sf4:
    ffmpeg:
      hwaccel_args: preset-vaapi
      inputs:
        - path: rtsp://usernamepassword@192.168.0.252:554/live0
          roles:
            - detect
            - rtmp
    detect:
      width: 1920
      height: 1080
      fps: 5
    record:
        enabled: True

detectors:
  ov:
    type: openvino
    device: CPU
    model:
      path: /openvino-model/FP16/ssdlite_mobilenet_v2.xml
model:
  width: 300
  height: 300
  input_tensor: nhwc
  input_pixel_format: bgr
  labelmap_path: /openvino-model/coco_91cl_bkgr.txt
version: 0.14

No landline for a month, is great

A month ago I turned off my AT&T landline and ported the number to NumberBarn. Couldn’t be happier. No more junk calls! Voicemails delivered to my email! It’s great. Can’t believe I wasted $100/mo on that horrible landline for so long.

Numberbarn has been fine. I wish it had more features. I just noticed today they don’t display any names in the caller ID info on the caller log, just the number. (CNAM, they call it). That’s too bad. Often the text info is pretty bogus but that’s a signal of its own kind, legitimate businesses identify themselves.

I don’t get a lot of spam voicemails. Maybe 50% of the 10 or so voicemails in the last month have been spam. 95% of the calls would have been, so that’s a big improvement. I suspect most of the fraud companies just hang up when they recognize it’s an answering service.

Ken pointed out one hassle with not having a landline; we don’t have wireless phones all over the house. Now if I want to call him I have to call his cell phone and hope he didn’t leave it in the kitchen where he can’t hear it. I can think of ways to fix this but they’re all pretty awkward and it’s not that big a deal.

I still have a landline in the other house. We may try porting that number to my ISP; Sonic.net bundles phone service I’ve never used. I’d get rid of the idea of a phone for the house entirely but Ken still likes it there for some reason. At least I can save some money.

AT&T cancelled my account as soon as the number was ported and prorated the last month’s bill without me ever having to ask. So that’s one worry settled.

OTOH AT&T also gave me a nasty little reward for being a customer for so long. A massive data breach dating back to 2021. They’re telling the press they have no idea how this data could have been leaked, not the reassurance their PR person is hoping it is.

Landlines and VoIP phone services

I’m fed up with my landline. I pay $100/mo and all I get are fraud calls and politicians asking for money. My Grass Valley number doesn’t even work reliably; crappy wiring and an unreliable AT&T VoIP setup that fails during power outages (in violation of their obligations). It’s long since stopped being POTS over copper.

So I’m doing like the young people do and ditching the landline. But I need the old number to work. So I’m porting it to a VoIP service. The other choice would have been to port to a second number on my cell contract, but I don’t want my cell ringing with scam calls every day.

I picked Numberbarn to port the number to. Other choices were Google Voice or Callcentric. But Google Voice looks creaky and on the verge of being abandoned and also can’t directly port a landline. A friend uses Callcentric but I didn’t try it. Honestly NumberBarn had me with the cute pig logo.

Numberbarn has a nice looking product. It’s clear what their business is: selling phone numbers for marketing purposes, they list vanity phone numbers at $1000 and up. But they have a significant sideline in helping people cheaply park phone numbers they don’t really use. Also simple voicemail, call forwarding, and phone menus.

I was particularly impressed with Numberbarn’s help pages, a set of clear marketing-free descriptions of how to do things you’d want. Their how to port in page is as clear as could be. They have symmetric porting out docs too, an easy process. A sleazy company would try to make it hard to leave their service.

It’s cheap too. $2/mo for basic parking, $6/mo for voicemail, fancy forwarding, menus, etc. I need the voicemail so I’m paying $6. It has a voicemail-to-email but audio only, no text transcription.

Porting

I’m porting an AT&T landline. The process is shockingly simple. I just sent Numberbarn a copy of my phone bill and it was approved nearly immediately, then took three days to actually happen. It happened just as predicted and now the phone is answered by Numberbarn’s voicemail. Easy peasy.

A little surprised by the security of that. Cell phone porting became a big problem with all the hacking of SMS authentication, so they tightened security and added a required PIN to port a number. It looks like anyone with a copy of a landline bill can steal the number. It may be the equivalent of a PIN is just printed on the bill.

Another authentication option was for them to call my number and me to relay a security code. But since my AT&T line isn’t even working at the moment, that was not an option.

Cancelling AT&T

This is going to be the hard part. I’ve already tried the website and a customer support call to cancel and had a terrible experience. AT&T can’t look up that number at all anymore, all they can tell me is that the phone number belongs to “Bandwidth”. I see some hints that Bandwidth may be another name for Numberbarn but I’m not certain.

With any luck AT&T will simply stop billing me now that the number was ported, but I’m not hopeful. I’m now taking meticulous notes for the inevitable PUC complaint.

Update: Numberbarn support replied swiftly and thoroughly and confirmed that Bandwidth is their carrier. Also they suggested AT&T might automatically cancel my bill. Fingers crossed.

Update 2: about a week later I noticed that att.com is showing “Canceled” on my old landline. I can’t find any more information on the website, just a bunch of irrelevant ads in the Notices section, but at least that’s a sign that I won’t be billed for further service.

TCL Roku vs Plex subtitles

Finally fixed an annoying problem where Plex subtitles wouldn’t show on my TCL TV (which runs Roku OS).

The solution is in the TCL TV settings, under “Accessibility / Captions mode”. Set it to “Off” (or maybe “On Always”). If you have it set to “On replay” or “On mute” then the subtitles Plex puts in a subtitle stream for the TV won’t display. (I suspect the TCL setting is overriding the stream.) I found this solution here.

There’s a different solution I found on Reddit that no longer seems to work. That has you setting the Plex app settings, to turn subtitles to “Roku captions mode”. Despite the Plex support docs describing this, my Plex app (version 7.14.6) does not have a Settings menu at all.

A third workaround is to tell Plex to “burn subtitles always”. But that has the server transcode the video and render the subtitles into pixels on the video stream. It’s much better to have Plex send a separate subtitle stream and let the TV do the rendering.

EV Charging Curve

Electric cars charge more slowly the closer the battery is to full. This response is called the charging curve. I was confused about what I was seeing and was wondering where the power goes if it’s not charging the battery. Turns out it’s never consumed in the first place: the car requests less and less power as the battery gets full.

Level 3

Level 3 DC chargers dump a lot of power fast into the battery. This forum discussion from May 2022 has a graph of the charging curve for the C40 and the XC40.

This graph shows charging power going from 150kW down to 50kW as the car charges from 10% to 80% in more or less a straight line, then further down to 25kW or so at 90%.

Level 2

Level 2 AC charging at home is providing a lot less power, 10% or less the wattage of Level 3 (typically). Here’s the curve going from 80% to 90% as measured by my Emporia home charger.

This shows charging power going from 9.2kW to 4.4kW. The drop started when the car was about 95% full and is not instant but ramps down over the course of 5 minutes or so. (The graph looks identical for amps.)

What seemed weird to me is that the Level 2 power draw stays at 9.2kW (38 amps) pretty much all the way up to 95%. I was expecting it to ramp down like the Level 3 does. But I guess the Level 2 power is so much less than the Level 3 power that isn’t necessary.

What also seemed weird to me is I thought on Level 2 my car charged faster going from 40–50% than from 80%–90%. But it’s drawing the same 9.2kW, so where was that extra power going? But I realize now I don’t really have a good measurement of that. I’m just eyeballing the time. And those battery percentages the Volvo reports are not particularly accurate measurements of how much power is actually stored in the battery.

I still don’t understand the underlying physics and chemistry of what’s going on to make charging slower when it’s nearly full. My hand-wavy explanation is the resistance on the battery goes up, so if you try to force too much current through a nearly full battery it gets wasted as heat instead. (Or worse, starts a fire). So the charging circuitry only requests as much power as it can safely put into the battery without overheating it. I think this is all some fairly complicated digital control logic but maybe it’s as simple as a circuit that responds to resistance.

Anyway for Level 2 the charging curve effect is pretty negligible. And not visible at all if you only charge your car up to 90%, as recommended. It’s more important at a Level 3 charger but the systems take care of it automatically for you.

Android Automotive vs Android Auto

Quick notes about Android Automotive Operating System, AAOS. I like it quite a bit. It’s part of why I bought the Volvo C40 Recharge.

AAOS is an Android-based operating system for cars. As the owner of a car, what I see is that I now own another Android device in addition to my phone and tablet. It has a different UI but it works like Android. I can install custom apps on it. And the default apps are quite good. Google Maps, of course, but a special version with EV charging info built in. Even better it integrates with my car’s systems so Google Maps can, say, look at my battery charge and help me plan a route. It also has Android apps for controlling the air conditioning, etc. AAOS mostly is visible on the car’s central display but it also integrates deeper into the car systems and the dashboard display.

Car software generally sucks. AAOS doesn’t, it mostly seems good and modern and not some OEM nightmare.

AAOS is different from Android Auto. Android Auto lets you mirror your Android phone’s display onto a car screen. Apple’s CarPlay is the equivalent thing for iOS. My C40 supports CarPlay but not Android Auto. I think they decided that Bluetooth integration with an Android device, plus maybe a little OS support to bridge things from the phone, was enough. I’m happy that calls, text messages, and media playing still work fine from my phone. But mostly I just run Google Maps and Spotify on the car itself.

GM/Chevy recently made the news that they were dropping support for both CarPlay and Android Auto in new cars. They’re adopting AAOS instead. That’s weird; AAOS can support the display mirroring mode. Dropping CarPlay seems like a real mistake, folks in Apple’s ecosystem are going to miss it. Also the press release suggests they’re doing this because they want subscription revenue; they can’t charge you if you’re just using your mobile phone to control the car. That sucks.

There are fewer AAOS apps that Android Auto apps. And both systems require extra work to support by app developers, a separate UI and affordances to not distract the driver. Here’s some developer info about AAOS apps from Google.

In practice I find the apps I want for my car are on AAOS. PocketCasts, Spotify, PlugShare. It even has YouTube and a web browser (only usable when the car is parked). Strangely A Better Route Planner is not on my C40. They do have an AAOS version for Polestar, not sure what’s going on there.

Home EV chargers simplified

I was confused about what I’d need for a charger at home for my EV. It’s far simpler than I realized. Lots of notes here specific to North America. Simple summary: get an electrician to install a new 50 amp circuit with an NEMA 14-50 outlet on it. Then use your car’s provided charger or buy a high quality charger like a Chargepoint Flex or an Emporia for about $500. You’re done.

Here’s lots of detail I’ve learned in the last week or two. Shoutout to Reddit /r/evcharging and in particular this wiki page and this post. They have useful if opinionated info.

How AC charging a car works

I’m only talking about Level 1 & 2 charging you do with AC power from a wall outlet. I’m ignoring Level 3 charging: that’s high power DC stuff you’re not doing at home. With AC charging everything from the wall outlet to your car plug is just to supply AC power to your car. It’s mostly just a wire; all the fancy stuff is happening in the car itself. The thing we call “a charger” on the wall with the plug is doing so little that “charger” is not really the right word. The Reddit nerds prefer the term “Electric Vehicle Supply Equipment” (EVSE).

Most EVs today use a J1772 plug that is carrying +120V, -120V, and ground to your car. It’s mostly a fancy extension cord. There are also two signal wires: one is used to detect that the cable is plugged in, the other is a simple protocol that tells the car how many amps max it can draw from the charger. Providing those signals is the only extra necessary thing an EVSE is doing.

Tesla has a different plug, the NACS plug. And starting in 2025 all North American EVs will use this plug instead. I don’t know details but NACS is enough like a J1772 that adapters are simple and cheap. During the NACS transition we’re going to be using a lot of those adapters.

Note that EVs have a charging curve: batteries charge slower and less efficiently the more full they are. Details are complicated and vary by charging source and car type. But all EVs charge better up to 80% or 90%; that’s part of why they all recommend not charging to 100%.

Level 1 and 2 charging

Level 1 charging is powered via a plain old plug, 110V AC and an ordinary NEMA 5-15 outlet providing 15A maximum (12A in practice). That gets you about 1.3kW and will take about 3 days to fully charge a typical EV with an 80 kWh battery. Everyone scoffs at how slow this is but can actually be useful if you’re charging in your garage and don’t drive much. Don’t write it off entirely!

Level 2 charging is also powered by a plug or can be hardwired. It’s higher power: 240V AC and often a 50A circuit. These high power circuits use a special plug. A NEMA 14-50 is common and typically will get you about 9kW, that 80kWh battery can be charged overnight. If you already have a 240V circuit in your house you can still use it even if it’s lower power or a NEMA 6-50 outlet. Level 2 is what people install in their homes.

Installing a power circuit

Unless you are lucky you probably need to install a new circuit in your house and that will require an electrician and maybe a permit. Go ahead and install a 50 (or 60) amp circuit, it won’t cost much more. And install a NEMA 15-50 outlet for the extra neutral wire. All this takes a few hours. I had no problem adding a 50A circuit to my 100A house power supply but houses with funky wiring, who knows.

The folks on /r/evcharging prefer hardwiring instead of a socket. It eliminates one point of failure, the need for an outlet, and possibly a GFCI breaker. On the other hand it means you need an electrician if you ever replace your charger, or at least do some tricky wiring. I chose the plug. Also there’s a question whether the common Leviton 14-50 outlets are up to the task of continuous high power draw for EV charging. I decided it’d be OK.

One weird thing is that for continuous loads, you’re only supposed to go to 80% of maximum rated power. See here or here for details. A 50A circuit should only actually have a 40A charger plugged into it. That 14-50 plug is also max 50A, so plug-in chargers stop at 40A. Hardwired will go to 48A because the plug is not a point of failure, although you will need a 60A circuit and breaker for that.

Choosing a charger (EVSE)

The EVSE does so little it seems unnecessary to spend a lot of money on one. Your car probably came with an adequate one and it may be all you need. The main distinguishing factor of particular EVSEs is a bunch of fancy scheduling and tracking software which are really not necessary. Your car probably can schedule charging itself. The tracking is not terribly interesting.

However: that charger is in your house. With a lot of power passing through it. This is not the place to cheap out on dodgy goods. Amazon is full of generic $200-$250 level 2 chargers that are not UL certified. They probably work fine but what if they set fire to your house? In the end I decided to pay more like $400-$600 for a trusted brand with UL certification. Almost all of them come with fancy software which you might then just ignore.

The evcharging wiki has a good set of recommended charger brands. I narrowed it down to three that had a plug version and were available on Amazon: Autel, ChargePoint, and Emporia. All UL certified, $400-$500 (on sale), well reviewed on /r/evcharging. I also liked the look of the Flo dumb charger but it’s hardwired only.

In the end I chose Emporia, mostly because it was the cheapest. And while I think the smart options are superfluous Emporia has an interesting suite of smart home electricity products. Including an energy monitor and a way to schedule the car to charge when your solar system has surplus power. I’m not using any of that now but I liked what the company is doing.

Conclusion

In the end it’s pretty simple to set up an EV charger at home. Running the circuit is the only hard part. You know what’s great? Never waiting in line at a gas station again. Having your car fill itself up every night when parked at your house.

Genie Pro Screw Drive remote programming

Got a new car with HomeLink and paired it to my garage door’s rolling code. Worked great! But then Ken’s HomeLink he programmed last year stopped working. We reprogrammed his, then mine broke. Did mine again, his broke. All through this a simple battery clicker kept working.

A trip through the manual informed us that this particular model can only pair with 7 transmitters. They don’t say what happens when you try to program an 8th but it seems to be a LIFO system, the last one obliterates the previous one. (Me, I would have guessed FIFO and the ancient 1st code would stop working. But that’d probably be the battery clicker that came with the device.)

The manual also told us how to reset the thing so it had no codes programmed: hold the button for 10 seconds. So we did that, then reprogrammed all 3 remotes, and all 3 work now. Hooray! I am glad I had a Theory of Mind for my Genie.

See also this earlier post about various options for garage door opener communications.

Charging a non-Tesla at a Tesla charger

Tesla runs a great charging network. Actually two charging networks: the Superchargers are the crown jewel with fast Level 3 charging but there’s also Destination Charging which is a network of power Level 2 chargers that are prevalent. You can use some of these in EVs with J-1772 + CCS plugs but it’s awkward right now. It’s getting better since the agreement on NACS and the transition is going on. In a few years we’ll all be using Tesla-style plugs (now called NACS or J3400).

Here is a map of Tesla chargers that can work with non-Tesla cars. It includes both “Superchargers open to Non-Teslas” and “Destination Charging”.

Access to Tesla chargers is via the Tesla app. Destination Chargers are often free, paid for by the business and/or Tesla. (Free is customary for a lot of J-1772 Level 2 chargers, too.) But now destination chargers can take money, too. I think Superchargers have always cost money although Tesla sometimes offers free charging as an incentive to Tesla buyers. For non-Tesla cars they cost about $0.50/kWh in California, or about what Electrify America is charging. Cars typically get 2.5-4.5 miles per kWh so this costs about about $0.15 a mile, or roughly the same as gas costs.

Level 2 / Destination Charging

The first trick is plug compatibility. You have to bring your own adapter for a J-1772 car, you are unlikely to find one to borrow at a Destination Charger. Amazon is full of “Tesla to J1772” adapters for about $80 that physically connect the two types of plug. I think these are relatively simple devices but there’s a locking mechanism and maybe a little signaling. These adapters will only work with LTesla’s Destination Chargers, not Superchargers.

The second trick is electrical compatibility. I think this just works. Level 2 charging is basically just providing AC current for the car to deal with, the car itself chooses the amperage and charging schedule. So it’s relatively easy. Most of the Tesla adapters I see promise 40 or 48 amps which is about the max level 2 you’re likely to see. A few specify 60 amps. In my car at least, I have to manually select how many amps to draw (Update: that may not be necessary).

The map shows several hundred Tesla Destination Chargers in California. Only one in Grass Valley.

I used one of these Tesla chargers for free in March 2023 in Florida. Worked fine and Hertz had provided an adapter with my rental Polestar 2.

(Interesting thing: J-1772 to Tesla adapters are half the price of Tesla to J-1772 and are much smaller. I think this reflects that in general the J-1772 connector is bulkier and more complicated. I wonder if that’s part of why the auto makers were willing to adapt the Tesla plug. Amazon has a few cheaper adapters but they look like scams with fake reviews.)

Level 3 / Supercharging

Plug compatibility for Level 3 charging is via Tesla’s new Magic Dock. If you tell the supercharger you’re not in a Tesla, it will unlock an adapter to J-1772+CCS that will work with your car. (The “magic” is that the adapter stays locked to the cable so you can’t take it away.) The Magic Dock is something of a temporary solution as NACS rolls out. Tesla is incentivized because it will get billions of dollars in federal subsidies for providing CCS compatible chargers. Good, that’s the subsidy working, assuming the Tesla Superchargers do function as promised. Musk sure is good at capturing government subsidies, it’s a feature of all his businesses.

I don’t know anything about electrical compatibility. I believe Level 3 requires significant negotiation of charging power. Presumably the Tesla charger speaks whatever software protocol CCS uses. I wonder what the endgame is after NACS is fully rolled out; will there be one protocol standard or two?

The map shows exactly two Superchargers for non-Teslas in California: one in Placerville and one in Scotts Valley. Both are charging about $0.50/kWh.

Commentary

Tesla has done a fantastic job building out a fast charging network. There are Superchargers in lots of places, they work well, and often they are pleasant places. They have a mature product with memberships, incentives, and mechanisms for third party billing (like a car rental). And their plug and cables are lighter and easier to use than J-1772 + CCS. I’m glad they won the standards war.

I hope we get a robust market of competing Level 3 NACS chargers. It will make a huge difference in Americans’ willingness to switch to an EV. I keep hoping someone figures out a business model where the charger is a destination. It might take 30 minutes to fill up but if you know you can get a good coffee or some decent tacos and the WiFi works, that’s not so bad.

Volkswagen sure shit the bed with Electrify America. That could have been a real competitor to Tesla’s Supercharger, making lemonade from their emissions fraud lemons. But instead of embracing the opportunity they did a bad job building a charging network. There’s lots of chargers, sure, but they are always broken. Also the Walmart parking lots they tend to be in are not exactly lovely. And their website and app are badly implemented. In general it’s just a poorly executed product. Opportunity missed.

The web is full of spam when you look for info on Tesla and charging. Zillions of websites with wordy low quality content farm articles, presumably partly AI written.

PG&E rates and EV charging

I’m about to get an electric car so I’m looking again at what I pay for electricity. Up to 54¢ a kWh! We have some of the highest electricity prices in the world. Also some of the most unreliable power for a supposedly advanced nation. And occasionally PG&E’s negligence kills some people or a whole town.

I have two houses and a full panoply of rates I’m paying. It’s remarkably hard to find the actual rates on the website or in your bill but this PDF has an overview of the common residential plans. Also the rates are hard to understand. There’s two tiers: a “baseline” and then overage. I’m only looking at overage prices. Also prices may vary based on time of day or season of the year. In total I use about 7000 kWh a year in San Francisco and 17,000 kWh a year in Grass Valley. There’s solar in GV that gets me to about net zero for that house on a yearly basis.

I’m mostly interested now in what it will cost extra to charge my car. I’ll only charge at night. I’ll be paying fully the higher tier pricing for the incremental extra electricity. I’m guessing I’ll use about 3000 kWh a year (or 13% more) for the car. Because of how the NEM 2.0 rate plan works there’s no advantage to me charging directly from my solar: PG&E credits me fully for everything I give them.

In San Francisco I’m on the old E-1 plan. There’s no time of day or seasonal adjustment. I’m paying 45¢ for past-baseline power. My car will be charging at 45¢/kWh.

In Grass Valley I’m on the E-TOU-C plan. (I also have solar under NEM 2.0, but that can be ignored here.) Power is more expensive from 4pm to 9pm, and for the four months of summer. Past baseline, prices are 46¢ to 54¢ in summer and 41¢ to 44¢ in winter. My car will be charging at an average of 43¢/kWh.

PG&E has a second time of use plan, E-TOU-D. It discards the baseline discount, has a shorter time window for peak pricing, and has lower average rates. My car there would charge at about 39¢/kWh. I think my overall bill would be higher though.

PG&E also has a EV2-A rate plan for electric vehicle owners. It’s significantly cheaper from midnight to 3pm (26¢) but then 43-57¢/kWh during late afternoon and evening. The car would charge at 26¢/kWh but the rest of my bill will go up. Too early to tell if it’s a net improvement for me.

Bottom line, if I charge the car 3000 kWh a year I’ll be paying about $1350 a year just to charge the car at my current rates. Which is just about what I pay in gas right now for the old car. If I switch to the EV2-A plan I might save $600 charging the car, but then the rest of the bill will go up and I’m not sure how much.

Update: in Jan 2024 the CPUC gave PG&E another eye-watering rate rise. Here’s an estimate of new rates (I think)

  • E-1: 53¢/kWh
  • E-TOU-C plan: 46¢/kWh
  • E-TOU-D: 35¢/kWh
  • EV2-A: ???

PG&E (or rather Opower) has a “find your best rate plan” that re-runs your old bills through each pricing plan and tells you what you would have paid in each plan. It’s not useful to me right now, but might be useful after owning the EV for a few months.

Hot water recirc energy cost

I have recirculating hot water and a gas hot water heater. It’s very nice having instantly available hot water! I always wondered how much propane I’m wasting pumping warm water around the house.

0.9 gallons a day, or about $60/month. Or 4x the propane I’d otherwise use in summer. (In winter I average around 6 gal/day for heating.)

In detail: I went out of town for a couple of weeks and unplugged the recirc pump. The average usage then (from Sep 23 to Oct 12) was 0.2 gallons. A month earlier it was 1.1 gallons. The low period had the hot water heater turned on, but no recirculation wasting heat. Also no gas cooking or actual hot water usage so not all of that 0.9 is attributable to the recirc loss. (And no furnace heat at all for any of this.)

I used to use a timer to turn the recirc off at night but it stopped working and I wasn’t sure the savings was worth the bother. I guess it was! My long term solution for this is to get a heat pump hot water heater which should be more energy efficient and avoid burning CO2. Some folks use instant hot water heaters at the point of use but I don’t think that’d work for me.

Eufy RTSP stream

I have a Eufy IP camera, a cheap $35 Security Solo IndoorCam C24. It does support RTSP but it’s not easy.

To get it working, I had to use the mobile app and get to the settings for the camera. Then open General / Storage / NAS (RTSP). The setup flow talks all about a Synology NAS which is confusing, the docs say that’s all that’s supported. But really what they mean is the Synology RTSP client is the only one they want to answer questions about; it seems to work with any RTSP client, including VLC.

Anyway, you go through the flow and the end result is you are given a stream link. It’s of the form rtsp://username:password@192.168.###.###/live0. It generates a random username and password and claims it’s doing digest security.

RTSP support seems hit or miss with Eufy. Not clear which all devices have. Also they’ve disabled or broken it in the recent past, judging by Reddit discussions. Maybe in response to one of their many security disasters. Anywat this particular “Indoor Cam 2K” works, with firmware version 2.1.8.7.

Eufy apparently does not support Onvif.

Also Eufy is a bad product and should probably be avoided. They were recently caught sending images to the cloud even when the camera was explicitly configured not to do that. That’s not just an honest security mistake, that’s some product manager making a decision to harm their users. It speaks badly of the company. Too bad, it’s an Anker product and works pretty well. I generally like Anker!

AAA and AA batteries

I started using rechargeable batteries about 15 years ago, when Eneloop batteries were the new hotness. Some of those old batteries no longer hold a charge. Also I got more interested in how they work. Some details, mostly about AAA batteries. AA batteries are very similar but have about 2.5x the capacity.

Old fashioned disposable AAA batteries are typically Alkaline chemistry. They’re nominally 1.5V and store about 1000mAh of power, so 1.5Wh. This is what Duracell sells you.

Most rechargeable batteries these days are NiMH. (NiCd are obsolete.) These are nominally 1.2V and about 1000mAh, so 1.2Wh. Capacity varies 20% though; Amazon Basics sells 850mAh. I recently bought some Tenergy batteries which are supposedly 1100mAh but actually 1000 when measured. Wirecutter has recommendations for other brands.

There are also Li-ion AAA batteries. The cells are 3.7V, so these come with a small transformer built in to get the power down to 1.5V. These seem to be sold as 1200mAh, so 1.8Wh of power. A lot of stuff I’ve read suggest NiMH batteries are better for most AAA applications but I don’t understand why, something about load patterns and battery longevity.

A typical set of 4 AAA batteries is about 5Wh of energy, or under a penny worth of electricity. Compare 10-15Wh in a cell phone, or 65Wh in a laptop.

Note the difference between 1.2V and 1.5V depending on battery chemistry. This doesn’t matter for many applications, I guess the power circuit isn’t that sensitive or smooths it over. The voltage also drops as the battery discharges but NiMH has a pretty flat curve for most of its duration. Li-ion batteries put out a steady 1.5V, presumably because of the transformer built in.

Batteries wear out over time. NiMH AAA batteries are typically rated for 500-1000 cycles. But the reality of batteries is they seldom have such nice clean full-to-empty load placed on them so the actual lifespan is shorter. I think the batteries I’m throwing out probably were put in a charger about 100 times at most.

Fancy battery chargers like this old one have a couple of nice features. One is variable charging power; it’s better for the battery to charge more slowly. Another is a “Charge Test” mode; it charges the battery to full, runs it down to zero, then charges it to full again and measures how much charge it actually holds. That’s how I figured out which batteries to throw away, the ones that didn’t hold more than 600mAh anymore. The charger also has a “refresh” mode where it cycles the battery repeatedly hoping to make it work better. I’ve tried using that in the past and it seemed to help but not be worth the bother.

Shelly heat/temperature + Grafana

I bought a little Wi-Fi thermometer, a Shelly H+T. Neat product; eInk display, wifi, runs on 4 AA batteries for a year. I don’t know much about Shelly but it seems fairly hacker friendly. In particular you can run the thing in local network mode and not use their cloud service at all.

Setting up Shelly

First challenge was getting the device up and running. The docs are good and there’s several routes. I went the WiFi only route (no Bluetooth); you plug the device in, get it into AP config mode by holding the reset button in the battery compartment. It creates a WiFi network for itself and runs a web server on 10.33.1.1 which you can then use to configure it. You have to work fast; even plugged in to a USB power source it seems to only want to run for 30 seconds before going in to sleep mode. The main configuration required is to tell it your wifi network details to connect to your LAN.

First step after that was to flash the firmware. Glad I did, they completely changed everything. Next step was to configure it to do something useful. Because it’s low power you can’t really poll the device, most of the time the WiFi is off. So instead it wants to push data.

Shelly is remarkably sophisticated and has a lot of thoroughly documented connection options. I chose MQTT with their default settings because it seemed the simplest path.

Setting up MQTT

I’m not a fan of MQTT, it’s too complicated. But it is a standard and there are tools. I found this guide helpful in getting started. It has you installing mosquitto for a MQTT server (“broker”), mosquitto-clients for testing, then setting up telegraf to be an MQTT listener for data logging to influx and thus Grafana.

mosquitto takes some config; by default it will only listen on localhost. You have to configure authentication. I used a simple username/password, probably “no auth” would be fine on my LAN too. Note this configuration has to occur before a line like listener 1883, defining which mqtt instance you’re setting up. (See what I mean about complicated?)

Then I pointed Shelly at the MQTT broker (no SSL, port 1883, username and password) and.. nothing. There’s a log file in /var/log/mosquitto but it didn’t have much useful in it. So I added connection_messages true to the configuration and then I could at least see that Shelly was connecting. No data logged to a file though.

To get the data you have to use mosquitto_sub to subscribe and listen to the data. There’s a concept of “topics”, which kind of events you listen to; # is a wildcard. You can also use mosquitto_pub to send test messages. Honestly to figure all this out I asked ChatGPT how to use it and it told me. Way easier than reading docs and it happened to work this time. (ChatGPT failed later producing telegraf configs.)

With all that set up I got Shelly logging overnight. It seems to log to two topics: shellyplusht-b8d61a8b17cc/events/rpc and shellyplusht-b8d61a8b17cc/online. The useful data is in the RPC.

The important RPC payload is a JSON blob method named NotifyFullStatus and a wakeup_reason of status_update. The data itself is in params and the key thing is data blocks for temperature and humidity.

Not clear on update frequency. When it was plugged in I was getting updates every 305 seconds or so. There was some status indication that suggests it wants to update every 600 seconds; I guess 300 is when it starts trying and the extra 5 is getting wifi online? On battery it updates less often, I think only when a measurement changes significantly. There’s a setting in the firmware where you can make it wake up for every change of 0.5°C or 1% humidity.

Anyway, Shelly is working and publishing to MQTT. Now to get the data somewhere useful.

Logging to Influx

Telegraph can take input from MQTT. It took some levering to get this working but I finally got telegraf to just store all the fields that are in the JSON data blog from Shelly. Here’s the config:

[[inputs.mqtt_consumer]]
  servers = ["tcp://127.0.0.1:1883"]
  topics = ["shellyplusht-b8d61a8b17cc/events/rpc"]
  username = "shelly"
  password = "hunter2"
  data_format = "json"
  # json_time_key = "params.ts"
  # json_time_format = "unix"
  tag_keys = ["method"]
  json_query = "params"

This logs all RPC messages from shelly; the useful ones with data but also other RPCs. It also logs all the measurements, many of which are not so useful, but it’s just easier this way and it’s only logging every 5 minutes at most.

Note the commented out date parsing. I’m sure I got that JSON key name right but telegraf couldn’t find it, at least in some of its inputs. I gave up. Instead telegraf will log with its own timestamp rather than the one Shelly reported. That’s OK most of the time but if Shelly buffers any data and uploads it in bulk it will be a problem.

Also the “tag_keys” seems to be useless. I was hoping to use influx tags to filter just on the NotifyFullStatus responses and not the other junk. No idea why but it’s not ending up in the database.

I probably should have tried json_v2 as the telegraf parser.

(An aside on testing telegraf with systemd. systemctl reload telegraf does work but sometimes delays, I think telegraf waits until the agent finished its last run. journalctl -f -u telegraf is a useful way to watch the telegraf log file. Shelly only logs every 5 minutes so it’s a slow process of testing.)

Calibration

A man with two clocks never knows what time it is. None of these devices are precisely calibrated so I don’t know for sure what’s right. Shelly has an option in the firmware to add a static offset for calibration so I can at least get it to line up with the Laseregg.

When I first was using it, my LaserEgg said 70.5°F, Shelly said 72.7°F. A Taylor thermoprobe (for cooking) says 71.5°F (both air and a glass of water). In general the Shelly is reading 2-3°F more than the LaserEgg and 2% less humidity.

But then I put Shelly in the fridge for 10 minutes, and it dutifully read colder. Then I took it out. Now 12 hours later Shelly and the LaserEgg are basically reading the same without me putting in a calibration offset at all.

Graph

Here’s 24 hours of my far-too-complex set of graphs of Shelly data. Top two are calibrating temperatures between Shelly and the Laseregg, bottom two are status just from Shelly. The weird dip in temperature is when I locked Shelly in the fridge

LED bulbs, Waveform Lighting

After last week’s article about LED lighting quality I noticed a lot of posts in the Hacker News discussion were praising bulbs from Waveform Lighting. So I ordered some to try. But they look too blue and I will be returning them. I’m flummoxed by LED lights now and am thinking I need some fancy color-tunable bulb.

Waveform Lighting sells high end LED bulbs: $18 for the typical A19, compare $3 for a basic Feit bulb from Home Depot. Waveform bulbs are supposedly better. A higher CRI (95 vs 90), a better spectrum beyond what CRI measures, and no flicker. Their website has a blog with a bunch of excellent semi-technical posts on it explaining what they do and why. I’ve been wanting high quality bulbs for awhile and they have a generous return policy, so I ordered some 3000K BR30 floods for my office / TV room.

They’re too blue.

When I turn them on low at night the room looks very blue. Way bluer than the old incandescents, which I expected. But also bluer than the 3000K Feit PAR30s I use. Nominally the Waveforms and the Feits have the same color temperature design; weird! The Waveforms also look too blue on a cloudy day. On a sunny day I don’t notice as much, presumably because the sunlight washes everything else out.

What’s weird is the measured color temperature of the Feit bulbs and the Waveform bulbs is the same. I measured this with an Android app. I didn’t calibrate the app so I don’t trust the absolute numbers, but the relative comparisons should be meaningful. The Waveform LED bulbs measured 4000K at all dimness levels; so did the Feit LED bulbs. The incandescents measured 3400K-4100K depending on dimmer setting. Those numbers are all about 1000 too high (calibration?) but otherwise plausible.

So why does the Waveform light look bluer to me? My only thought is it’s in some detail of color accuracy, that the Waveforms fill in more bluer spectrum than the Feits. I don’t have a way to measure that. But I know how it looks to me. The good news is I like the cheaper bulbs more! So that’s money saved.

Update: after a day or two with both the Waveforms and Feits in the same room I no longer think one looks bluer than the other. They seem a similar color temperature to me now. However there’s definitely a difference of some kind in color between the two. I can’t describe it and one doesn’t look better to me than the other. The room with both lights feels a bit cold / late night convenience store for me. It’s not objectively true but my subjective vibe is more “fluorescent lighting” than “candles”.

Desired color temperature

I think I’d prefer the Waveform bulbs in an application where they were turned on during the day to, say, light an office. I believe their claims the colors are more accurate.

But this is a room where I either stare at a computer screen during the day (don’t much care about the ceiling lights) or watch TV at night (want cozy dim lights). I think what I really want is a light that turns redder towards 2700K at low dim settings, them up to 3000K or maybe higher at full brightness. Philips sells “warm glow” bulbs that are exactly like that. But it’s not clear that’s a viable product. Now I’m contemplating programmable smart bulbs of some sort.

It’s funny, when I first learned about LED bulbs I was sure I wanted true sunlight 6000K bulbs. It’s natural! Turns out, at least in the west, we’ve all learned that cozy indoor lighting looks red like a fire glow. I put some 4500K bulbs in my shower and they look just terrible to me on cloudy days, like cheap fluorescents.

Other Waveform thoughts

I really wanted to like these Waveform bulbs. I’m happy to pay for higher quality!

They are good heavy bulbs. I take that as a sign they have a serious heat spreader.

I didn’t get any sense for flicker. I’ve never noticed flicker in any LED bulb.

I like the lens on the BR30s. The surface of the bulb is a smooth glow, not like the visible points of light in the cheaper Feits.

The Waveforms take about half a second to turn on after flipping the switch. Not a huge deal but it seems weird.

I’m testing with a 20 year old Leviton incandescent dimmer, which is not correct. The Waveform mostly works with it, but the minimum dimness is too bright. Also there’s a quiet buzz coming from the bulb at low dim levels. Both of those problems would probably be fixed with a proper modern LED dimmer. I’ll note the cheap Feits work fine with the old dimmer; another cost savings.

Renting an electric vehicle

I had my first real experience with an EV these last two weeks, renting a Polestar 2 from Hertz to drive around the Ft. Lauderdale area. It was great! The Polestar 2 is a nice car, a comfortable sedan, more or less a Volvo S60. It’s a competitor to the Tesla Model 3 or maybe Model S. I miss the car and now wish I owned one! I used this as an opportunity to learn about how EVs work, these are my notes. I also posted about it as I was going on Mastodon.

Charging

The question “how do I charge this car?” almost stopped me from renting an EV. I’m glad it didn’t! It wasn’t as easy as filling up at a gas station but it wasn’t hard, and the free electricity + parking you get as a perq in some places kind of made up for it. There was a learning curve though, the variety of charger types is confusing. Hertz didn’t have much useful information for me.

The car has a 78kWh battery and about 220 miles of useful range. It uses 0.32kWh of electricity per mile. I was staying entirely in the urban area between Ft. Lauderdale and Palm Beach, so no experience of long distance trips far from chargers.

The first thing I learned about is the difference between slow, fast, and rapid chargers (or level 1, 2, 3). Slow / Level 1 is what you get with an ordinary AC socket, which in the US tops out at 1.5kW, so you’re getting 5 miles per hour of charging or 40 miles overnight. Not useful, I never did it. Fast / Level 2 is higher power AC, typically around 8kW. These are the ubiquitous chargers you see in parking garages, etc, and are often free. (See the green markers in the map above). It’s also what you’d have in your home. Fast charging is more useful; picking up 25 miles in range while having lunch for free is nice. But for a real fill-up you need a rapid charging station, a destination facility like a gas station. See the orange markers above. These have 50-150kW chargers and can fill a whole battery in under an hour.

Rapid chargers are what you need when far from home. There are not nearly enough of them, particularly between cities. And a typical location only has 3-6 chargers, each one occupied for up to an hour at a time by other cars. Also often several chargers are broken, none of these facilities are staffed and seem to be out of service for days at a time. Electrify America is one common brand, and expensive! But frequently found at Walmart locations. My favorite was an FPL Evolution charger in Wilton Manors, conveniently near a store and a good coffee place.

The other confusing factor is charger compatibility. There’s basically two options: Tesla and everyone else. In the US newer non-Teslas use the J-1772 connector at fast chargers and a J-1772/CCS combo at rapid chargers. Voltage and power are auto-negotiated. My Polestar had an adapter that let me charge with a Tesla fast charger and I think there’s some work towards making Tesla rapid / superchargers work with other cars, too.

EVs don’t want a full charge; it’s not good for the battery. Mine came pre-set to stop charging at 80%. The charging slows down towards the end too; that first 50% is very fast, up to 150kW (or more?) but it slows down to 50kW as it gets near the top.

Finding a charger proved pretty easy. I used the PlugShare app mostly. The Polestar maps app also has a database of chargers although it wasn’t quite as complete.

Paying for a charge was awkward. Many of the chargers want you to install their own proprietary app, even if the charge is free. I ended up with a small collection of apps and accounts, a hassle similar to paying for parking with an app. Electrify America had actual credit card readers, like a gas pump. That seemed great at first but one reader was broken and also then I didn’t have an app to easily check on my charging status as I went out shopping.

All in all charging wasn’t a big deal but it was definitely more planning and mental load than just putting gas in a car. A lot of this complexity was all about being in a rental car at hotels. If you own an EV you’ve probably made some arrangement to charge it at home, in which case most of the time you don’t need a public charger at all. For that matter one of the places I stayed had a free charger for guests; nice amenity!

Driving differences

The most fun thing for me was seeing how Polestar has re-considered the concept of car-as-product. Much like Tesla has.

It mostly drives like a normal car but not entirely. There’s no ignition! Just sit in the car and go. Gears are forward, reverse, and neutral. If you take your foot off the accelerator the car slows pretty aggressively, regenerative braking. This saves power and also means you can mostly drive with just the one pedal. Also the car doesn’t creep forward if you don’t have your foot on the accelerator. Both things too some getting used to but I ended up liking them quite a bit, they make sense for an electric motor. You can configure the car to simulate these gas engine legacies if you want.

A nice side effect is there’s no stigma of sitting in the car parked with the AC blasting cold air and the radio on. Just chilling in your portable living room. Sure, you’re using some battery, but that’s OK. There’s no gas engine idling, making noise and smell and waste.

The car controls and electronics are fully reimagined around a touch screen tablet and an Internet connection. No knobs for A/C, stereo, etc. The core software is Android Automotive. I found the UI very simple and straightforward with no unpleasant surprises. Maps works, car status apps work, all simple. I had a hard time figuring out how to turn the AC on. And finding the home button to get to the main UI. But those were both one-time things and once I learned them they were fine.

All in all it’s a nice car to drive. I was similarly impressed with a Tesla Model S when I test drove it. Reconsidering the car product and UX is a good thing.

Cost

I rented the car from Hertz at a nominal $53/day. That’s a pretty great price for a relatively high end car like a Polestar; I’d have expected to pay as much as $100/day for a gas car of that quality. Hertz seems to have made a major effort to promote EV rentals, they do a lot of Teslas too. I suspect they’re buying the cars at a discount, good marketing for Polestar.

Charging costs were anywhere from free to $0.30/kWh to $0.45/kWh. The car uses about 32 kWh per 100 miles, so it works out to $10-$14 per 100 miles if you’re paying for electricity. The similar Volvo S60 gets about 30 miles / gallon, so with $3.35 gas the combustion engine car costs about $11 per 100 miles. Bottom line, it costs about the same per mile in energy. Unless you skim electricity off of free chargers!

Hertz provided the car at 67% battery and told me to bring it back at 60% or more if I didn’t want to pay a battery recharging fee. I don’t remember what that fee was but it seemed about in-line with what you’d be charged if they had to add gas.

Summary

I really liked the Polestar 2. I miss it! I may end up buying one, or something similar. I’d gladly rent one again but if I were taking 100+ mile trips far from towns I’d consider the charging infrastructure available carefully. In a big US city, charging was only a minor hassle.

CO2 and Cognition

Last year I blogged an aside comment about how higher carbon dioxide concentration makes you dumber, based on this 2021 article. It turns out that the story is a little more complicated. See this Hacker News comment for one reference. Or even better, this 2020 overview by the Naval Submarine Medical Research Laboratory: Stressors Present in a Disabled Submarine Scenario: Part 2. Effects of Environmental, Mental, and Physical Stressors on Cognition.

Page 22 has the relevant details on CO2 and cognition. Here’s the gist of it (quote heavily edited)

the relationship between CO2 exposure and cognition is debated ... While some studies have found that elevated CO2 may impair cognitive functions including decision making, attention, mental efficiency, and mathematical processing, these findings are not consistently replicated. In fact, many studies have been unable to establish a relationship between CO2 exposure and cognitive deficits.

There’s more in the article and it is full of citations of 50 years of research; well worth a look if you want detail.

One thing that seems particularly important: is more CO2 by itself a problem? Or is CO2 a proxy for stale air and there’s lower oxygen or some other confounding contaminant like carbon monoxide? I imagine every good study controls for this but it’s hard to know in your own home.

To get a sense of scale, normal atmospheric composition is 200,000 ppm oxygen to 400 ppm carbon dioxide. A little more CO2 isn’t going to actually displace a meaningful amount of the O2 you are breathing.

A full year of solar

I’ve had my solar system for just about a year now, time to collect full data.

In 2022 PG&E says I netted -1670 kWh. I used 16,000 kW in 2020 and 2021, so I generated about 17,700 kWh this year. Or just about 10% over my usage. My electricity bill should be 0, or maybe even a tiny bit negative.

My solar system was designed to generate 16,600 kWh a year (with 28 * 410W = 11.5kW of panels). So I generated about 7% more power than expected. Not complaining! I am also glad to be generating a bit more power than I use because I intend to convert to electric heat pumps and cars eventually. Although I don’t really have that much excess power...

Above is a graph of daily net power, based on PG&E’s data. You can see the seasonal effect very clearly. I’m net negative quite a bit in spring and summer. I start using more than I make in August and September, to run the air conditioner. (I was out of town in October, hence much less power usage.) I go full net positive once the days get shorter and the sky gets cloudier. It’s nice that my NEM 2 rate plan nets me out over a full year; it’d suck if they trued up once a month.

I was hoping to have better data with the fancy PVS6 monitoring software I built. That worked great right until the day the PVS6 died, stopped talking to the Sunpower servers. No idea what happened there. They eventually just replaced it for me and I haven’t plugged in my little Raspberry Pi to exfil the data since. I have no idea if my monitoring broke it but I don’t want to chance it. Honestly the kind of minute-by-minute data I was getting from the system isn’t very useful anyway, daily summaries are good. Sunpower’s website should give me that but like I said, only started getting good data in September. (Also their website is awful but I bet there’s a data download somewhere.)

Very glad I got solar, wish I’d done it sooner. My system will pay for itself in about 7 years total. The deal under NEM 3 isn’t nearly as good for California consumers, I’m lucky to have gotten in when I did.

Update: true-up bill

Got my bill which contains the full year’s “true-up” for my NEM 2 solar system. I don’t honestly understand much of this. But they agree that I supplied about 1800 kWh more power than I used and paid me the $0.06/kWh or so I expect. (Note they charge $0.40/kWh for the same electricity, but at least I zeroed that part of the bill out.) Also something like $5/mo for delivery charges, eh.

UPS battery replacements by size

Replacing the lead acid battery in a Cyberpower 1000AVR. Officially the battery is called a “RB1290”. It is is 12 volts, 9 amp-hours, dimensions are 5.92 x 2.53 x 3.69 inches. There are a zillion options for replacements at half the price of the OEM battery, the keyword is “1290”. I ordered this one.

What caught my attention is there’s folks out there selling replacement batteries with different specs. 12V/8Ah, 12V/7.5Ah, ... Presumably as long as it’s 12V and fits in the space, it will work. What I don’t know is what practical impact lower capacity has. Does the Cyberpower firmware measure capacity somehow? Or is it programmed to expect a 9Ah battery and thus will confuse everyone when it runs out of juice earlier than expected? I suspect it will still just work, they measure remaining capacity with voltage or something.

The 1000AVR is rated for 600W and 9 minutes at half load. That suggests it has 90Wh of capacity for AC power. The battery’s DC specs are 108Wh, so that’s in the same ballpark. They also sell a bigger 1500AVR with two 1280 or 1290 batteries. That’s 900W or 12 minutes at half runtime, or 180Wh. So the math all makes sense.

Can I buy a higher capacity battery that will fit? Probably no. This site lists a lot of options for 12V batteries that are the same size, ranging from 7AH to 9AH. The 7AH batteries are a tiny bit cheaper ($13 vs $15) but I can’t imagine why you’d pick that.

Some previous notes from me. My new favorite UPS is a CyberPower CP1500PFCLCD PFC Sinewave. Looking now I see someone sells a DC-only UPS for routers, USB devices, etc. Interesting product! The category seems to be called “mini UPS” and Amazon has several choices.

Bonus link: Replacing a UPS Battery With Super-Capacitors

Nest is a bad product

A few years ago I bought the hype and installed a Nest thermostat. Bad choice; it’s a terrible product. I finally made it vaguely acceptable by disabling all the “smart” learning features and using it as a simple programmable thermostat. It works OK except all the times it fails, like when the Nest website is down or the time they shipped bad firmware that drained the battery necessitating you pull the thing off the wall to recharge it with a USB cable before your heater worked.

Anyway, I thought I had it fixed. Now I looked at the dumb message inbox I haven’t looked at in a year+ and see this:

Those top two messages are telling me they changed something. (The other messages are spam). Notice the lack of any notification on what changed. No idea; did they edit my schedule? What did they do? The times look the same as I’ve always had but I think I used to have it programmed to 68? I’m not sure, I stopped remembering because I had set it correctly and was comfortable.

Nest’s big claim is it saves you money and saves the environment. It does this by making you colder. I’m all for saving money and the environment. I wear a Jimmy Carter sweater. I programmed my thermostat for the right temperature for me. And now apparently Nest has decided it knows better. By making me colder. Maybe? There’s no way even know what change it made.

Update: I’m cold

A month later and I’m pretty sure Google changed my schedule on me. I’ve been cold every day. I finally reprogrammed my temperature to 68. (Which took about 30 clicks; the web UI is very awkward.)

Looking at the notifications I got I see now this is Seasonal Savings. To be fair, the docs are pretty good and claim that the feature is opt-in. I don’t recall opting in but, eh, maybe? Anyway I think this was enabled and changed the temperatures on me, both the daytime from 68 to 67 and night time from.. 62? I don’t remember .. to 59.

I think this may even be a good feature: it both saves individuals’ money and helps mitigate CO2 pollution globally. My real complaint is more about the notification. The messages only show up in some notification queue I long since disabled because it’s full of marketing spam. And the messages don’t tell me what changes it made, just that it changed something. Both problems are fixable if someone had the right product idea.

(PS: I tried asking support for help and it was a frustratingly useless experience. He kept pasting in canned replies about resetting my entire schedule and reprogramming it. The agent never once suggested it might be “seasonal savings”.)

Fixing Samba for Sonos v1 (Ubuntu 22.04, 22.10)

To make Samba in Ubuntu 22.04 jammy and 22.10 kinetic work with Sonos v1, add these lines to the global config:

server min protocol = NT1
unix extensions = no

On Sonos the login works fine with a blank username and blank password (assuming your music volume is a guest volume). I think username guest, password blank also works.

That first line has been necessary for awhile because Sonos v1 has an ancient SMBv1 client baked into it and the company won’t update it. The second line about unix extensions is new; it wasn’t necessary in the Samba included in Ubuntu 20.04. I don’t know what changed. Ubuntu 20.04 uses 2:4.13.17~dfsg-0ubuntu1.20.04.1; Ubuntu 22.04 installs 2:4.15.9+dfsg-0ubuntu0.3.

I think the “unix extensions = no” setting is reasonably safe. The docs suggest it does something to make Unix SMB clients happier; I don’t have any of those.

I’ve been low-key chasing a problem for months. It’s been super frustrating. So much so I even considered creating an alternate server. I don’t know if the problem is a change in Samba itself or if it’s specific to the Ubuntu build. I build Samba 4.17.3 from source on Ubuntu 22.10 and had this problem, so that suggests a change of behavior in the sources.

The unix extensions config options seems to have to be in [global]; it didn’t work to put it in the share definition. Here’s the full share definition I am using:

[musicshare]
follow symlinks = yes
wide links = yes
path = /home/nelson/Music
read only = yes
printable = no
guest ok = yes

The stuff in there about symlinks and wide links might not work with unix extensions turned off.

A Sonos v1 SMB server

Summary: do you need a SMB server to serve your local library of music files to your v1 Sonos? Barry de Graaff has a solution, sonossmb. It’s a small Node implementation of SMB that works with Sonos. It works! It does take a bit of hacking to install though.

About sonossmb

I used Samba for years to serve music to the Sonos. The problem is the v1 systems are unsupported and have an ancient insecure SMBv1 client baked into them. And starting with Ubuntu 22 (which has Samba 4.17) it no longer works with Sonos, even with the special v1 config directives. No idea what’s wrong. That got me speculating that a simple stripped down anonymous-only SMBv1 server for Sonos might be a nice product. Which is what de Graaff created!

His server is based on Adobe’s Node SMB server, a project I never heard of and looks abandoned. He tells me it mostly works with Sonos just fine. He just made one tiny change to upcase the share’s name. The packaging and installation is a little trickier. He’s got some good docs and a script but it’s still something you might need to understand Linux pretty well to get running. More on that in a bit.

One problem I ran into; Ubuntu 22 ships Node 18. And that gives an error related to SSL ciphers I think because Node dropped support for old insecure SSL clients. The workaround of export NODE_OPTIONS=--openssl-legacy-provider worked for me.

Note that the share has a name like \\192.168.0.2\PUBLIC and you must log in with the username “guest”, no password. Empty username doesn’t work.

It’d be nice if Samba could be fixed. That SSL thing makes me wonder if that’s what broke on Ubuntu 22, that they too dropped some old SSL stuff that the Sonos ancient client needs. There’s some discussion on the Samba list. One happy thing is one of the Samba developers himself has a Sonos so someone in the know may work on the problem.

Packaging, Snap.

Barry’s server works but I can’t quite use it as-is on my LAN. I really need a full Samba server too. But I only have a single Linux box. And SMB doesn’t work well other than on a single port, 445. Some clients do work on other ports but I haven’t tested it with Sonos and am pessimistic. Maybe I need to just add a second IP address to my server and bind the special Sonos server there, but yuck.

All the drama of getting the thing installed makes me think a Snap container / image is the perfect way to run this server. There’s a snap for the web server Caddy so a daemon that accesses local files and serves them on the network is possible in Snap. But I’ve never built a Snap and have no idea how hard it’d be. I guess Docker would work too but Snap seems to be the choice for consumers on Ubuntu systems so I think starting there makes sense. I may give a go at building a Snap, we’ll see.

adobe/node-smb-server patch

Here’s the patch Barry sent me to upcase filenames:

diff -Naur node-smb-server-master/lib/smb/cmd/tree_connect_andx.js sonos-smb/lib/smb/cmd/tree_connect_andx.js
--- node-smb-server-master/lib/smb/cmd/tree_connect_andx.js	2021-06-22 17:20:12.000000000 +0200
+++ sonos-smb/lib/smb/cmd/tree_connect_andx.js	2022-12-09 08:21:10.674527000 +0100
@@ -10,6 +10,10 @@
  *  governing permissions and limitations under the License.
  */
 
+/* As required by original License I hereby notify you that I have made changes to this file.
+ * Copyright (C) 2022 Barry de Graaff
+ * */
+
 'use strict';
 
 var put = require('put');
@@ -76,7 +80,7 @@
 
   logger.debug('[%s] flags: %s, password: %s, service: %s, path: %s', SMB.COMMAND_TO_STRING[commandId].toUpperCase(), msg.flags.toString(2), msg.password.toString('hex'), msg.service, msg.path);
 
-  var shareName = msg.path.substring(msg.path.lastIndexOf('\\') + 1);
+  var shareName = msg.path.substring(msg.path.lastIndexOf('\\') + 1).toUpperCase();
   var shareLevelPassword = utils.bufferEquals(msg.password, Buffer.from([ 0x00 ])) ? null : msg.password;
   if (_.indexOf(server.getShareNames(), shareName) === -1) {
     result = {

Battery backups: UPS, battery generators, etc

I’ve learned a surprising amount about how to have battery power for when the AC power goes out. Some summary notes.

One important stat: “transfer time”. That’s how long it takes for the backup power to kick in. You need this to be fast if you don’t want the device to turn off and on again. For reference, 60Hz power cycles every 16ms. UPS units are the only ones I know of fast enough that a computer won’t be interrupted when the power goes out. You can use a UPS along with one of the bigger and slower backups.

Many of us have good ol’ UPS units to keep our computers up in momentary power outages. My favorite consumer brand is Cyberpower. These are typically sold by max power + runtime and it’s hard to find how many watt-hours are actually in the battery. There’s a surprising variety of types of UPS units. I now buy PFC Sinewave units that condition the AC power and produce a nice clean wave. As a side effect this makes the UPS work better when on dirty power like a generator; with a cheaper UPS on generator it would switch to battery backup every few minutes. Transfer time on a UPS is < 10ms and consumer devices shouldn’t even notice.

Gas or propane generators. I have a Generac Guardian 22kW for when PG&E takes our power out for hours or days. These are expensive and terribly inefficient, particularly when running at low power. They also put out pretty uneven power; when they get loaded the 60Hz briefly slows down to 58Hz or whatever. But if you need to be off-grid for days at a time they are the most practical choice. I paid $15,000 for mine. It’s rated for 3000 hours, so that’s $5 / hour! Although presumably it can be refurbished? Transfer time is ~15 seconds, everything will turn off before it switches on.

Battery generators. These are a new class of product that replace portable gas generators, basically a very fancy lithium battery with an inverter. I have an EcoFlow Delta 1300 that PG&E gave me to avoid liability for my power going out. These are really capable devices, absolutely excellent for being off-grid for a few hours. They charge via AC and also come with the circuitry to charge via solar panels or electric car chargers. I’m impressed with mine as a product. One drawback; you need to drain the battery occasionally to avoid it wearing out. Also the transfer time is 30 ms; fast, but not fast enough to keep your computer on. It’s not a UPS.

Whole house batteries. These are the fancy things like the Tesla Powerwall. I don’t have one but wish I did. They’re expensive as backup power, a gas generator is a lot cheaper. I’d particularly like to have a small battery, just like 4000Wh of capacity or something. Enough to bridge an hour long power gap and let me keep my solar running; during the day I can charge it faster than I’d use the power. Last I looked no one made a small product like this. Not sure about transfer time; I think the Tesla Powerwall is slow enough everything is turned off briefly.

One extra note: all these systems I use are focussed on providing AC power. But 90% of what I care about plugged into it runs off DC power, it’s dumb to have a battery, an inverter to produce AC, and then a transformer to swap back to DC. The EcoFlow Delta has serious USB charging circuits. I suspect it’d be possible to get adapters to power things like network routers off those USB ports and that might be more efficient.

HVAC thermostat access: Carrier Infinity Touch

Trying to diagnose an HVAC control problem. Software details below on how to get access to data from the Carrier thermostat.

I have a very fancy central AC system with a Carrier Infinity Touch thermostat and three zones controlled by dampers. My office is in the main zone 1 and is set to 75F, but in the late morning it cools down to as low as 69. The thermostat is in another room and unfortunately right next to the bedroom zone 2, with a door between we usually leave open.

I’m able to measure a few things: the temperature from the HVAC thermostat, the temperature from a Laseregg sensor about a foot away from the thermostat, and the position of the damper for each zone (0-15, scaled to 50-65). Unfortunately I can’t get access to HVAC fan speed or how hard the compressor is working (ie, what stage).

Here’s details of zone 1 on three different days:

The key message here is with the door shut (on left), the two thermometers (blue and yellow) tracked each other’s temperature within 2F. But with the door open (on right) the divergence goes up to 5 degrees. The middle graph had me opening and closing the door during the day; not positive but basically every time the blue thermostat line dips down is when I closed the door.

I have no theory for why the two thermometers would show different temperature trends at all, or why the difference would vary depending on the door being closed. The thermostat is mounted on a wall, but I don’t think that wall is unusually hot or anything. Is it possible the thermostat isn’t reporting a simple temperature sensor but some complicated synthetic thing based on air temperature?

The other thing I learned from this experiment is what the dampers that control zone flow are doing. Zone 1 is the main room with the thermostat graphed above; zone 2 is on the other side of that door I’m opening and closing.

Three days of temperatures in zone 1 and dampers zone 1 and 2

It’s a bit messy, but the main thing this is showing is that every morning the AC isn’t even cooling zone 2 (purple), all the cold air is going to zone 1 (orange). Zone 2 comes on in the afternoon and usually zone 1 tapers off, although yesterday on the very hot day basically both zones were full open.

No clear conclusions here; I really wish I understood why the thermostat and the Laseregg thermometer diverge so much. But I do see why my office in zone 1 gets so cold in the mornings; all the air is being diverted into that zone. With the door open I suspect that cold air then bleeds into zone 2 enough the HVAC decides it doesn’t need to explicitly cool zone 2 itself. Closing the door helps with that, or maybe if I set zone 2’s temperature a little lower it’ll change things.

The real solution would be to move the zone 1 thermostat further away from zone 2.

Trying to understand all problems through my lens of software engineering is foolish. I suspect a real HVAC expert would be able to understand the problem quickly. I should call the folks who installed this, their system designer seemed good, but the techs they send out aren’t creative problem solvers.

Software details for accessing Carrier data

Here’s how I got this data from my Carrier HVAC.

The thermostat comes with a crappy website for controlling it and no API for data. Fortunately folks have hacked this; Infinitude is the key software and there’s a Home Assistant wrapper.

Infinitude is a Perl proxy server. You run it on your LAN, use the thermostat config to point it at the proxy, and now you have a MITM for recording data and control. It’s a pass-through, the Carrier Internet app still works. Infinitude has its own Web UI with status display and the ability to configure some or all of what the thermostat does. It also has an API.

Infinitude also has support for a serial interface to the thermostat with high frequency data; I didn’t mess with that. And apparently the thermostat now has MQTT support so that’s an interesting alternative that someone may hack support for. (Or not; it may be that a side effect of MQTT is that the proxy hack won’t work any more.) The discussion in that link is interesting btw, this thermostat is a much more capable system than the consumer UI would indicate.

I’m running Infinitude as a Docker image. It wants to run on port 3000 but unfortunately that’s in use for Grafana already (even in the container?!). And the entrypoint doesn’t let you override that. So I ended up having to modify the Dockerfile and build my own image. I’m launching with ./infinitude daemon -m $MODE -l http://:3030

Infinitude is not well documented. The docs promise a --help but I couldn’t make that work. Not sure what other command line arguments the thing supports. I’ve lost my ability to read Perl (to the extent Perl was ever readable) so I gave up.

There are some docs for the REST API but they are incomplete. A key API call not mentioned there is /api/status. Between that and /api/config I can get a lot of data off the device. What’s there?

There’s some device-level stuff, most of it not filled out. There’s a timestamp with a bogus timezone (-08:01 when it should be -07:00. Lol.) Most of interest is per-zone data accessible with jq with the key .zones[0].zone[0] for my living room

  • clsp, htsp: desired temperature setting (cool and heat)
  • rt, rh: room temperature (73-76) and humidity (40-41)
  • damperposition: numbers from 0 to 15. 15 is running full out, I think, but I’ve seen 10-15 and 0
  • zoneconditioning: active_cool, idle
  • currentActivity: home, manual (or sleep, etc?)
  • hold: off or on, depending on how I set it
  • otmr: 22:30, the time the current home program ends
  • enabled: always on?
  • fan: always off? (maybe manual fan control)
  • id: 1, the zone number
  • name: living room, the zone name

It seems to update at least once a minute.

What I’m not seeing here is how hard the compressor is working or how fast the fan is running. That data can be displayed in the thermostat, but it’s more a property of the HVAC itself than the thermostat. I wonder if the HVAC unit itself has a serial port you can tap for data? I’m not aware of it having any Internet access.

I didn’t look as close at /api/config, it didn’t seem very interesting. This is where the program seems to be available; times and temperatures.

California electricity grid; resource adequacy

California has its own electricity grid, roughly independent from other states. The California ISO that runs it has an excellent dashboard (and mobile app) showing grid status, predicted demand, the march towards renewable energy, etc. It’s very well done, I think a response to the chaos around the year 2000 when we didn’t have enough electricity for the state.

We’re about to have a very hot week so I looked in detail at the 7 day resource adequacy graph. What this means is documented mostly here.

There’s two datasets: graphed in teal and purple respectively. Teal is more or less actual power. Dashed line is forecast capacity; it fluctuates mostly with solar. The faint dotted line is forecast demand; it fluctuates mostly with air conditioning need and evening home demand. What this is showing us is that towards late afternoon on 9/4, 9/5, and 9/6 we’re going to have a little more demand than supply. That’s not a catastrophe; CAISO can buy power from other states, at least assuming any is available.

The purple graph is the same data but excludes wind and solar from production, that’s why it’s so steady. (It also excludes something from demand but I’m not sure what). An added complication are “credits”; I’m not sure what those are, but if you visualize them they’re only about 2GW out of 55GW.

It’s worth noting that these are predictions, promises of what the electricity providers are telling CAISO they can generate. I believe they’re obligated to actually supply all this promise, the shortages in 2000 and 2001 was partly because some of the generators were playing games with supply to manipulate the market.

There’s a lot of other neat data on the CAISO site, particularly the supply pages that highlight renewables. May 8 2022 was a banner day: we had enough solar and wind to cover all demand, so fossil fuels dipped very low. (Not zero, but we exported more power than we generated in fossil fuels. I assume that was a choice made for financial reasons.) Alas this is only possible in late spring when solar is high and demand is low.

Another interesting dataset are the curtailment reports, times CAISO tells solar or wind providers to stop providing power because they have no place to put it. It’s not a huge amount of power and seems mostly to do with local bottlenecks, not pure overcapacity. Exta power first goes to batteries and pumped hydro.

One thing CAISO doesn’t provide much is graphs of trends over year; they’re very focussed on intraday reporting. They do publish monthly reports with data in PDF format.

PG&E solar billing; two channels

Did you know PG&E smart meters have multiple channels? “Channel A represents energy pulled from the grid” while “Channel C represents energy exported back to the grid”. Weird! Details below.

PG&E screwed up during my solar period and for 6 months even though their records showed I was sending them more power than I was receiving, they were billing me for $200 worth of electricity a month. I eventually got a refund but I made a CPUC complaint about what looked like abusive and fictitious billing.

To PG&E’s credit they got in touch with me to resolve my complaint and I had a chat with a knowledgable customer agent who gave me a clear answer. Here’s how CPUC summarized it:

PG&E advised that NEM customers are billed with interval data using 2 channels on the SmartMeter: Channel A registers consumption, while Channel C registers exported generation.

The PG&E docs show pictures of bills with breakouts by channel, but I can’t find that in my bill. But the docs I’ve found online are 15 year old, many for NEM1 (I’m on NEM2) so maybe it’s not available now, or I won’t see it until my yearly true up.

I can’t make any sense of how this would work electrically. AFAIK my solar feed was installed with vampire taps between the meter and the circuit breakers; there’s no separate wire coming in from my solar directly to the meter to record. Maybe the two channels are more of a synthetic thing, with A being the sum of watts used during intervals that are positive and C being the sum of the negatives. Or maybe there’s some magic in the energy grid that can detect flow? I doubt it.

The funny thing about all these attempts to verify what PG&E is saying is they come to nothing; you’d never prevail in a dispute over how they bill. My Sunpower monitoring regularly shows me about 1kWh a day better off than PG&E bills me. Flaky meters? PG&E skimming? Who knows. The PG&E data looks roughly accurate though and they are effectively the law, so not much point second guessing it.

ffmpeg and hevc_qsv Intel Quick Sync settings

I’m revisiting my experiments using Intel Quick Sync to transcode video into H.265 using the hevc_qsv transcoder. I’m using jellyfin’s build of ffmpeg. Here’s where I ended up:

function to65 {
  /usr/lib/jellyfin-ffmpeg/ffmpeg \
    -c:v h264_qsv \
    -i "$1" \
    -map 0 -c copy \
    -c:v hevc_qsv -preset slow -global_quality 22 -look_ahead 1 \
    $2 \
    "${1%.*} x265.mkv";
}

Doing this results in an H.265 video file about 1/4th the size of the H.264 file and takes about 1/8th the show length to transcode. (ie: 5-6 minutes for a typical 42 minute tv show). Quality looks about the same to me but I’m using fairly unexciting video sources to test.

ffmpeg options

The challenge is this is all very poorly documented, particularly quality settings. Keep in mind that hardware H.265 encoding is generally considered lower quality than the CPU based x265 encoder. NVenc is said to be better than QSV. Also be aware Google search is treating hevc_qsv as a synonym for h264_qsv, so searches will often find irrelevant information if you’re not careful.

ffmpeg -h encoder=hevc_qsv is supposed to give you a list of all the codec specific options. You can see that list here. But there’s no real basic quality or bitrate setting, just a lot of mysterious technical-seeming options. Some of this might be documented in the Intel Media SDK docs or this white paper on how it all works.

Instead you want these ffmpeg docs and the QSV encoder help page. The key option here is global_quality. I think this works like crf (which is not an option and seems to be silently ignored if provided). The number is not documented but can be 1 (highest) to 51 (lowest), folks online recommending about 21. With global_quality set you still have 3 algorithm options: -look_ahead 1 seems to be the fanciest. I’m not sure but that might be the default. -preset is another option to consider; slow seems the right tradeoff to me. I did not consider the -profile option.

I still feel like I’m missing one clear set of docs for how this encoder works. I cobbled some of it together also using this cookbook page.

Testing

I did a very casual test of these settings using a 720p web rip (AMZN) of a TV cooking show. The original file is about 6000kbps; the video stream itself is 5800kbps H.264. I have a tin eye; I’m OK with fairly mediocre video encoding for most things like this. I’m just trying to keep some old TV shows around without taking up too much space.

For visual quality, -global_quality had an enormous impact; it’s the most important setting. Using the default settings instead or was unacceptably bad, particularly on scene transitions. Honestly anything from -global_quality 18 to 26 looked about the same to me. The preset option didn’t have nearly as clear an impact on visual quality.

Preset does have an impact on encoding speed. medium: 9.5x. slow: 7.5x. slower: 3.7x. Quality settings didn’t have much impact on encoding speed.

Here’s bitrates at different settings of -slow -global-quality N

-global_qualityFile bitrate (kbps)
182911
202309
221777
241395
261114
original6075
default hevc_qsv1222

Running ffmpeg this way uses 1 CPU core and the GPU at 100%.

Screenshots

Sorry for the lack of labels on the images. The first is the original, the second two are without global_quality (and unacceptable). The rest are progessively lower global_quality although honestly they all look about the same to me. This was a frame with a lot of detail right after a scene transition. It’s not crystal sharp in the original so it’s not a big surprise many of the transcoded versions are roughly the blurry same.

Sonos server alternatives

I’m pulling my hair out trying to get Sonos to connect to my new SMB server. The various dark arts needed to enable SMB1 for Sonos’ ancient file sharing implementation aren’t working and there’s no debugs. Is there some way to share my local music files other than SMB? There’s no way to plug a USB drive into a Sonos directly :-(

One alternative is Plex. It has music capabilities. I’m finding it a little flaky and until I fiddle further it’s only finding files that it has metadata for, not the weird MP3 files that fell off the back of a truck.

Another alternative is Airsonic, another Plex-like media server. It has explicit Sonos support via the Sonic Music API (SMAPI), a new-to-me thing.

A third alternative is Bonob. I know nothing about it, just found it as a SMAPI server. I’ve seen it mentioned in concert with Navidrome.

SMAPI is an interesting back door into Sonos serving! A whole documented API. You can add a service of your own via bare bones HTML interface at http://192.168.0.50:1400/customsd.htm (IP address is of a Sonos player on my LAN). I wonder what the API schema is like; I suspect it is oriented to music with tidy metadata and not “giant pile of MP3 files in carefully curated directories”.

There’s some small or abandoned GitHub projects that are SMAPI servers: YouTube, a NodeJS server, a C# server. This NPR One service looks active.

You know what would be really nice? A stripped down SMB1 anonymous server solely for Sonos clients. Samba is so complicated, something that works with Sonos’ ancient client might work better. Alternately some folks use a Raspberry PI as a NAS/SMB gateway.

Ubuntu, ffmpeg, and Intel GPU acceleration

My fancy new Linux box has an Intel 12th gen CPU (Alder Lake) with a GPU in it. I wanted to try using ffmpeg to transcode video from H.264 to H.265. Here’s how I got it working, it was not easy.

Transcoding commands

First, my old way of transcoding without GPU acceleration

ffmpeg -i "$1" -map 0 -c copy -c:v libx265 -crf 25 $2 "${1%.*} x265.mkv"

I get about 4x encoding speed on an i5-12600K (compare about 1.1x on a ten year old i7-2600). However all 16 cores are pegged at 80% ish and the machine is drawing 165 watts. Note we’re using the libx265 encoder, all CPU. It’s not bad.

The new hardware accelerated way (some of these arguments need tweaking)

sudo /usr/lib/jellyfin-ffmpeg/ffmpeg \
  -c:v h264_qsv \
  -i input.mkv
  -c:v hevc_qsv
  -c:a copy out.mkv

This runs much nicer! I get 7.5x encoding speed. But now I’m only using 1-2 cores and the machine is drawing only 55 watts. I haven’t looked closely at encoding options or video quality but a quick preview looks plausible.

The primary change here is different codecs; h264_qsv and hevc_qsv. These are Intel Quick Sync codecs that are hardware accelerated using the GPU. The h264_qsv decoder uses about 10 watts less than the default CPU decoder (and 1-2 cores). The hevc_qsv is where the big savings are, some 90 watts.

The other change is I’m using jellyfin’s build of ffmpeg. Installing all this was a bit of a trick. Note also I had to be root to run this; I think there’s a way to change permissions so you can open the video device without root. Update: the devices are in /dev/dri which are usable by group “render”.

Installing prerequisites

I’m starting with an Ubuntu 22.04 server install running the 3.19 mainline kernel. Probably any kernel is fine.

I installed these packages from the default Ubuntu repository:

$ apt install onevpl-tools vainfo intel-media-va-driver-non-free
$ sudo vainfo
vainfo: Driver version: Intel iHD driver for Intel(R) Gen Graphics - 22.3.1 ()

OneVPL is Intel’s userspace for Quick Sync, the GPU accelerator. The non-free driver is recommended. vainfo is probably not necessary but is a handy tool for verifying the graphics driver.

With this I thought the stock ffmpeg would work. But it did not. I finally gave up and installed the jellyfin-ffmpeg package with the Ubuntu Repository instructions. Jellyfin is an open source media server, sort of like Plex. Its hardware acceleration docs are a lot clearer than ffmpeg’s wiki docs and apparently their build of ffmpeg has something important that Ubuntu’s does not.

Updates

intel_gpu_top (from intel-gpu-tools) is handy for seeing what’s running on the GPU

Sunpower PVS6 web console

The Sunpower PVS monitor has a full HTML web console accessible on its internal network. The PVS acts as a full Internet router on a debug ethernet port you can plug into. If you plug a laptop into it the laptop will be online (routed through the PVS) and also serve extra stuff at http://www.sunpowerconsole.com/. It’s mostly a web view of the data in the JSON API but it’s an official debugging tool and is quite nice.

I have my RPi plugged into that debug port and am proxying all web traffic, so on my LAN I can access http://pvspi0.local/ and get at these pages.

Here’s a list of URLs that it supports. These come from this detailed comment which also describes what these URLs do. A lot of these are steps on a little configuration wizard that presumably installers use. I think all these URLs are safe to load but some clearly have buttons to press that could reconfigure or break your system. Don’t press those.

The info view is particularly good; here’s a partial screenshot (I didn’t include the serial numbers.) Three sections: the PVS as a whole, per-panel/inverter data, and then CT monitors.

Solar panel max output, microinverter details

My solar system is mostly doing great. But I’m obsessing over small details and one thing I’ve noted is some (but not all) of my panels seem to max out or even underperform in the middle of the day by 5-10%. I’m trying to figure out why.

Panel 2122: expected
Panel 9897: clipped in the middle

Above is a graph of two of my 28 SunPower SPR-A410 panels with SPR-A410-G-AC microinverters. These were built and installed in 2021. The graph on the left shows what I’d expect; a steady increase in output following the sun. The panels face west, so it’s not a symmetric curve. The falloff end of the day is shading.

The graph on the right is the weird thing; the DC power gets up to about 300W and then sticks there, even dropping down a bit to under 290W. It does briefly get to 334W at the end of the day, so it’s not some absolute max. It’s like that’s the max output of the panel is being limited somehow. It looks like 15 of my 28 panels do this, the other 13 have the smooth curve. It’s clipping about 10% of power production for the middle part of the day, so maybe 5% of a panel’s possible output or 3% of the whole system.

I know a 410W rated panel will never actually put out 410W. But how much should it put out? The maximum I’ve ever seen is 385W (DC) or 367W (AC).

But what I really want to know is why some panels do this odd clipping thing when others don’t? Some theories:

  • Shading. I really don’t think so, both on visual inspection and also just looking at the pattern.
  • Overheating. That was my first theory but the temperature graphs don’t really bear it out.
  • AC conversion. There’s no obvious difference in the AC vs DC power for the panels, they all look to have about the same conversion efficiency. The clipping pattern is visible in the DC as well.

Some things to do next:

  • More statistical exploration. Is it the same panels doing the same thing every day? Is the effect consistent day to day?
    select SERIAL, max(p_mppt1_kw) from pvs6_inverter where SERIAL='…9897' group by time(1d);
  • Get out the map of which panels are installed where and see if there’s a spatial correlation.

Data Details

I’m pulling this data from the SunPower PVS6 device_list API call which is accessible from the device itself. It reports the following variables for each microinverter at each panel:

  • Status: STATE, stat_ind. Always “working” or “error”
  • Temperature: t_htsnk_degc.
  • Cumulative production: ltea_3phsum_kwh.
  • Instant power measurements: p_3phsum_kw, p_mppt1_kw
  • Instant current measurements: i_3phsum_a, i_mppt1_a
  • AC frequency: freq_hz
  • No longer available: v_mppt1_v vln_3phavg_va

The interesting measures here are temperature and power in kW.

Power (and amperage) are reported both for DC power (mppt1) and AC power (3phsum). DC is always(?) the higher number so I assume the small difference is a measure of microinverter inefficiency. Which seems to be about 5% when the panel as a whole is producing about 300W.

Updates

This pattern didn’t happen on 2022-06-21, a fully sunny day. The only real difference I can think of is that my house was using more power; very hot day, AC running. So there’s more load in the house. But surely that doesn’t matter, PG&E will absorb however much power I can produce? Anyway here’s a graph of 9897, the problem panel above. All of the panels look like this this day.

9897

My custom solar monitoring system (PVS6)

I’ve been tinkering with monitoring my solar system and have come to a fairly nice useful setup. Time for a post documenting where I am. The details on how I did all this are in previous blog posts but I’m summarizing here. Some code in this gist.

The Display

Daily view

The daily view is focused on giving me a basic picture of my electricity usage. Green is production for the day, black is the PVS6 measurement of net (ie: production - consumption). Yellow is PG&E’s own view of net. I suspect PG&E’s data may be more correct; I’m not sure if the PVS6 CT sensors measure reactive loads correctly. Doesn’t much matter anyway; PG&E is the authority whether they are right or wrong. Mostly I just care that they are close. (Jan 7 is a data measurement anomaly.)

Minute-by-minute view

This view gives a lot of detail minute by minute. The top panel is a detailed view of production and consumption, what is a single bar in the daily graph. The second graph compares production to a forecast. Below that are details of individual panel production. The individual sparklines towards the bottom are fun; the panel in the upper left goes to 0 in the morning in the shadow of the chimney on my roof. At the bottom is a simple sparkline of lifetime net production, I had a little party when it passed 1MWh.

Implementation

The data import code is all in this gist. The Grafana panels are not shared anywhere, sorry.

Here’s all the places I’m pulling data.

  • PVS6: the Sunpower solar monitoring system
  • PG&E: manual downloads via their “Big Green Button”
  • Predictions: forecast.solar

The whole system is built with Telegraf collecting the data into an Influx database and a Grafana dashboard to visualize it. What a great set of tools those are! A real pleasure to learn and work with.

The PVS6 stuff is the bulk of it. Turns out Sunpower has a JSON endpoint on a web server in your PVS6 and folks have worked out how to interpret the data. It’s pretty hacky; I’m using a Raspberry Pi to proxy the data onto the rest of the network. I’ve written a ~200 line Python script to collect the JSON data from the PVS6 every minute and emit it in Influx wire format for import. It also does a little analysis within the minute’s dataset to facilitate easier graphing.

The PG&E import is a very simple bit of Python code that converts PG&E’s data into Influx. I have to do this download by hand in the website right now. They do have an API but it requires some sort of signup I haven’t tried to do yet. I should add that PG&E’s Big Green Button CSV export is really quite good. The CSV data is clean and simple. And they have history! I was able to get 9 years of this house’s electricity usage. Nicely done.

The forecast.solar import is also very simple. They have a easy-to-use API where you tell them your location and the size and orientation of your solar system. Then they give predictions for power generated, including weather-corrected. The free version of the API is fine for this use; I download a new prediction every six hours.

Next steps

I plan to keep tinkering with the data display. I suspect as time goes on I’ll be more interested in the daily summaries than the per minute view, so I’ll probably pay more attention to that.

It’d be nice to automate the PG&E data download.

I’ve had some thought about packaging this all up as a Raspberry Pi image. I think the whole thing could run on pretty much any flavor of RPi, it’d be like an add-on to the PVS6 with a nice local web dashboard. But that’s a lot of work and I have zero interest in offering a product that uses an unauthorized Sunpower interface. Sunpower has a fairly decent monitoring website with something much like my daily summary view. They also have tools for installers showing per-minute data. Those aren’t available to end consumers, I think on purpose, and I suspect they would not be thrilled by me offering a competing product.

Solar sparklines

Look at all this free electricity! Time scale is 6 hours. These are 410W panels which in practice seem to max out about 320W AC, or 350W DC before the inverter takes its share. This is from Jan 13; maybe I’ll get more in summer.

Customizing a Raspberry PI Zero 2 W for PVS6

Awhile back I set up a Raspberry Pi to be a gateway to get access to my SunPower PVS6 monitoring system. That’s going great; the extra status info is really helpful and interesting. (Bonus screenshot below). I just bought a Raspberry Pi Zero 2 W to be the new computer for this. It’s so tiny it’ll fit entirely in the PVS6 box, powered by the USB that’s in there.

It works! The wifi is pretty flaky, despite me getting an amazing -30dB signal. It seems to be a problem with one specific access point, need to tinker some more. (Update: it may be wifi power saving.) The cable mess is pretty janky but it’s going to be shut inside a box, not sure I care. A smaller ethernet adapter would sure be nice.

Here’s my detailed software notes on setting this up.

  1. Mostly I’m just following this guide
  2. Use the RPi image installer to burn RPi OS Lite to a new SD card. Note this is a 32 bit OS.
  3. Create and configure a wpa_supplicant.conf file on the DOS partition of the SD card
  4. Create an empty ssh file on the DOS partition
  5. Boot the RPi, find its IP address via my DHCP server. (The name raspberrypi.local might also work.)
  6. Log in with ssh as pi/raspberry. Ignore locale complaints.
  7. Change the password for pi
  8. Become root
  9. apt update; apt upgrade. (This takes awhile!)
  10. Enable console autologin using raspi-config
  11. Fix locale using raspi-config
  12. Change the hostname to “pvspi0” using raspi-config
  13. Edit /etc/dhcpcd.conf so the ethernet is not used as a gateway
  14. apt install chrony
  15. apt install avahi-daemon
  16. Disable wifi power saving
  17. Reboot the pi
  18. Log in to pvspi0.local using pi/newpassword.
    Note mDNS takes awhile to start working, a minute or two after the RPi starts up
  19. Install haproxy
  20. Configure /etc/haproxy/haproxy.cfg. I did not include stats.

A brief note on power consumption. Idle the RPi Zero 2 W seems to use about 165mA (at 5W). Running stress-ng -c 4 peaked at 570 mA. The magic number here is 500 mA, that’s the minimum power for a USB port. I expect the system to basically be idle all the time so I think I’m safe with no extra measures. But some ideas on reducing power consumption.

  • Turn off HDMI. Instructions don’t work.
  • Turn off LEDs
  • Use fewer than 4 cores
  • Turn off unnecessary daemons. bluetoothd, hciattach (the serial console)

Here’s the bonus snapshot of some of my Grafana config. Not running on the RPi; all its doing is proxying requests. These graphs are centered on showing the status of all 28 separate panels, something you can only do by accessing the PVS6 data directly.

Small multiples in Grafana

I learned how to make lots of little graphs in Grafana 8 today. It’s a bit strange but I figured it out thanks to this video on variables and these docs. Here’s a visualization of the power production of all 28 solar panels on my house. Some of those panels aren’t doing a lot of work in the morning; hope it’s better in the summer!

The first step is to declare a variable. You do this in the dashboard settings. In this case I wanted to create a variable named “inverter” which has 28 possible values, one per serial number. I’ve already stored the serial numbers as tags in my Influx data so this Influx Query will get at them

show tag values from pvs6_inverter with key=SERIAL

When you do this Grafana will magically add a little selection UI to your dashboard. You can configure whether there’s an “All” option and whether multiple sections are allowed when you define the variable.

Then you need to make a Grafana panel for the graph that is parameterized by that variable. This is as easy as adding a where SERIAL =~ /$inverter$/ to the query for the graph data; you can do this via the graphical query builder. Once you’ve done this you can choose which graph you want to see, but there’s still only one panel with one graph.

The last step is to enable repetition. This is under “Panel Options / Repeat Options”. You choose which variable to repeat by, then what layout you want. “Horizontal” actually means vertical too; I have it set to 6 max per row and it creates multiple rows automatically. Then go back to the dashboard view and select “All”. You should see all your panels. It’s a little wonky about reloading on changes, you may have to do something to force the UI to refresh.

The last bit of polish I did was to remove all the decorations from the graph I could to get it to display more densely. No title, hide the legend, no Y axis. I switched to the Graph (old) widget because I couldn’t figure out how to hide the X time axis in the new Time Series graph. The only thing I couldn’t do was change the padding of the graphs themselves; there’s more whitespace than I’d like. But it’s not bad and I appreciate how much UI work Grafana does, so nicely.

InfluxDB 1.8 schemas

I’m using Influx more and more for system monitoring. I’m setting up a new system to monitor my solar system and realized I don’t understand Influx data schema. Here’s my notes, based on the docs. This is for Influx 1.8; I think it’s broadly the same in Influx 2 but I’m not sure. Their docs are really quite good but I had to summarize it here to understand it.

Influx schema concepts

I’m going to follow those docs’ example: you have two scientists (langstroth and perpetua) conducting a census, recording observations in two locations (1 and 2). Each observation records two things: the count of butterflies and the count of honeybees. Observations are timestamped. Note the term observation is something I made up; it’s not an InfluxDB term. The question is how you store a bunch of observations in Influx.

Influx feels a little free-form and schemaless but really it’s pretty structured. Each observation is a row. Every row has a bunch of columns in it that boil down to key/value pairs. Rows can have different numbers of columns in them. Here’s all the components of an Influx schema

  • Measurements. These are more or less like tables in databases. You have one Influx measurement for each observation. In a traditional relational database you’d have a table per kind of data and a row for each observation. In our example there’s one measurement called “census” that records all the observations.
  • Timestamp. An integer, in nanoseconds. Signed 64 bit numbers from the years 1677 to 2262. In a table database you’d have a column named timestamp. It’s probably indexed.
  • Fields. These are the measured data for each observation. Fields have keys (names like “butterflies”) and values (numbers like 12). Field values can be strings, floats, integers, or booleans. In a table database you’d have one column per field with the column name being the field key and the values being the field values. There’s probably a lot of different values for field values. Field values are not indexed.
  • Tags. These are labels for the observations. Tags also have keys (names like “scientist” or “location”) and values (strings like “langstroth” or “location 1”). In a relational database you’d also have one column per tag, named by the tag key and with the tag value stored in the row. There’s probably only a few values for tag values. Tag values are indexed.
  • Series. A series is the name for all of the measurements that match the same measurement name and tag values. A series isn’t a thing you create explicitly, it’s implied by the set of values of tags. Ie: one series is “all of langstroth’s observations in location 1.” There’s no direct analog for a series in a relational database, but it’s the kind of data you’d regularly query.
    select timestamp, butterflies, honeybees from census
    where scientist = langstroth and location = 1

InfluxDB is schemaless in that you can create new series without having to define them first. Insert some new data with a new measurement name and tag values and it will make a new series. Each measurement can have its own collection of fields with values of various types.

In practical use it’s a pretty close match to how we use tables for storing observations in a relational database. The big difference is the distinction between tags and fields; some of the columns are independent variables like who took an observation and some are dependent variables like the count of butterflies.

Designing my solar schema

Going back to my solar monitoring project, the whole reason I’m looking at this is the code I found creates a whole lot of measurements when I think it should create one.

For example there’s a measurement named “sunpower_pvs_inverter_operating_frequency_hertz” and a different one named “sunpower_pvs_inverter_heatsink_temperature_celcius”. Each measurement then has a single field typically named “gauge” where the actual data is stored, a number like the temperature or frequency. That feels clumsy to me, maybe it’s a consequence of the data being cast in Prometheus format?

To me it feels more natural to have a single measurement named “sunpower_pvs_inverter” and for each observation to have two fields with keys “operating_frequency_hertz” and “sunpower_pvs_inverter”. Each field would store the data directly; no “gauge”.

I agree more with the tag design of the code I found. For instance I have 28 inverters and these are represented in the data with tags like device_id=E00100128000007. But they went overboard with tags; there’s separate tags for software version, URL the data came from, etc. This might come in handy with a complex hetereogeneous system but it’s confusing complexity for my simple system.

Here’s the schema I think I want. It kind of tracks the schema implied in Sunpower’s own JSON output from the device_list call. Just four measurements.

PVS status. This is information on the monitoring computer itself. No tags needed, some field keys:

  • SWVER dl_err_count dl_comm_err dl_skipped_scans dl_scan_time dl_untransmitted dl_uptime dl_cpu_load dl_mem_used dl_flash_avail

Production. This is measuring data from the PVS6 CT sensors on the solar power production power line and has type “PVS5-METER-P” in the JSON. I don’t think I need any tags at all for this. Some field keys I will record values for:

  • STATE p_3phsum_kw net_ltea_3phsum_kwh freq_hz s_3phsum_kva q_3phsum_kvar p_3phsum_kw

Consumption. Again CT sensors, this on the house consumption side independent of the solar. This has type “PVS5-METER-C” in the JSON. There’s two values for many things because I have a split phase system with different sensors on each side. Some interesting values:

  • STATE net_ltea_3phsum_kwh p_3phsum_kw q_3phsum_kvar s_3phsum_kva freq_hz i1_a i2_a v1n_v v2n_v v12_v p1_kw p2_kw neg_ltea_3phsum_kwh neg_ltea_3phsum_kwh

Inverters. This is the detailed data from each solar panel, there’s one JSON block for each of 18 panels. Some values:

  • STATE SERIAL ltea_3phsum_kwh p_3phsum_kw vln_3phavg_v i_3phsum_a p_mppt1_kw v_mppt1_v t_htsnk_degc freq_hz

Inverter rollup. I might want to add a synthetic fifth measurement, something that summarizes the state of all the inverters. You could do this at query-time in Grafana or whatever but it’s probably easier to do it in the Python code which is collecting the data. Probably this is what I’d actually graph; trying to draw 28 different inverters separately seems like a mess. Some possible measurements

  • Count of working inverters
  • Sum, average and S.D. of inverter kW (both AC and DC)
  • Number of inverters well below average kW
  • Sum, average, and S.D. of inverter voltage and current (both AC and DC)
  • Average and SD of inverter temperature

I think in all cases the timestamp should be when my own monitoring code ran. Each bit of JSON data in the PVS output has its own timestamp and I bet that can matter sometimes, say if an inverter isn’t communicating correctly. But I could imagine a lot going wrong too; I trust my own clock more.

A big question for me is if I should try to filter and reprocess all the data coming from the PVS6 JSON. Or just insert it more or less as-is. Filter each JSON item into either a tag (“SWVER”) or a field (“killowatts”). That means inserting a bunch of junk into Influx I will never care to query. But then again it means not losing data, either.

Data meanings

This has nothing to do with Influx but I was trying to understand what some of these data values mean.

“LTEA” seems to stand for “life time accumulator” and is one of the few (only?) bits of data that has history. Most of the rest are instantaneous values; current watts, not watt-hours.

“3phsum” seems to refer to three phase power, presumably the sum of all three phases so you have a single number. I think my inverters are simple single phase so this doesn’t really apply, but maybe they use that word for consistency with other products. The only measurements of wattage are labelled “3phsum” so I’m gonna just ignore the details.

Getting local access to SunPower PVS6 data

Tinkering with my new solar system. The install includes a fancy SunPower monitoring system called a PVS6. SunPower has a decent website which gives you current conditions and hourly history of energy production. But I want more detailed data! And thanks to this guide I’ve got access and am starting to unpack what all is there. This GitHub project also has lots of notes and this PDF is quite detailed.

Access to monitoring data

The PVS6 has a web server with stats you can access over the network. The trick is you have to use the LAN1 installer port to get to it. You don’t want to just plug it into your network; it has a DHCP server of its own that might make mischief. So instead I set up a Raspberry Pi with haproxy to forward HTTP requests to the PVS6. The guide I followed has detailed instructions and now I have access to the PVS6 web API.

So what’s there? The notes here are a detailed guide. The main command for monitoring is DeviceList. Apparently most of the data updates every 15 seconds. The JSON output is complicated, but it boils down to a block for the PVS itself, a block for each CT sensor measuring overall electricity flow, and a block for each inverter (28 microinverters for me). Note it’s pretty slow, about 6-7 seconds to answer a DeviceList query.

The numbers I get from the PVS6 do seem to match what SunPower shows me in their consumer app.

sunpower-pvs-exporter

At this point I took a left turn and decided to install this monitoring setup. It’s a Python project that creates a Prometheus service from the PVS6 data, which Telegraf can import. The project also includes some Grafana dashboards. Looks nice!

I installed sunpower-pvs-exporter directly on the Raspberry Pi, no need for haproxy in the path. Then I set up telegraf to query it (just need to configure the URL) and insert the data in to InfluxDB. The resulting schema is a bit messy; Grafana is now polluted with lots of measurements with names like sunpower_pvs_power_meter_net_energy_watt_hours. And a whole lot more series inside that, and the values all are named “gauge”. Not awesome but I can work with it.

Unfortunately importing the sample dashboards from the project did not work. Some config did come through but not the queries. (Schema mismatch?) I hand-edited a few and got some stuff working but it’s not great. Also the schema is not a great match for Grafana so the queries are pretty contorted. All told I got discouraged at this point; if I’m going to have to do this much hand-work I might as well write my own code to pull data straight from the PVS6 JSON and output it in nicely aggregated Influx format.

Mysteries

My solar install has something weird; their estimate of my usage is wrong. They seem to think that in the middle of the day I’m using 6kW, 3-4x more than I use. Also usage goes up with solar power. I think maybe the CT sensors aren’t installed correctly. Or maybe this has something to do with not being fully activated at PG&E? The electric meter display looks correct, just not the SunPower monitoring, so I’m thinking I have an install problem.

The other confusion is arithmetic. I have one CT power meter labelled “GROSS_PRODUCTION_SITE” and one labelled “NET_CONSUMPTION_LOADSIDE”. That’s what’s graphed in the picture above, those two numbers. But note that’s net consumption; if you want gross consumption you need to add those two numbers. That’s baked in to the sunpower-pvs-exporter’s queries but it confused me at first. Particularly since my net consumption numbers from the power meter seem to be wrong.

jq

I took a quick crack at getting basic wattage output with JQ. This dumps the wattage of all the things in my report; the two meters and also the individual inverters.

jq '[.devices[1:][].p_3phsum_kw? | tonumber * 1000 | round] | @csv'

p_3phsum_kw appears to be the actual AC power production. I assume that means “3 phase sum”. It seems to account for reactive loads.

Thoughts

At this point I’m declaring victory for the day. I’ve got access to the data. I still need a system to massage it and import it into InfluxDB and I don’t think sunpower-pvs-exporter is it for me. Too many problems. Telegraf’s JSON plugin might be sufficient but I’ll probably end up writing my own Python code so I can massage things as desired. In particular I’m trying to think how to handle the data streams for all 28 inverters, that seems a bit unwieldy.

Some solar calculations

I just got solar installed on my roof in Grass Valley, CA. 28 SunPower SPR-A410 Panels for a nominal maximum of 11.5kW. I’m not officially done yet but in testing it seems to be working and I’m enjoying the spectacle of my meter running backwards. Looking forward to getting access to SunPower’s monitoring software and hopefully lots of data.

In the meantime I was curious what to expect for power generation. NREL has an excellent calculator called PVWatts that takes precise details on the panels orientation, location, etc and estimates how much power you’ll generate. It takes into account local weather, various inefficiencies in the system (I’m calculating a total loss of 11.5%), etc. Anyway the final number they give me is just about 15,000 kWH in a year. The proposal estimated 10% more but that could easily just be different assumptions about efficiency. The system is sized to just about zero out my historical usage over the course of a year and take full advantage of PG&E net metering.

How about monthly variance? November works out to 22kWH per day in November or an average of about 900W. And what about variance over time of day? Here’s a curve of total insolation from this calculator; this doesn’t include factoring the orientation of the panels.

PVWatts doesn’t have a nice display for this, but they do let you download per-hour calculations for the entire year. Here’s an excerpt for today

HourWatts
07:00195
08:00456
09:00775
10:001968
11:002579
12:003578
13:003619
14:005147
15:002705
16:001060

Interesting how skewed this is to the afternoon; I assume it’s because my panels are at an angle on a west-facing roof.

Anyway that’s all theoretical calculations. I’m excited to get actual measured outputs and compare. Soon!

Propane stoves do not produce soot

This came up on Twitter again today; do gas stoves produce soot? As measured typically in PM2.5, small carbon particles. The answer is no, at least not if your stove is working right.

The graph above is from my Kaiterra Laser Egg (with CO2 sensor) sitting about 10 inches from the burner on a Wolf CG365P/S/LP. I ran the hot burner - 18000 BTU - at full blast with no ventilation. It was turned on for 25 minutes at 10:07 am. As you can see in the graphs above there’s a noticeable increase in CO2 and temperature, but no PM2.5. None. (The CO2 rise is significant but on the order of what my body produces when I sit down near the sensor.)

I trust this sensor; here’s the PM2.5 levels from the same sensor (but 40 feet away) yesterday. We browned some meat about 7pm, which does create soot. I think that’s why people think their gas stoves create soot; they burn something and then blame the fuel, not the food.

Image

Note this is a propane stove, not natural gas, and that may make a meaningful difference. Propane is pretty much pure C3H8 and as long as there’s enough oxygen it burns clean, producing CO2 and water. There is an incomplete combustion that produces carbon monoxide and soot; that shouldn’t happen in a house and in fact the CO could kill you if it’s bad enough. Natural gas is a more complex fuel with various hydrocarbons. I don’t have a natural gas stove handy to test with.

There are other reasons to be concerned about gas stoves. Primarily global warming; that CO2 it puts out is a problem. An electric stove powered by renewables is better for the climate. But in a typical gas powered American house the gas stove is a relatively small contributor to CO2; the gas heater and hot water heater are far bigger contributors. Heat pumps are a higher priority than induction cooktops IMHO.

The other problem with gas stoves is other pollutants, particularly NO2. I’m not quite sure where that comes from, the fuels themselves contain no nitrogen, but presumably there’s contaminants or maybe some side effect with atmospheric nitrogen. From what I’ve read this threat is mostly theoretical and can be managed just by venting your stove to the outside.

I’d be remiss to not point out this article which directly says gas stoves alone put out PM2.5. That contradicts what I’ve read and my own measurement. More complex is their link to this study which finds that homes that cook with gas tend to create more PM2.5 when cooking. But the study is mixing several factors together: energy source, cooking oil type, cooking methods. It’s not hard to imagine that a screaming hot wok on a gas jet would put out more soot than a pot of soup gently simmering on an induction burner. As with all things environmental, the details get complicated.

Anyway: it’s your scorched bacon that’s making soot in your home, not the gas burner.

Low temperature cooking: Wolf dual-stack burners

I bought a new gas cooktop, a Wolf Professional Gas Cooktop (CG365P/S). It has “dual stack burners” for low temperature control: in addition to the main burner there’s a lower second burner with smaller holes just below the main burner. Having tested it I’m skeptical how useful this feature this is.

The dual stack presents a question when cooking: do I use the main range or the low range? Where do the temperatures intersect? I tested it by putting on a pot of water and waiting for it to come to equilibrium. This is for the small burner, of which there are three. There’s also a medium and large burner. I tested with the Liquid Propane version of the cooktop; it may be natural gas is different.

160F: Main burner, full low
167F: Low burner, full high
142F: Low burner, full low

So there you have it; the lowest high setting is about the same temperature as the highest low setting. It’s more or less a continuous dial. There’s not a lot of range of temperatures on the low burner.

I should note 160F is really low for cooking. Well below boiling water, of course. Well below a simmer too, that’s about 200F. Here’s some reference temperatures. These might not compare exactly to the temperature I measured in the pot of water. (The temperature on a dry or lightly oiled surface is going to be different than the temperature in water.)

284F: Garlic burns
235F: Soft ball sugar for candy
212F: Boiling water
190F: Slow cooking in an Instant Pot on low
167F: Dual stack burner crossover
160F: Hard boiled egg
160F: Conservative food-safe temperature for some things
150F: Cheese fondue (max temperature)
143F: Soft boiled egg
140F: Safe temperature for holding hot food
132F: Medium rare sous vide steak
130F: Chocolate tempering
120F: Rare sous vide steak

You could sorta sous vide something with this burner! Or use it instead of a double boiler (as the marketing suggests). Honestly, it’s very rare I’d ever need to go below the 160F of the main burner. The only thing I cook this low regularly is French-style slow scrambled eggs (which are delicious but takes patience.)

What I really want is fine control over the temperature range. Gas cooktop manufacturers have started to understand this. While they still market themselves on max output (and hot can be good!) they often talk about low temperature performance, too.

That being said the knob on this cooktop is really not helpful for fine control. There’s a total of 60 degrees given to controlling high to low; on my last cooktop I had 270 degrees. There’s more like 90 degrees of control for the low range, but then there’s so little temperature variance there that’s unnecessary. It’s just a bad UI.

Knowing all this now I’m not sure I would have chosen the dual stack burners from Wolf. Maybe it’s more useful on the larger burners. They’re fine, but they aren’t as useful as I had hoped. Also no doubt they complicate the plumbing. The igniter mechanism is the weak system in these products but now there’s a complicated valve that could go wrong, too.

I should add the environmentally correct position these days is to not buy gas cooktops in the US. Burning gas puts out CO2 and contributes to global warming. It’s not the biggest source of CO2, at most 9% of a typical house, house and water heating are by far the bigger contributions. However gas stoves also put out a lot of NO2, a pollutant that’s not healthy to breathe. That’s a real problem although venting to the outside mostly takes care of it. (NO2 is not a greenhouse gas, although N2O is.) Induction is the new hotness and has excellent precise heat control.

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.

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.

Automatic irrigation

I’ve got a bunch of automatic irrigation in my lawn, all Irritrol equipment. (What a brand name!) Some notes on how it works. This little video is very good.

The valve is a diaphragm ordinarily held in place by finely balanced water pressure. There’s a solenoid as part of the system that ordinarily is in a closed position so water can’t flow out a dump port. When the solenoid gets electricity it raises that stopper so a small amount of water is released. That lowers the pressure on the diaphragm, allowing the main water flow to go down the pipe. I think a spring is involved somewhere to hold the solenoid valve closed.

The key thing here is that the solenoid isn’t doing a lot of work. It’s moving a small part that controls a small water flow; it’s not turning a big valve or somehow manipulating full water pressure.

The solenoids are controlled via a 24V AC wired signal coming from an irrigation computer. When the computer turns the water on it supplies continuous power at about 0.5 amps. That’s a lot of power! But I’m not sure how many watts it really ends up being; I’m finding things that suggest it’s about 2W, not the 12W I’d naively assumed.

The nice thing is if the power is cut the valve automatically closes, there’s no need to energize it to get it to close. Also the 24VAC solenoids are standard; any ordinary irrigation controller can control any brand’s solenoids and valves.

The wires are usually direct buried in your lawn. You know, right under all the shovels and other tools. Hopefully they’re buried deep enough that they aren’t broken but in practice they get broken frequently. Guess why I’m reading about this? (Although in my case I think it’s a gopher, not a shovel.) PVC conduit is about $50-$100 for 100 feet, so next time I run a wire I might splurge for some protection. Irrigation wire tends to be fairly hardy plastic but not metal armored. Mine has 5 strands; 4 wires for signal, one common neutral. I believe these systems are grounded through literal ground.

Irrigation wiring is often a mess. I paid someone to trace a lot of wires. We found one run goes maybe 800 feet through four splices. That we found, those four were in boxes.

Unfortunately irrigation valves require power, which in practice means a wire. There are very few consumer solar controller options and what I could find is expensive; $100 or more for a single valve. There are multivalve solar controllers but they seem hard to find and priced for commercial use.

Battery powered irrigation controllers are more readily available. But two experts I talked to don’t like them. Partly because just being outdoors means they aren’t going to last forever. Also the realities of batteries. One guy suggested you need to change the batteries at least twice a year. And if you forget and don’t notice, your plants die. Also the battery powered controllers require special 9V solenoids.

TIL about OpenSprinkler, a modern open source sprinkler controller with a web interface. It looks to be a serious supported product, too.

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')

Wyze / dafang camera notes

I have a cheap Wyze webcam running Dafang firmware. Some quick notes because I keep forgetting this.

The camera is accessible at http://dafang/ when it is online. The default login is root/ismart12 but I changed the password.

The camera’s MAC address is 2c:aa:8e:a4:73:bd.

It is currently configured to record a timelapse (image every 15 seconds) and a video at 15fps.

Wyze camera v2 hacking

Wyze makes these amazing little cameras for $25; 1080p, infrared capable, two way audio. $25! The drawback is their firmware is very limited and you’re stuck trusting their web services. I am not willing to upload video from my house to a cloud server.

Solution: Xiaomi-Dafang-Hacks. It’s a hacker firmware you can install on top of the Wyze v2 cameras and various other similar ones that’s much more flexible. It’s designed for local use, you can get the thing to put out an RTSP stream, MQTT events when there’s motion detected, etc.

I followed this guide for setting it up. Basically it comes down to “flash the firmware to this funky .bin file you put on a MicroSD card. Then copy a new OS to the SD card for it to boot”. I think it would have worked the first time but I had a typo in my WiFi config file. I got it right the second time. Or as I told a friend:

Well I carefully ground the powders, then charred them in the brazier with aqua regia. I collected the vapours in the alembic and distilled them three times, using a clean retort washed with the tears of a child each time. I poured the final elixir into the Wyze camera and rebooted it and... no joy.

Ah hah! I found a spec of dirt in my elixir, perhaps rheum from where the tears were not adequately filtered. I re-ran the distillation process and watched the one flashing light for signs of success. Previously, the light shone a steady yellow. This time it winked out. Success!

Now the camera is listening on https://dafang/ and lets me do various things, all without involving cloud servers I know nothing about. Now then.. what was my plan for using this thing anyway?

Updates

After dorking around with this for awhile I’m much less impressed. The firmware seems pretty flaky to me even once installed reliably. Either that or the camera is.

The RTSP stream for H.264 is a mess. The encoding isn’t quite right so VLC often displays corrupted video, it’s like it’s missing key frames or something. Sound is 50/50 whether it gets transmitted or not. The record feature in the system doesn’t seem to even try to record stuff and writes a naked .h264 file, not a container format. (Also it works by using RTSP to localhost, lol.)

The thing there is a lot of support for is doing something in response to motion detected, using the motion(1) program from Linux. It’ll send messages to an MQTT server, or record a static JPG to the SD card, or send an email, or send a Telegram message (!). I don’t know if that stuff is any more reliable than anything else but I can see how it’d be useful.

I have this same experience every time I hack with camera software; there’s a big gap between “eh, kinda works” and a nice usable system with clean rounded corners. I really want to just buy a working home security system that’s Internet and camera centric. But it has to not send stuff to a cloud server out of my control.

Update 2

After most of a year away I revisited this blog post, grateful to have the notes! Got the hacker firmware up and running and updated. It’s nicer! Also the update process is a bit buggy. It leaves your old config files in place but some of those files needed updating. In particular there’s a DCIM_PATH set in the configs for various recording services that should be set to /system/sdcard/DCIM or a subdirectory thereof; nothing was recording locally until I enabled it. Simplest thing is to go to /system/sdcard/config and diff the .conf files with their .dist versions and fix things by hand. (“Simplest”).

I haven’t figured out if the firmware is more reliable than it was last time I tried it. A bunch of stuff seems flaky. You pretty much have to reboot when changing the configuration for anything; even stopping and restarting services manually doesn’t always pick up new configurations for some weird reason. Recording audio with the video does not seem to work. If you delete a file in the web UI you have to reload the page to see the other files remaining. Trying to do unusual things doesn’t always work as planned. For instance I set the video framerate to 15fps. The recordings I get from it are still marked 25fps, but the on screen clock shows me we’re now playing in accelerated time. Dumb.

“Hilarious” thing: the default login is root/ismart12. You can change the HTTP login password easily, but that doesn’t change the SSH login that’s still there. Nice. I also found there were Telegram and Matrix accounts pre-configured; no idea if those were demos, or some automatic thing generated for me, or if by default the firmware just shuttles your video to some random people somewhere. The services weren’t enabled so it was probably harmless, but geez.

Kaiterra Laser Egg air quality monitor

I bought an air quality monitor, a Kaiterra Laser Egg+ CO2. You can see the readings from it here.

I bought this device because Wirecutter recommended it and it had a CO2 sensor. AQI or PM2.5 is the thing everyone cares about when there’s smoke, but I was also interested in CO2 levels in my house. This sensor does both. I also liked that Wirecutter said it had a good simple UI. And it has good cloud integration for data access. I’m looking forward to finally setting up Home Assistant to monitor it.

Setup out of the box is very easy. Charge the device (it has a battery!), turn it on. Install a mobile app, hold a button on the device a few seconds, and the mobile app walks you through the setup. Which mostly is just typing the wifi password for your network. I’m impressed with how these things get easier every time I get a new gizmo. I assume a Bluetooth handshake was exchanged.

Second half of the setup is getting the device to upload data to a cloud server somewhere. That was also easy; create a web account, then scan a QR code on that site on my phone and it automatically adopted my devices. From there I can publish a “kiosk URL” anyone can read. The URL is hilarious; just some JSON with the device ID and a web token signature all base 64 encoded. Eh, it works.

Now I want to get into the details. The docs don’t say a lot but there’s more info online here. By default it publishes an AQI number which I think is comparable to numbers like what PurpleAir or EPA publishes. (But which exactly? I don’t know other than it’s a US number.) It also publishes raw numbers for PM2.5 (in ug/m3) and CO2 PPM. And even more raw, there’s also “0.3μm per 0.1L of air”, a number which I guess is just a physical measurement and not adjusted at all.

Sitting outside in smoky air, The AQI and PM2.5 numbers are roughly in line with nearby sensors on Purple Air. The CO2 sensor read about 600 even when outdoors. I think that’s supposed to be 400 (which is normal outdoor a ir), so I went ahead and pressed the calibration button and now the reading says 400. It has some complex self-calibration but maybe this will help it along. I sure hope the smokey air doesn’t mean the CO2 level is naturally higher as well.

The CO2 sensor can directly measure global warming! Back in the 80s “normal” was 335 ppm; now it’s 415ppm. More details and history in this article.

Update: I got the device working with Home Assistant. Was as simple as configuring the HomeKit device that HASS found, which was apparently the Kaiterra. Type in the pairing code on the Kaiterra screen and I’m done.

Generator notes after 42 hour outage

We used our new generator in anger for the first time during a 42 power outage thanks to a PG&E PSPS, their response to their murderously unmaintained power network. It mostly worked fine and we didn’t even really notice any difference. Main problem was our ISP went down; that’s not our generator’s fault.

We used 10.7% of our propane tank for the outage; 54 gallons, or about 1.3 gal/hour. Or $150, if you look at it that way. The spec sheet says the generator uses 2.5 gal/hour at half load, 3.9 at full. It’s a 22kW generator and we’re using it nowhere near even half load. We average about 1500W over the day, so just 7% of capacity, but we’re apparently consuming 33% of max fuel. Not a big surprise but useful numbers to know.

Aside from the noise the main way I knew I was on generator is the lights flickered. And the cheap UPS in the server closet kept clicking off and on. (The fancy power conditoning UPS did not). Last time I looked at this I traced it to the well pump turning on; the momentary load generates a tiny brownout before the generator catches up. This time I noticed the oven heating also caused this kind of fluctuation a couple times a minute, a little weird since you’d hope the heating element was a steady load.

Turning off das Blinkenlights

In my last post I made fun of the RAM with LEDs mounted on it to flash in gaudy patterns. I’m serious; that crap annoys me. And for some reason blinking lights are all the rage for all sorts of PC stuff, you can’t get away from them. So I finally figured out how to turn them off on my PC.

The CM2 had the coolest lights ever. Also the display was totally for show.

ASUS X570-Pro: has a series of lights blinking RGB patterns on the motherboard. These are called “Aura” in the BIOS and you can turn them off there. These motherboards also have a whole special hardware device for driving individual LEDs in software; I never installed those. And the BIOS also makes a distinction about “functional lights”, which I imagine are a few LEDs and the Q-Code 2 digit display that tell you basic useful things like “is the motherboard working?” I left those on.

EVGA GeForce 1080 FTW: this has some very bright LEDs on the back, right at the display connectors. The NVidia Experience bloatware contains a standalone program called LED Experience that you can use to configure the LEDs. Setting effects to “off” results in the lights still being on. So instead I selected the effect of a constant color at brightness zero. Seems to work.

UPS vs generator: PFC

I mentioned before my cheap UPS units didn’t work well on generator power. If something turned on (like a pump) that drew a lot of power the generator briefly didn’t keep up, the power dropped, and the UPS would switch to battery. Worse it would fail on my gaming PC, losing power entirely.

These are cheap UPS units, the minimal failover possible. My best guess why my gaming PC would shut down is it was drawing too much power. I never observed the thing taking more than 330W and the UPS was rated to 450W, but maybe that was enough to overload it. But the general unhappiness on generator power, the switching to battery, that seemed bad and fixable.

So far so good with a new UPS, a relatively expensive 1000W unit called the “CyberPower CP1500PFCLCD PFC Sinewave”. I think the key feature here is the PFC Sinewave, which is advertised as “provide sine wave output and correct minor power fluctuations without switching to battery”. That sounds like some form of power conditioning, even when not on battery. I think it’s a step up from basic Automatic Voltage Regulation, which “stabilizes the incoming AC signal to maintain output power at a nominal 120 volts by controlling high and low voltages without resorting to battery power”. Maybe AVR just clips the power at 120V while PFC actually creates a smooth sine wave? Dunno.

The PFC unit costs 33% more than a simple AVR. It may be overkill, I wonder if AVR would be enough to smooth out generator problems. Not sure I care, at this point I’m willing to pay a premium for things that work well.

The step up from this AVR/PFC stuff is a UPS that’s always running on battery. There’s AC power coming in to charge the battery, and AC power being generated off the battery, but AC never flows direct. These units are significantly more expensive (2x or more).

Oh, one downside of this CP1500PFCLCD is that it runs a fan when it’s on battery. Fairly noisy. Presumably a heat thing.

Ubuntu 20 vs Sonos: SMBv1

After I upgraded to Ubuntu 20.04 my music library stopped working on my Sonos. Turns out this is a Samba problem. Somewhere along the line Samba disabled SMBv1 by default; apparently it’s insecure and old. However some clients like Sonos only support SMBv1, so the result sucks.

The fix is easy. Add this to your smb.conf and restart Samba

server min protocol = NT1

I also have these lines lurking around for other obsolete clients, but I’m not sure they even work any more. They aren’t necessary for Sonos.

ntlm auth = yes
nltm auth = ntlmv1-permitted

Sonos sure could do a nicer job of error handling. The only error you get is “it failed” with a link to some irrelevant docs about Windows stack size. I figured out the real problem in this Reddit thread.

Apparently this is also a problem with Synology servers, which recently switched to SMBv2 or above only.

I don’t know if there’s a security risk in exposing SMBv1 this way. It’s all behind my firewall so I’m kind of hoping the Maginot line keeps me safe. Also it’s a freakin guest read only fileshare, why is there any login protocol at all? Ugh.

It’d be nice if Sonos upgraded to a newer SMB client, but apparently they’re not in a hurry to. And now given the major platform switch plus their emphasis on streaming services over local music, I’m a little afraid SMB may never be updated on Sonos.

Power monitoring generator, well

We have a new generator, since we live in a third world country where PG&E is unable to provide reliable electricity. It works pretty well, a fancy Generac standby unit with load shedding. Even has a decent website monitoring the generator via WiFi, also there’s hacker software for reading the generator’s state from a serial diagnostic port.

Anyway, when we’re on generator power the UPS units sometimes complain, switch to battery power briefly. I think I’ve also noticed the lights flickering. That got me worried the generator was putting out bad power so I hooked up my IoTaWatt to monitor the AC power.

The IoTaWatt’s main function is to monitor power draw through individual circuits. It directly measures current. But it also monitors voltage and frequency via an AC transformer sensor. Near as I can tell it samples that data many times a second but the most detailed data I can get from the status API is once a second. The most detailed graphs are every 5 seconds.

Generator load

Voltage and Frequency. Generator switches on at 12:06

As the above graph shows, the voltage and power doesn’t really change much when we switch over to generator power. Both PG&E and the generator are providing about 122V. The generator’s frequency isn’t quite as stable as PG&E was but a variance of ±0.1Hz isn’t that bad. (PG&E sometimes approaches that variance too.)

Well-related power blip

The graph above shows what happened as 12:17:30, one of the times my UPS kicked in. Turns out just then the well pump turned on (the red line), adding about 1.5kW load (or about double total power, the blue line) in that instant. The generator didn’t quite react fast enough. The power draw of some other loads (yellow and purple, basically room lights) dips briefly. More telling: the frequency of power, the black line, drops significantly, by nearly 0.15Hz. That’s the sign the generator is overloaded, it starts running more slowly and the frequency drops. It recovers quickly enough, but it’s enough to make a sensitive UPS unhappy and cause a visible flicker in the lights. Note the voltage (green line) doesn’t notably drop; I imagine the generator has a voltage regulator that smooths this out.

So that’s why the lights flicker and the UPS complains. I think that’s just a limitation of a consumer generator. It’s plenty of power to make everything run, but it’s not quite as clean as when you have utility power.

Well

Looking at this reminded me to take another look at what the well pump was doing.

It’s still coming on every 30 minutes or so even when there’s no water demand at all, which suggests a leak somewhere. I know it’s not outside, because I turned that valve off. I’m pretty sure it’s not inside either, I’d have noticed. Maybe the well is leaking back into itself, against the check valve? Dunno. Like I said before it’s wasting about $0.50 of electricity a day, but otherwise seems mostly harmless.

Above is a cumulative graph of well power usage over 24 hours (blue) with transitory power (green). As you can see we use a lot of water overnight, when the irrigation is running, about 5kWH or $2 worth. The well doesn’t stay on continuously for much of this, other than one period about 6:15am. Our water system has no buffer of any kind; no tanks or reservoirs.

TCL Series 6 TV

Just got a new TV, a TCL 6 Series and couldn’t be happier. I bought it after this glowing review. Pretty much every other review says the same thing; excellent picture quality for the price. It’s quite cheap even for an LCD TV, and definitely way way cheaper than an OLED.

I’m not able to judge picture quality except to say it looks great to me. It’s better than the 2013 era Samsung panel it replaced; brighter, bigger, sharper. The 4K 60fps demo reels look amazing. Of course the default picture settings are oversaturated garbage, but fixing that isn’t too hard.

The key picture setting for this screen is “movie mode”. That means “don’t blow out the colors”. However when you enable that it also for some dumb reason defaults to “warm color temperature”, which shifts all the colors to the red. So set that back to normal. Also it turns off Local Contrast which is one of the nice features of the set, so turn that on to high. Then turn off all the fancy motion interpolation type stuff and it looks pretty great.

I particularly like that there’s a quick setting for “darker / normal / brighter”, which means you might actually change that based on time of day and room lighting. There’s also a game mode for HDMI inputs that has decent latency (19ms, or just about one frame).

One nice feature for this set is that its operating system is Roku. Not some dumb badly designed TV manufacturer stuff, just good ol’ Roku with its open ecosystem of third party channels. I’ve been using Roku devices for years, mostly for Plex and Netflix and Amazon, it’s nice to have it native in the TV. I managed to get ARC (“Audio Return Channel”) working so the sound is still being sent to my fancy AV receiver for decoding.

Speaking of the receiver, I’m less clear on what to do with it now. It’s limited to 1080p (or 2160p @ 30 fps, lol). And seems to block HDR too, or at least my PS4 won’t do HDR through it. I guess I could just plug all my inputs in to the TV and use the receiver solely as a digital audio decoder + amplifier. The wiring is tidier if the receiver is a switch, but then I can’t pass 4K/HDR content through it. If I didn’t already have speakers installed in my walls I think I might just get a nice soundbar and call it a day.

Still haven’t considered the joy of making my old Logitech universal remote drive the new system. Need to settle down how the receiver fits in first.

4K is still such a bandwidth hog I can’t imagine I’ll be using it much if any for watching video. Would like it for games though. HDR interests me much more, it’s great we can finally get higher contrast ratios on TV sets. Apparently there’s competing standards for HDR, awesome. This panel supports both Dolby Vision and HDR10, which I guess are the two most common formats. Hopefully that’s good enough.

Cyberpower pwrstatd revisited

Eight years ago I wrote a blog post about the Linux software for my UPS. I was pretty negative about it. What’s funny is now 8 years later I’d forgotten about that post and re-installed that software and thought “hey, that’s not so bad”. Mostly because they publish a dpkg which just works. But revisiting my post I see my complaints still apply: requires root, no source code, aggressive shut down options. They’ve even added a thing now where it schedules the whole UPS to turn itself off 10 minutes after the outage. WTF?

Anyway, reconfiguring the daemon so that it never shuts anything down itself, it’s OK software. Not great, not bad. Mostly what I want is the munin plugin for monitoring the thing. I put one in my blog post; someone picked it up, improved it, and has it on Github now. Open source works!

OTA digital TV notes

Did you know TV shows are broadcast for free over the airwaves? It’s amazing; no need to pay the cableman or satellitelady their rent. At least, if you want to watch ad supported non-premium programming.

OTA digital TV has gotten pretty simple. Basically there’s just MPEG-2 streams floating around at ~600MHz for the taking. I just got a tuner and antenna to pick them up. An HDHomeRun Connect Duo for the tuner and a Clearstream Eclipse antenna. Total cost: $100 to $150. There’s other options, see Wirecutter.

So far so good; without any effort to set up the antenna right, in San Francisco I can get 46 channels. Really it’s 12 channels, but there’s multiplexing so where channel 2.1 is KTVU in HD, channel 2.2 is KTVU-SD and channel 2.3 is a random movies channel.

The diversity of channels is pretty neat. I’m enthralled by channel 60.5 PJKFNX which is showing First Nations Experience, a whole channel of indigenous peoples programming. I think YouTube is the only other place I could find content like that.

Devices

The antenna is nothing exciting. Some flat piece of floppy vinyl with some very stiff coax cable coming out. This particular Eclipse antenna has a 20 dB amplifier attached to it. No idea if the amplification is necessary, or if more would be better.

I like the HomeRun tuner. It takes power and antenna in, has ethernet out. That’s it. The device serves MPEG streams and some diagnostic info via a web interface. Very simple and hackable.

Software

I’m currently watching via the HDHomeRun Windows app. It’s a fine bare-bones viewer, backed with some sort of program guide. They run a DVR service too; I wonder if they even bother recording anything or if it’s more of a Sling-like setup. There’s mobile apps too and I think a new Roku app.

The HDHomeRun includes a basic HTTP API for programmatically getting a list of channels and watching MPEG-TS streams. This caveat is fascinating

The client will have a slightly different concept of how long one second is due to slight differences in the client clock timebase vs the broadcaster clock timebase. The client must adjust its concept of real time to match the incoming video stream

No one watches live TV anymore though. I bought this in part because I finally got a Plex Pass and one of the value-adds for that is Plex has DVR software. Setup of the Plex DVR was easy, the program guide is good, and it seems to record OK. Recording seems to run a transcoder stream at 150% CPU on my system which is odd, I have both commercial skipping and transcoding compression disabled. Maybe it’s just having to collect and assemble the chunks. The final output is a .ts container that has what looks like the broadcast MPEG-2 and AC3 streams in it. I’ve set up recording a show regularly, we’ll see how it does.

One thing I’ve noticed is a lot of the older video I’m seeing is interlaced. And I guess decombing isn’t a standard feature. It’s ugly.

Update the DVR seems to work great. I also enabled commercials skipping and transcoding for smaller storage. It seems to work OK. Commercials skipped even in a live news broadcast, which suggests they’re doing some live detection mechanism and not relying on a content database.

Transcoded to 6Mbps 720p (H.264) using about 1.5 CPU cores out of my system’s 8, so the impact isn’t too bad. Resulting file is 3GB/hour for 720p, which is not great, but for a fast transcode it’s not bad. You can see the settings they’re using here; as the commenter points out, a lower CRF would be a nice space / quality tradeoff. Right now it’s not configurable.

Channel availability

I’m currently getting channels 2, 4, 5, 7, 9, 38, 42, 44, 50, 54, 60, and 66 (with many variants). That’s the major “broadcast” networks (ABC, CBS, NBC, and regretfully FOX) plus a bunch of other random stuff. Most channels have 99%+ signal quality, but 60.5 is only 84%. Still looks fine to watch. Note this testing is being done right before the FCC repack when stations get renumbered to free up some bandwidth.

There’s several sites that’ll let you check what channels you should expect. Results below. To simplify things I’m assuming if I get one channel I get all the other related multiplexed ones.

Note each test has a different list of stations. I think what my antenna auto-detected is a strict subset of all of those. What these online sites tell me is I can probably get a few more channels with better antenna placement. I will note I did a second scan and got the exact same result of 46 channels, so at least it’s stable.

AntennaWeb: 2, 4, 5, 7, 9, 11, 12, 22, 38, 42, 44, 45, 50, 52, 54, 60, 66

FCC: 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 14, 22, 26, 28, 36, 38, 44, 48, 54, 60, 65, 66, 68

TabloTV: 2, 3, 4, 5, 7, 9, 11, 12, 38, 42, 44, 45, 48, 50, 52, 54, 60, 65, 66

TVFool: see picture below. I’m not sure their database is current, but I love this nerdy visualization.

UPS battery lifetime

I use cheap UPS units for battery backup. Things like the CyberPower CP825LCD, basically power strips with a 12V battery and an inverter. They work OK.

For a few years. The lead acid batteries in them eventually wear out, and after 3-5 years they don’t hold a useful charge anymore. They lose capacity over time, too. Unfortunately these cheap UPS units don’t have a good way to monitor their battery health. You only notice when the power goes out and find you have 5 minutes of battery backup, not 15. Or else the unit just fails entirely and starts beeping confusingly or doesn’t provide power, even when plugged in.

Checking battery health

There is a way to easily check the battery life though, at least with CyberPower UPS units. Their PowerPanel software connects to the USB port on the UPS and gives you info on battery status. Including a self test which calculates battery capacity in the moment

Before I clicked the “self test” button it was saying Battery Capacity was 100%. But that was a guess based on the fact the battery was fully charged. Self test swaps over to battery power for a couple of seconds and then measures drain. This battery really only has 1/3 capacity which means it’s time to replace it.

You can also do a simpler version of this self test by just yanking the plug and seeing how long the UPS lasts. Works better if the UPS has some sort of display of battery life remaining. But I found that a little confusing; this software test works better.

Every UPS I’ve had also runs its own self test regardless of whether there’s any software talking to it or not. I’ve never seen this test report any useful information, though. Maybe when it fails that’s what sets the UPS off on the endless beeping until you change the battery? Dunno. I sure wish they’d invest a little more into communicating to the user this necessary maintenance.

One other neat thing about the software: they report wattage used as well. For some reason the CyberPower LCD units don’t show that on the LCD screen.

Another blessing of the software is it lets you turn off the beep alarm when the power goes out. I already know the power is out, I can tell because of how dark it is. I don’t need every UPS in the house beeping at me.

These UPS units offer software for Windows, Mac, and Linux. The last time I used the Linux software (from APC) it was scary bad code running as root so it could run shutdown. But it did reliably output numbers on battery activity that I could graph with munin.

Replacement batteries

The simple solution to a failing battery is to replace the battery. The CP600LCD I have that just failed is $70 new, or $35 for a battery from CyberPower. Not great. But fortunately lead acid batteries are standard and common; as long as it’s a lead acid battery with 7V, the same Ah capacity, and the same physical size, it’ll work. (Probably any capacity battery will work but if you want it to fit the case, you’ll want the same size.) I ordered an ExpertPower battery for $17.50, or just half of the CyberPower official price.

The one thing to look out for is that the connection terminals come in two sizes: F1 and F2. F2 is wider. My UPS has F2 connectors but the new battery has F1 spades, I’m hoping it’ll still fit well enough to just work. You can also buy very simple adapters, metal clips, but the Amazon price on something that cheap is ridiculous.

Don’t put your old battery in the garbage, they are hazardous waste. Instead dispose of them like you would a car battery. Most trash collection companies have a special pickup or dropoff option for them. Places like Auto Zone and Home Depot often take car batteries for recycling, too.

Better batteries

Battery tech has come a long way; why are we still using old lead acid batteries? Mostly because they’re cheap, and UPS units don’t need to be compact or light. There are other battery tech options though.

Our ordinary lead acid batteries are “VRLA”, sealed. There’s a different type of “flooded” lead acid battery that’s open. They work for more cycles, but they are constantly venting hydrogen and needing distilled water added to it. So not really practical for home use.

I’ve never seen a NiCd or NiMH consumer UPS. The articles I’ve read say they are just too expensive for the performance, although I’ll note that didn’t stop laptop manufacturers in the 90s / early 00s. There are some hacker projects you can find building cheap 5V UPS backups with NiMH AA cells for low power devices like Raspberry PIs. Sounds fun.

As for lithium, I think it’s just too expensive. APC does build one consumer lithium-ion UPS, the APC BG500. But at $270 for a 500VA backup it has a hard time competing with the $50ish 500VA from lead acid batteries. It’s smaller and the battery will last twice as many years, sure, but for 5x the price? There’s a range of high end rackmount lithium UPS units for datacenters where compactness matters, but now we’re talking thousands of dollars.

IoTaWatt energy monitoring

I’ve been playing with an IoTaWatt energy monitor. This is a bit of hacker-friendly kit that measures electricity usage on each circuit in your breaker box. It gives you real time wattage data with 5 second samples and makes it much, much easier to understand where power is going in your house.

There’s a lot of products on the market now that do this kind of thing. Many are full consumer turnkey products like Neurio or Sense. They have cloud based monitors and some fancy pattern recognition to tell you things like “your refrigerator is failing”. I opted for the more hacker-friendly one, both to keep the data private and to be able to play with it more myself. See also OpenEnergyMonitor. I tell you, what I really want is something like a Leviton Smart Load Center, where the panel and breakers do this kind of monitoring themselves. (Price seems to be ~$4000 for a house, compared to $1500 for traditional dumb breakers.)

This post is long because I’m in the middle of learning about this stuff. But after running it just for 24 hours I learned some things like I have a leak in my water system somewhere, that my office uses 80W even when everything is “turned off”, and just how much electricity videogames use when you’re playing them. Having precise numbers for all this stuff is great.

How it works

The key sensor technology is the Circuit Transformer, a ~$10 metal coil you clamp around the hot wire of a circuit you want to monitor. The magnetic field in the main circuit induces current in the CT, which you can then read out the other end as either variable voltage or amperage. The common split-core CTs are installed without disturbing the wires in the breaker box at all, and nothing is electrically connected. Even so it’s important to keep the CTs plugged in to the controller box; if they aren’t they can build up a dangerous charge.

The CTs are plugged in with 3.5mm jacks to a controller box. The IoTaWatt is an Arduinio-class system that basically takes 14 CT sensors as input, stores the data on an SD card, and has a web interface over WiFi. The custom software (not Unix) includes a decent graphing interfaces and enough APIs to load the data up to some other system like Emoncms or your own stuff. It seems pretty good.

Installation

A temporary installation isn’t as hard as I feared. You take the panel for your breaker box off, exposing all the wires. Then you clip the CT sensors of the appropriate sizes around the wires you want to monitor. Done! You don’t even have to turn the power off first although obviously you should to be safe.

Of course it’s not so easy. The tricky part in North America is we use split phase power. We get 240V from the power company but it’s split into two out of phase 120V legs. The CTs only monitor a single leg, so if you’re measuring a 240V circuit (like a well pump or a dryer) you need to use two CTs, or pass both hot wires through a single CT, or double up the measurements. Also it’s easy to install a CT backwards, so the values are all the wrong sign. Fortunately the IoTaWatt has many software tools to compensate.

The other problem is a permanent installation. All the CTs and wires take up a lot of room in the breaker box. And the IoTaWatt also has to go somewhere, and be plugged in to two wall transformers. If you have a big breaker box you could just leave it inside (if code allows), but I’m not sure how well WiFi works there. I haven’t figured out a good permanent install.

What I measured

I just went with a simple temporary install to get some basic measurements. I only measured for a subpanel in my house and wasn’t able to get some of the more interesting things like the refrigerator. What I did get:

  • My office: a simple 110V circuit. This is where I spend all my time and includes my PC, my PS4, and my TV. Also overhead lights.
  • Furnace fan: simple 110V circuit? Gas heat, so fan only.
  • Pool: full 240V circuit. I’m only monitoring half of it, so I have to double the numbers reported. This may not be entirely accurate if the load is not balanced. But my 385W pump load shows up as 200W on the graph, so doubling is roughly correct.
  • Well pump: a 240V only circuit. I should double the numbers reported.
  • Septic pressure dose pump: another 240V only circuit, should double.
  • Subpanel supply: a full 240V circuit, with two monitors installed. I believe it’s correct to sum the two numbers when measuring the load.

Data and Graphs

Here’s some data I collected after running the monitor for 24 hours.

Power usage for individual circuits (already doubled as needed):

  • My office: 4600 Wh
  • Furnace fan: 1200 Wh
  • Pool: 3200 Wh
  • Well: 1400 Wh
  • Septic: 700 Wh
  • Total measured: 11,000 Wh
  • Subpanel supply 1: 7400 Wh
  • Subpanel supply 2: 9300
  • Total subpanel: 16,700 Wh (or about $4/day)

Office and Pool

Office and Pool

Here’s a graph of power usage over the course of a day. The yellow line is my office, the blue line is the pool.

The pool is easy to understand. Note the graph is at half scale, I forgot to click “double” in the setup. The filter pump turns on around 2am, has a brief priming jolt, then runs steadily at ~400W until 6am. There’s a 30 minute window of very high usage, 1800W, that’s when the second pump turns on to run the sweeper. There’s also an occasional usage of power during the day, well below 100W. That’s a little pool cover pump I have that runs when there’s enough water. It was raining this day. The pool uses 3200Wh a day or $8.

My office is harder to understand. At night it’s a steady 80W; that’s with most everything turned off or in sleep mode, but I still have a bunch of network equipment and vampire loads from TV gear. The load in the morning of about 200W is when I turn on my computer and do low power stuff like reading web pages. It spikes up to 400W when I’m playing a game on my PC. The 350W load is when my PC is relatively idle but I’m playing a game on my PS4. The TV seems to also spike the whole circuit load up to 200W. There’s also some overhead lights in the mix. Putting this all together, I can estimate these loads:

  • Constant load 24/7: 80W
  • Idle PC use in morning: +120W
  • PC gaming: +300W
  • PS4 gaming: +250W
  • Watching TV: +100W
  • Full day: 4600Wh, or ~200W average.

Furnace, Well, Septic

Furnace, well, septic

The furnace fan (in red) uses 120W when it’s on. It doesn’t run at night. It averaged about 50W this day.

The septic pump runs a few times a day; this value should be doubled. It’s sorta correlated to water usage but not really, it’s not as simple as “every time I flush the toilet”. It’s a high load when it runs, 2000W, but only briefly. Average daily usage is 30W.

The water pattern is more troubling. (Again, values in graph should be doubled). My well pump is coming on every 30 minutes and it’s basically uncorrelated to water usage in the house. That to me says I have a leak somewhere. I turned off the outside water while monitoring this and the frequency went from ~25 minutes to ~33 minutes, so while there may also be a smaller leak outside the big loss is coming from the indoor plumbing. I’m pretty sure I don’t have any leaky faucets or running toilets. Maybe it’s the well itself and the water system’s pressure tank. Apparently a common failure mode is that the check valve leaks pressurized water back up into the well, so it has to refill itself every once in awhile. The power usage isn’t so bad (60W average, or $15 a month) but I don’t want to waste water. And it’d be better not to have the wear and tear on the pump.

Subpanel Inputs

This is the graph of the power going into the panel. Both legs of the 240V circuit, I believe it’s correct to sum these. Not sure why they aren’t balanced more? The yellow line seems to go higher when I’ve got lights turned on and the office is busy, so maybe it’s uneven 110V loads. Not sure it really matters anyway. Note that the 5 circuits I’m monitoring in detail only add up to 11,000 Wh of the 16,700 Wh the panel supplied this day. I’ve got a bunch of other circuits I’m not monitoring, I guess they add up to about 1/3 the usage.

Conclusion

I like this IoTaWatt! Even with a temporary install I think I could learn enough in a few days to model out all the power usage of my house. Idle load, average load, and max load for every circuit in the house. That will be hugely helpful when designing a power backup for PG&E’s stupid outages, whether a generator or a battery.

What I really want is to have this kind of monitoring all the time, storing history in the background. Would love to see how my usage patterns vary over time, or spot new water leaks, or realize when the refrigerator is failing. I think the IoTaWatt is sufficient to do that, at least if you can find a nice way to install it permanently.

I do think an integrated system like the Leviton Load Center makes more sense though. I wonder if their system is in any way open? I fear the answer is no. No hint it works with any of the open source software, and Leviton doesn’t even have it working with Alexa yet. I bet there’s a way to scrape data out of the web app.

Bonus

Another graph, this of the next 24 hours. All the doubling, etc is done correctly.

Some rough watt-hour numbers

PG&E’s incompetence means I’m thinking about electricity storage recently. Some rough numbers:

Devices you charge and use:

Batteries you can charge things from:

There’s a huge variety in the stuff I lumped together as “charger”, particularly how well they furnish AC or DC for usage. Your car battery is only as good as the inverter you plug into the stupid cigarette lighter, for instance. That EGO Power Station is designed to be a full portable AC power solution that can put out 3000W of clean power (well, for 20 minutes). Briefcase solar systems can also recharge themselves from solar panels.

I currently own a Powercore and two spare UPS units, for a total of about 275Wh. With that I can charge my laptop 4 times, my iPad 8 times, or my phone 25 times. I also have the car which is good for about 3x more charging just off the battery, which doesn’t count idling the engine to keep its battery charged.

Update learned a couple of things in the latest outage. The car inverter works pretty well, but my 2017 A3 only puts power out the 12V sockets if the engine is running. You can leave it running unattended if you start the engine with the door open. The car manual says 120W maximum out the socket, so my 300W inverter purchase is overkill and I guess I could blow a fuse. Other thing I noticed is the inverter was no good for trying to charge a CyberPower 875AV UPS; the display on the UPS showed it was picking up a little charge but not really. The cheap TrippLite UPS I have did seem to charge better from the inverter, or at least the inverter got awfully warm.

My electric bill says my house averaged using 35,000 Wh a day for the last year. A lot of that is optional load; in a low power situation I wouldn’t be running the pool pump, the electric oven, etc.

A single rooftop solar panel generates roughly 300W maximum, or 1370 Wh per day (average over the course of a year in NorCal).

x265 transcoding

I continue to re-encode video I get into x265. It’s much smaller, which helps both with storage and bandwidth. And it looks fine to my tin eye.

My script has evolved over time. This is what I do now:

ffmpeg -i “$1” -map 0 -c copy -c:v libx265 “${1%.*} x265.mkv”

In theory this leaves all the audio and subtitles alone, just copies them, but re-encodes the video in x265 with default settings.

I was in a hurry today and so got fancy with resizing the video to 360p and using a faster / less accurate encoding setting.

ffmpeg -i “$1” -map 0 -c copy -vf scale=-1:360 -c:v libx265 -preset faster “${1%.*} x265.mkv”

Quality definitely suffers for this, but I can encode at 3-4x playback speed on my CPU this way.

Door King 1812 programming notes

I have a gate at my house. It’s driven by a LiftMaster Miracle 1 motor unit, which in turn is commanded by a Door King 1812 gate controller. This was all installed around 2000 but the design probably predates that. I got deep into the setup of these things trying to make the gate do what I want, and failed. Mostly because I don’t understand the Miracle 1.

The Door King 1812 is still sold today, still supported. The manual is here, I reference it by section number (like 2.2.1 for master code).

Programming it seems daunting. I tried at first to get it working using the PC software and a modem, but that requires a monthly $$ subscription to use and seemed pretty rickety anyway. Instead I used the touchtone programming interface. This is overwhelming at first, but really not so hard.

The key thing here is the gate controller is wired into my phone line. It’s listening in-line and can be programmed to work as an intercom using the phone wires, to synthesize a ring on my phone line, and even to answer and make phone calls. I talk to the controller via my phone; just pick up and press *7 at the dialtone to get the gate’s attention and it answers with a beep.

One wrinkle: some steps require you press 0 and # simultaneously to end programming. (I write this as 0-#). I found neither phone keypad I have is able to send two tones at once. I ended up having to use the gate keypad to program things so I could enter 0-#.

Here’s some stuff I learned:

Master code. You need this to do anything else. Old ones had a default of 9999, newer ones have a default of the last 4 digits of the serial number. Someone had written mine down on a sticker inside the keypad box. See 2.2.1 for setting a new master code; you open the keypad box and flip a switch. I’ll use “xxxx” to stand in for this code later.

Attention. The gate listens for a code, *7 by default. It beeps when it responds. All commands to the gate start with that. See 2.2.2 to change the number 7. You can inspect the state of the gate relays with this attention command, as described in 4.11. After a brief delay the gate will beep at you to tell you which relays are open.

Basic operation from house phone. *7 9 to open the gate. In detail: the controller is programmed to respond to simple commands on digits 1-9, described in 4.13. *7 gets the gate’s attention, and then it’s sent the command 9. These commands are called “tone open numbers” in the manual and their programming is explained in 2.3.2.

Basic operation from keypad. #zzzz to run an entry code program, described in 4.4. Typically this is something to open the gate. You program codes (like #1234) and give them to friends who you want to get in.

Program strike time. Described in 2.3.1. Various commands tell a relay to operate for N seconds before turning off again. That’s how you have it open the gate for N seconds, then close it again automatically. I believe my gate was programmed to do this for 2 seconds (much less than the time it takes to swing the gate). I think this is the way the Door King signals the motor controller; a short pulse on the relay.

Program tone open number. Described in 4.13 and 2.3.2. *7 *05xxxx 1* 987#* 0-#. This is super complicated. I’m telling relay 1 that when I press 9 I want “momentary activation” for the strike time, when I press 8 I want “hold open”, when I press 7 I want it to deactivate, and nothing for the 4th command (#).

I’ll be honest and say I’m confused about what I ended up with. *78 seems to cause the gate to hold open. Then *78 again will cause it to hold closed. *77 doesn’t do anything?

Program entry codes. Described in 2.6.1, see 4.5 for definitions of “momentary” and “hold”. I entered *7 *02xxxx 18* zzzz* 0-#. That sets up the new entry code zzzz to location 18, a “hold” location. That should cause it to hold the gate open when #zzzz is entered, then close when #zzzz is entered again. If I’d set it to a “momentary” location again like the number 11 then it would only open the gate for the strike time, then close it again.

Security hardening. The controller can answer and make phone calls. I don’t want that. Sections 2.3.5, 2.5.1, 2.5.3 all seem relevant things to turn off.

Garage door remote. My gate also comes with garage door buttons to open. The Door King doesn’t have anything to do with this; it’s wired directly to the Miracle 1.

There’s more the gate controller can do. You can set it so some codes only work at certain times, or certain days. You can program it to accept and make calls. Etc etc. I didn’t do any of that.

The relay and the Miracle 1 motor. This is key to the whole programming. All the Door King is doing is turning a relay off and on. What does that mean to the motor?

I got lost here. The Miracle 1 isn’t really programmable, but does have a few configurable options. I believe ours was configured so that a signal from the relay means “open the gate, wait 45 seconds, close the gate again”. What I want is a signal to open the gate, then a second signal to close it again. The Miracle 1 manual suggests that’s not really possible but I know it used to work that way, so it must be. But in the process of tinkering with it I got the gate in a state where I couldn’t even make it open reliably. It may be that something’s wrong with the limit switches or the power supply. I got fed up and quit.

AXIS 1034-W security camera setup

A couple years back I bought a wireless security camera, an AXIS 1034-W, and did a halfass setup using the ancient Linux program “motion” to do the heavy work of recording video. I just revisited all this using the on-board features of the camera itself and it’s so much better. This product is obsolete; the newer Axis M1065-LW looks better in lots of ways and some of these notes probably don’t apply. And there’s a whole world of other manufacturers making security cameras, but for me anything with cloud based video uploading like NestCam is a non-starter.

The hurdle is this old camera is really designed to be configured in MSIE, with ActiveX controls (no really) and a Java applet (I know, I know!). Once I got IE 11 fired up it got a whole lot easier to set up the camera. You literally can’t configure the motion detection without running Java. Dumb!

Anyway I’m not going to document everything I did. But the basic thing was to enable audio recording (off by default for some reason), then set up a “quality” stream profile to capture 1280x800 H.264 with audio. Then I configured the image motion detection to trigger on very small objects (ie: far away from the camera) and set up an action for it to record any detected motion to an SMB share on the local network.

End result is pretty good. The main drawback of this camera model is it doesn’t illuminate the scene nor record with infrared. So it doesn’t work very well in the dark. Newer models do. It does have a passive infrared sensor for motion detection but it doesn’t seem to work well enough.

 

2017 Audi A3 map update

Wanted to update the maps in my car’s navigation system. To Audi’s credit they provide twice-yearly upgrades via a variety of methods, some free. (Sadly they don’t seem to have any way to update the MMI firmware though). The map updates are badly documented, so here’s the details.

First, the easy options that cost money. You can pay the dealer to do it. Or you can pay for the Audi Connect service (the cellular data for your car) and updates come over the air.

Now the free manual option. Discussed here, also see this video. It’s not hard or scary, the only real nuisance is their Java download program. Detailed walkthrough:

Downloading update

  1. Log in to myAudi.
  2. Click the “Audi connect services” button. I had a lot of trouble with their SSO redirects, maybe related to my ad blockers and privacy stuff.
  3. On the Audi Connect website go to Services / Map Update and select “Complete Package”, then click the “Prepare Package” button.
  4. Download the map update! Ha ha just kidding. Download a tiny JNLP file for Java Web Start to run a download program that Audi requires you use.
  5. Run the JNLP program. I managed finally by enabling it in the Java control panel (Security / Enable Java content for browser and Web Start applications) and then running “javaws foo.jnlp” from a command line. Perhaps there’s an easier way.
  6. Wait for the download. The full US maps were about 11GB.
  7. The download program creates four files. Two small files: one named metainfo2.txt and one named randomhexstring.md5. And two directories with the data: Mib1 and Mib2. Apparently all 4 are necessary for an update.
  8. Copy the 4 to the root directory of a FAT32 system on an SD card. (A USB drive will work as well.)

Installing update

  1. Go to the car and put the SD card in one of the slots for the MMI. (I used SD2).
  2. Turn the MMI on. (I do this by turning the radio on, not the ignition).
  3. Go to Settings / System Maintenance / Version info to check the versions of things on your system already. This shows the MMI software version (0694 for me) and some basic navigation database info; you have to navigate to the Navigation database submenu to see all the databases you have. My car had about 20 2016/2017 databases for North America, plus a single 2017/2018 for USA, Region 4 (California, where I live). That was an OTA update I got right after buying the car.
  4. Go to Audi Connect and select “Software update”. Select the source you plugged in (SD2 for me) and it begins. It takes awhile, about 30 minutes for me.
  5. Leave the car and close the door. Lights will turn off but the MMI will continue to be running with the screen lit and updating. Eventually the screen will close and it seems to keep updating. Hopefully none of this drains the battery too much. The update is automatic and requires no extra input
  6. Once it finishes you may have to enter a single click  to acknowledge the update.
  7. Go back to Version info to check the version numbers. Now all my car’s maps are labelled “2018”. Success!

Of course I’m curious about the contents of the update files but couldn’t find a lot of info. Mib1 has a directory named “Eggnog” and Mib2 has “Truffles”; internal product names? Mib1’s datafiles seem to be named “.psf” and Linux guesses some (but not all) are FoxPro FPT files, which seems plausible. Mib2 is mostly compressed data I couldn’t figure out, which some small SQLite tables without much interesting it. Probably all proprietary data, of course, and if they’re smart it’s encrypted too to prevent casual snoops like me from lifting all the data out.

Shame Audi doesn’t also let you upgrade MMI firmware. Mine has a bug where it’s limited to indexing 10,000 music files. Admittedly that’s a lot of music, but it’s a nuisance if you just want to copy all the music you own into the car. Static array sizes: not even once!

x264 / x265 sizes compared

Doing a little ugly fast and loose codec comparison. I took a pirate scene MKV file in 720p with 5.1 audio, an hour long video file that was (no doubt) lovingly encoded in H.264 with one audio track and several subtitle tracks. I then transcoded it to H.265 and H.264 using ffmpeg with default settings. This also transcoded the audio from 640kbps AAC to 276kbps Vorbis. Anyway here’s what I got for file sizes:

Original file

  • 1800MB, 720p, 51 minutes
  • 1580MB video, 240MB audio
  • h264 (High)

x265

  • 170MB, or roughly 10% the size
  • 80MB video, 90 MB audio
  • hevc (Main), encoded with “ffmpeg -c:v libx265”, default settings.
  • Encoded at about 1.3x playback speed (software)

x264

  • 400MB, or roughly 22% the size
  • 290 MB video, 90 MB audio
  • h264 (High), encoded with “ffmpeg -c:v libx264”, default settings.
  • Encoded at about 3x playback speed (software)

The x265 encoding is remarkable. The video is literally smaller than the audio! And the resulting file is 10% of the source. The video segment is 5% of the size of the source and the audio is 38%.

The x264 re-encoding is also notable, in that I’ve squished it to 22% of the source with nominally the same codec. That’s a pretty good savings and indicative that the source of the file was probably encoded with very high quality / high bitrate to make paying customers happy.

The resulting x265 file looks fine on my TV. You can see some posterization on subtle dark areas and maybe the sound isn’t as clear. But I’m blessed with a tin ear so those degradations don’t bug me much. No doubt there’s a sliding bar here between bandwidth and quality that a proper codec testing setup can do. Me, I’m just a dumb bear using ffmpeg default settings and pretty happy with the result

This post was all motivated by this post and discussion about comparing AV1 to x264 and VP9. AV1 is the new hotness in codecs, although as with all these things there’s years of controversy and patents and hardware support to settle before adoption.

Blu-Ray to x265

I am super excited about the Vinegar Syndrome re-release of Liquid Sky. One of my favorite movies from the 80s, most of us watched it on crappy 3rd generation VHS tapes or if we were lucky, a low quality DVD. Vinegar Syndrome remastered it and put out a beautiful Blu-Ray with gorgeous color and lots of extra features. Only problem: it’s a disc. Who can play discs these days? So I ripped it. (For myself only, I respect Vinegar Syndrome far too much to give out copies.)

Pasted image at 2017_12_12 02_36 PM.png

Blu-Ray discs are encrypted so most computer tools can’t read them. But MakeMKV can. It’s a straight up rip; it copies all the tracks off of the Blu-Ray and puts them in MKV containers on your hard drive. No re-encoding so the 2 hour movie is like 29 GB.

Re-encoding it to a smaller file is easy. Handbrake will do the job fine but for some reason was running slowly for me, so I used ffmpeg instead. Here’s the command:

ffmpeg -hwaccel auto -i title00.mkv
-map 0:v -c:v libx265 -crf 26 -preset slow -tune grain
-map 0:a:0 -c:a:0 aac
-map 0:a:1 -c:a:1 copy
-map 0:s:0 -c:s copy
ls.mkv

I’m doing this the complicated way with -map options so I can pick and choose audio tracks. Track 0 is the main audio, track 1 is director’s commentary. There’s also a track 2 which is the sound without dialog, but I decided not to include it. Just the one video track of course, and one subtitle track.

I transcoded the main audio. The source is in 768kbps DTS, overkill particularly since the audio is mono (as the original film was). So I’m re-encoding it to AAC. I have no idea what bitrate that was going to give me. The result is about 150kbps which seems reasonable, if generous.

I also transcoded the video to H.265, the result is about 3300kbps for 1920x1080. crf 26 is higher quality than the default crf 28. Preset slow trades off CPU time for higher quality / smaller video. And “tune grain” tweaks the encoder to try to preserve film grain, something abundantly visible in the source disc.

I wanted to transcode the subtitles to SRT but that didn’t work for me, ffmpeg threw an error.

The metadata mostly came through but then some of it is wrong; bitrates and stuff were copied from the Blu-Ray. Chapter marks did come through from the original source.

All told it took about 18 hours or about 0.1x real time speed. That slow preset really makes it slower, something like 4x slower.

Hardware accelerated ffmpeg transcoding

Since I have a Linux VM with a big GPU lying around I thought I’d take a quick stab at hardware accelerated video transcoding using ffmpeg. Quick results:

  • software decode, h264 software encode: 0.355x real time
  • software decode, h264_nvenc hardware encode: 2.7x real time
  • cuvid hardware decode, h264_nvenc hardware encode: 2.8x real time

So the hardware h264 encoder is about 7x faster than software. Hardware decoding is nice but not a huge improvement.

This is all on a 1 vCPU, K80 Google Compute server. Crappy little CPU and big beefy GPU. Normal desktop machines probably have less of a spread in results.

I really wanted to test this with H265 encoding, but the hevc_nvenc encoder does not work with the Kepler-class K80 hardware. I’m regularly doing H264 -> H265 transcoding at home now and on my i7-2600 it transcodes 720p video at just about real time.

Between the video transcoding and the machine learning I’m itching to own my own Linux box with a GPU in it. I could add a GPU to the existing server but it seems to be $200 minimum. The old server is 6 years old, maybe it’s time for a full hardware upgrade. Go for SSDs. Ubuntu 17.10 while I’m at it; these LTS releases are reliable but limiting.

I wonder if there’s a way to use the on-chip Intel GPU more? Probably not worth the hassle.

 

Converting video to x265 with avconv

A simple command line for converting video to small x265. These options are chosen to produce acceptably low quality, low bitrate output.

avconv -i in.mkv -c:v libx265 -c:a copy -crf 29 -s 854x480 -preset fast out.mkv

  • c:v libx265 means “encode using x265”.
  • c:a copy means “copy audio, don’t re-encode”
  • crf 29 means “slightly worse than default 28 quality”
  • s 854x480 means “resize to 480p”
  • preset fast means “I don’t have a hardware encoder so please don’t take forever”

Obviously better quality is possible, this is producing about 500-600kbit/second video or about 4x the same of the audio track.

Speaking of audio track it’d be nice to convert whatever the source is to 128kbps AAC stereo. I’m not clear if a simple “-ac 2” is sufficient or if more complex downmixing is necessary.

Foscam R2 is garbage

I got a Foscam R2, a cheap and capable Internet camera for home security. But the software is so bad and insecure I’m returning it. A camera in my house has a high bar for security. I do not want video from my house leaking on the Internet. Foscam is designed around a cloud service, so the bar is very high indeed. Given how bad my first 30 minutes were I’m returning the thing.

Summary:

  • I can’t upgrade the firmware
  • I can’t connect to the IP interface at all
  • The website requires a native code plugin to run
  • They don’t quote user input correctly

Security problems

The biggest problem is utter contempt for basic security. Some examples:

The camera configuration won’t accept my wifi password because it has a space in it. Foscam support has an alarming list of characters you can’t use, including & and =. This suggests they aren’t properly quoting user input. (The linked discussion confirms that.)

The camera’s local IP interface is HTTPS only. Nice! Only there’s no valid SSL certificate since there’s no meaningful hostname. After telling my browser to ignore the warning I can get a login page and a tip briefly pops up “Don’t support using HTTPS to login chrome”. Logging in with Chrome does not work. Neither does Edge. I can maybe log in with IE10, but all I get is a popup saying I have to install a .exe plugin first to use the camera. No thank you.

There’s several separate websites: foscam.us, foscam.com, and myfoscam.com. I’m not positive but I think the .us site is an American reseller? They have an alarming security note

In early June Foscam Digital had been notified of 18 security vulnerabilities that existed on cameras manufactured by Shenzhen Foscam ...  Foscam Shenzhen initially did not address the vulnerabilities for several months ... . However, on June 14th, shortly after the vulnerabilities were communicated directly to end-users by Foscam Digital in order to pressure Foscam Shenzhen to take action, Foscam Shenzhen released a firmware update response available here

Usability problems

I can’t upgrade the firmware. The mobile app has a firmware upgrade option and does seem to upgrade the camera to 1.11.1.6. But then there’s a second upgrade to 2.x.1.18 (yes, the x is part of the version number) that does not work via the mobile app. There’s instructions for upgrading via the web interface but since I can’t log in, I can’t do that.

 

The English translation is terrible. The very first text you see in the mobile app you have to use to configure the camera is “Has the account?Sign up”. There are translation errors all over the product. I’m usually the last person to criticize someone who speaks imperfect English as a second language. But this sure makes for a bad impression.

The website for the Foscam cloud service works for about 30 seconds, then pops up a dialog that says “Foscam web component has beed upgraded” (sic). The popup is modal with a “Click to download” button that says “Please click me to install plugin(Now we don’t support IE(64))”. It downloads a .exe that I wouldn’t dream of running.

 

I can’t find their MAC address prefix 00:62:6e in the OUI database. That might not mean anything. Or it might mean they’re cutting some important corners with their ethernet chipset.

 

 

HD FM Radio

My new car supports HD Radio. What is that? It’s a US standard for radio stations to broadcast a digital sideband adjacent to their audio frequency. The FM version is a 100-150 kbit/sec digital stream that encodes data in HDC, a proprietary standard that is similar to AAC. In theory there can be multiple HD streams on one channel, and a station could be digital-only. I haven’t seen that in practice.

The audio quality definitely seems better than analog FM. It’s also better than the low bandwidth Sirius XM channels like their NPR channel, that thing is awful. The big bummer is that since it’s a sideband the digital FM broadcasts don’t really offter the opportunity to free up any spectrum. Not that the TV spectrum process has gone very well.

 

 

2017 Audi A3 vs SD cards

My new car has a fancy stereo from Audi / Bang & Olufsen that can play audio (and video!) off of SD cards. Awesome! So I loaded up a 128GB SDXC card with my music collection, inserted it, and watched it crash as it indexed. But it seemed to work anyway after rebooting. Only some music is missing.

Looking more closely I figured out music started being missing right around Johnny Cash. But nothing wrong with those Johnny Cash files, they work on a new card just fine. A bit more googling and head-scratching and I learned the Audi might only read 64GB of an SD card. This limit is baffling; the big limit on SD is 32GB, the SDHC format. The car’s manual explicitly says it supports up to 128GB cards. I found this other post that claims > 64GB cards work, but only with FAT32, not exFAT. There may also be limits on the number of files / directories / etc, but it’s vague.

Anyway, on my exFAT SDXC card everything after Johnny Cash is unreadable. At first I thought that was the 64GB limit but counting carefully really it’s like 69GB in. I’m also at about 9800 files before I hit the Js, so maybe it’s actually a 10,000 file limit?

Another mystery is the indexing system. It definitely scanned the SD card the first time it saw it, for several minutes before crashing. Now when I put the card in it doesn’t index it. I’m not positive if it’s detecting changes in the drive or not. (I think so?) Where is it storing the index? There’s a file on the root of the SD filesystem named “WMPInfo.xml” that it placed there, some Windows Media Player junk. But it’s only 296 bytes. The car has its own dedicated hard drive with a partition for a “jukebox” I can copy music to. Perhaps it has another partition for databases and stuff. It’s got a copy of the GraceNote database built in somewhere!

 

Garage door remote radio

Spent way too much time today learning about how radio garage door openers work. Good articles on Wikipedia: remotes and rolling codes.

Most garage door openers work on a radio signal in 300-400MHz. There are various identification / code systems in use to uniquely pair transmitters and receivers.

My San Francisco garage works by having the transmitter and receiver share a single 10-12 bit key that is programmed via DIP switches. Presumably they also have to agree on which frequency they speak. (Two gate controllers also work via DIP switches.) Note this kind of system is terribly insecure, it’s easy to build a universal opener that just sends all codes.

My Grass Valley garage has Intellicode, a rolling code. This works by the transmitter having a secret key. You put your receiver in “learning mode” and it memorizes the secret key. Then there’s a simple PRNG-like crypto protocol where the transmitter is generating one time passwords that the receiver recognizes. This is more secure than a fixed code, although there are attacks against it too.

There’s a variety of “learning remotes” that you can use to duplicate a garage door opener, to make a new transmitter. Fancy cars tend to have HomeLink systems. I just bought a Clicker battery powered remote.

HomeLink seems to work by first listening to a working transmitter, then copying it. Presumably it’s figuring out what frequency to use. And if it’s a fixed code, it learns the 10-12 bit code that otherwise you’d set with DIP switches. If there’s a rolling code you have to do an extra step of having the receiver now learn the HomeLink’s key.

The Clicker seems to work by me manually identifying which type of transmitter I’m trying to clone. It’s got a library of ~15 types, which presumably tells it what frequency to use and what kind of code it needs. Then there’s either physical DIP switches to set and memorize or for a rolling code, you have the receiver learn the Clicker’s key.

There’s also a new modern world of Internet-enabled garage door openers where you just tell it to open via a smartphone app. I’m told you can retrofit these as new receiver units wired into an existing working motor drive unit.

 

Setting up motion and an Axis camera

A few months back I bought a simple network camera for low-key home security and then never set it up. Well I set it up now and it works. Some notes.

The camera is an Axis M1034-W. It mostly works well. Right out of the box pretty much; acquires an address via DHCP (ethernet first, until you configure wifi). Immediately serves a video stream once it’s up and has a straightforward web configuration interface. That’s the good part. The bad part is the only video stream that works is Motion JPEG (ie: a bunch of JPEGs). There’s support for H.264 but it requires a Quicktime plugin to view, a nearly dead technology. Also a video stream is all I can get. The camera has its own motion detection stuff but it requires a Java applet (!) to configure. So that’s all dead web technology. But the basic camera and HTTP viewing works.

I ended up using motion to monitor the camera and publish images and movies of motion. My original idea was to use ZoneMinder, but that install uses PHP and MySQL and seemed like overkill. motion just writes image files to a directory (and optionally, a database). It does depend on avconv / ffmpeg, but that’s all.

Configuration of avconv was pretty simple. Install it in ubuntu, set up a /home/motion, set up a /home/motion/.motion/motion.conf with the config. The key configuration directive was “netcam_url http://192.168.0.XXX/mjpg/video.mjpg”, to tell it how to find the Motion JPEG stream. You can also have it poll static JPEGs via a URL like http://192.168.0.XXX/axis-cgi/jpg/image.cgi?resolution=1280x800 but I’m imagining the motion JPEG stream is better. I also had to set up the username / password for the camera, and some output options. There’s a lot of choices for tuning the motion detection algorithm, file writing frequency, etc.

The main tuning I did was set the Axis camera itself to only serve 640x480 @ 10fps. Sad to lose the quality, but I don’t want to flood my wireless network with 18 mbps. We’re pushing about 2 mbps as it is; motion JPEG is a really stupid way to send video when you expect nothing to change. My Mac Mini is chewing about 6% CPU processing this data.

When I have more time I’m going to look to see if the Axis camera itself can usefully do the motion detection and video encoding. I think it can, just gobstopped by the Java applet requirement. I mean, really?

Home surveillance cameras

I want a security camera for my house, for when I’m away. Nothing too creepy or serious, just some peace of mind so I can see if a package got delivered or if the propane delivery guy came.

tl;dr; I’m going to try ZoneMinder with an Axis M1034-W camera.

The mainstream product everyone recommends is Dropcam. But it and its competitors all work by uploading a video feed 24/7 to a server they host which then does the processing to do useful things like only show video clips of motion, etc. They tend to charge $10/month for the hosting. And it’s a lot of bandwidth. So I’d rather roll my own, using my own Linux server. (Yes when Jack Bauer breaks in, Chloë will be able to knock my surveillance offline with a Linux zero-day. That’s not my threat model.)

The hacker solution for this stuff is surprisingly unclear. On the Linux video collection side, motion(1) is a popular low level tool for doing motion detection from video feeds. ZoneMinder seems to be the high end tool of choice for managing multiple cameras. It works with a lot of stuff including video capture devices hard-wired to the machine and network cameras.

I’m baffled by the choice of camera hardware. I decided to try Axis because they have a developer program, ZoneMinder works well with them, and they have a reputation for being good but expensive. I only need one camera so expensive is OK. The M10 line seems to be the low end stuff, $200 instead of $400+. The M1034-W is the WiFi option. They also make wired POE stuff which seems like it’d be good for outdoor use.

That’s all research. I ordered the camera, will tinker with it next week.

 

Mac screen capture: creating League of Legends highlights

I felt like a huge nerd today and wanted to record a video highlight from a League of Legends. Lots of steps here to capture the game itself, capture video and audio on the Mac to a file, convert it to something usable, then upload it. Here’s all the steps.

Generate content: record game replay

The service replay.gg will record all your League of Legends games for you. It’s terrific! Using it you can watch one of your games later in the observer client. I use this to get the exact game scene I want to capture.

Capture content: video and audio capture

The Mac does not make it easy to capture full screen video and audio. I used to use the commercial product Screenflick to do this but it’s pretty buggy. So this time I did the capture with Open Broadcaster Software, which is a free. The UI is a bit more hackerware but for my purposes it’s perfect.

OBS records video pretty much right out of the box. I tinkered with the Advanced Output settings to record at the bitrate of 10,000 (overkill) using the faster preset. Note that OBS is doing h.264 encoding live while you go, so it’s taking CPU power. The “slow” preset definitely interfered with my game framerate. (Screenflick records with a very fast, disk intensive codec and then re-encodes later, which is kind of nice.)

Audio is a problem. Update: see this second post about sound. OBS recommends WavTap but I couldn’t make it work. Instead I installed SoundFlower, which also works well with OBS. Basically SoundFlower installs a kernel module that’s a new loopback audio device. You use the Sound control panel to tell the Mac to make SoundFlower 2ch the default audio device. SoundFlower then passes that through to your actual headphones or whatever, while also making the sound stream available to apps. Note that starting with Yosemite it’s getting very hard to run custom kernel drivers in MacOS. Thanks a lot, Apple.

Now I have OBS recording movie files to my hard drive of whatever is on my screen. Yay!

Edit content

The next challenge is editing the capture down to what you want to share. I’m allergic to iMovie, and AFAIK there is still no good free simple “let me cut 15 seconds out of my video” GUI tool for Macs. I ended up using ffmpeg to do this with these instructions. ffmpeg lets you pick to the nearest millisecond, but irritatingly VLC won’t show you milliseconds in playback, so precise cuts suck.

Here’s the command I used to cut from 00:02 to 00:19 of my recording and re-encode it at decent quality. Unfortunately you can’t just use “-copy” in ffmpeg because that doesn’t properly trim the audio for some reason; you have to reencode.

ffmpeg -i obs.flv -c:v libx264 -preset slow -crf 20 -ss 00:00:02 -to 00:00:19 out.mp4

Man I’d like a simple GUI program that lets me watch the movie and set a start time, an end time, and press a button to do this cut for me.

Share content

Now you have an ordinary MP4 movie file you can share anywhere. I uploaded it to Streamable, a lightweight hosting / sharing service for video that plays nicely with Reddit and friends. They re-encoded it to a 2260 kbps vp8+vorbis file which still looks pretty good. In particular I think they kept my 60 frame per second source, much appreciated.

Temperature vs time

Funny graph from my computer in a Kansas datacenter. Something changed there and the temperature has dropped 4°C over 12 hours. And just at the same time, the phase-lock loop that NTP uses to sync time with the kernel goes off. The error isn’t big, at most 8ms, but it’s amusing.

sensors_temp-day ntp_kernel_pll_off-day ntp_offset-day

SmartTVs

I just bought a new TV. They are now plagued with a huge number of “smart” features you have to turn off to make the set useful. You pretty much can’t buy a TV without these.

First off is all the video processing. The motion interpolation / dejudder / etc that takes a lovely mastered Blu-Ray source and then makes it look like shit and 100ms out of sync with the audio. Fortunately TVs generally have a “game mode”, so-called because gamers want low latency displays. As a side effect it disables all the video processing.

Then there’s the Smart TV stuff. I’ve been buying Samsung TVs and watching their apps evolve. It’s not bad; you can legitimately watch Netflix or (probably) Youtube entirely on your TV now. Only problem is that there’s no simple way to get sound back out of the TV and in to your nice wall-mounted surround sound speakers. So all this smart TV stuff is useless unless you want to listen to 5W of shitty stereo. (Not strictly true; there’s a new HDMI 1.4 standard called ARC that does feed audio back up the cable.)

The Smart TV stuff is a little useful if you really just want a simple TV to watch movies in the kitchen. But for anyone who is at least a little serious about home theater, it’s useless. Worse than useless. Because now your TV has an operating system. So it takes a long time to boot, is vulnerable to security holes, and is popping up features and notifications when you don’t want them. I was particularly charmed to see this year’s Samsung TV includes a virus scanner. In the display. Awesome.

There used to be a class of flat panel displays called “monitors” that were really just a screen; no speakers, no “smart TV”, no bullshit. Unfortunately that market segment is gone. My suspicion is that the TV manufacturers are hoping to one day capture customers and turn them in to Internet service subscribers, so that they make more money than just selling the fancy glass panel. Ugh.

Bonus link: simple TV feature comparison matrix. Samsung’s marketing literature makes it impossible to understand what you are actually buying. What’s the difference between a JU6500 vs a JS8500? About $1000, but their web site does a terrible job informing you what that $1000 buys. This third party site has a simple feature matrix. May they make many dollars in Amazon referral fees.

Addendum

XKCD #463

Nest thermostat hacking

I got a Nest thermostat a few months ago. I mostly like it, even if it is a bit overdesigned, it’s a lovely product. But a few days ago the battery stopped charging. Turns out charging is complicated on these things; it’s trying to vampire off the furnace control lines. Mine report to be running at about 35V, 20mA. That’s less than a Watt of power, not a huge amount, although it’s been enough so far and Nest tells me it should be sufficient.

Anyway, the diagnostics on the unit for battery charging are not very good. But the Nest helpfully uploads its battery state every few minutes, at least if it has enough battery charge to do that. Unhelpfully the webapp doesn’t show battery history. So I have to make my own.

I ended up using python-nest and writing a simple script to get the battery state.

import nest
username = 'nelson@monkey.org'
password = file('password').read().strip()
with nest.Nest(username, password) as napi:
    for structure in napi.structures:
        for device in structure.devices:
            target = device.target
            temperature = device.temperature
            ts = device._device['$timestamp']
            battery = device._device['battery_level']
            print "%.3f,%.3f,%.1f,%.1f" % (ts/1000.0, battery, temperature, target)

Boy that Python Nest API is funky. And undocumented. I have no idea what a “structure” is supposed to mean. The object doesn’t really exist until you query it with the iterator protocol and it lazily makes an HTTP request. Once it does I think you can also access it as an array, but not before. Then there’s the device which you access with properties, but that only has some data, the battery level is hidden in the device._device object which you access as a hash table. And while the command line tool can print whether the heat is actually running at the moment or not I never could find that in the data structures. At least I got my battery recording.

The Internet of Things enables whole new worlds of yak shaving.

littleBits remote temperature sensor

My friend gave me a littleBits Smart Home kit for Christmas. Fun electronics toy; you snap together a simple network of components like temperature sensors, LED displays, and a “cloud module” to build devices. I set up a simple thing that gets the room temperature, displays it on an LED, and also feeds it to the cloud device. It works!

Update: left it running a couple of days, 100% stable. A bit bandwidth hungry though; about a megabyte an hour uploads, or 300 bytes a second. And about half that download. I suspect it’s sending a single voltage value once a second and the rest is overhead.

Here’s a Python program I wrote to fetch the data from the device. The wrinkle here is that there’s no simple “get current number” polling interface; it’s all subscriptions and streams. That seems to be on purpose and while I can sort of see the rational, it does make the HTTP client 4 lines of code instead of 2.

#!/usr/bin/env python3
from pprint import pprint
import requests, json, sys, os
token = '27ebe6c681d8db547ff8ac02714e6c07ed08084cf844ffc247cc9f926f155b4'
device = '00e0547ff8ac'

headers = {
    'Accept': 'application/vnd.littlebits.v2+json',
    'Authorization': 'Bearer %s'; % token,
}

try:
    resp = requests.get('https://api-http.littlebitscloud.cc/devices/%s/input' % device,
                        headers=headers,
                        stream=True,
                        timeout=5)
    output = next(resp.iter_lines(decode_unicode='ascii'))
    resp.close()
    data = json.loads(output.lstrip('data:'))
except Exception as e:
    sys.exit(1)

out = os.path.dirname(os.path.realpath(__file__)) + &quot;/data.tsv&quot;
with open(out, 'a') as fp:
    fp.write('%d\t%d\n' % (data['timestamp'], data['percent']))
sys.exit(0)

all my music albums sorted by date

Useful bit of shell for looking at my music library by age acquired:

find . -type d -links 2 -exec \
  stat -c "%Y %y %n" {} \;    \
| sort -n                     \
| cut -c 12-22,50-

The find shows all leaf directories. The stat command prints the file modified time for the directory in two formats. Sort by timestamp, then use cut to extract just the date and pathname from stat.

The find -links is said not to work in the MacOS bizarro filesystem. Works fine on Linux, didn’t test through an SMB mount.

I’m using the directory mtime, the good ol’ Posix way to sort of tell how old a directory is. Or rather, last time a file was added/removed from the directory (IIRC). The 20+ year legacy of Unix not really supporting creation times on files reliably. (Quick, what’s the difference between mtime and ctime? And why is atime such a bad idea for web servers?) ext4fs has a new attribute called “birth time” that looks useful, but the userspace tools still don’t know how to read it.

Sonos hacking

I love my Sonos devices, they are reliable and sound great. I’m also curious how they work, and I do wish there were better diagnostics for media files that refuse to play.

Turns out the Sonos has an admin web interface on port 1400. A URL like http://192.168.0.20:1400/support/review brings up a bunch of debug data; substitute the IP address for one of your Sonos devices. It loads slowly. Also appears to be centralized, no need to find the right device first.

I also found my way to SoCo, an open source hacker interface to the Sonos. Command line control over playing, queuing, etc. Neat stuff and seems to work.

What I haven’t found is any way to get an error message why a track won’t play :-(

I thought the Network Matrix was interesting. Screenshot below. STP presumably refers to spanning tree. Sonos’ core magic is the way music plays completely correctly, synchronized, in an unmanaged wireless network. Presumably this is the status of the magic that makes that work.

Screen Shot 2014-09-26 at 10.58.02 AM

Converting ALAC Apple Lossless to 128kbps AAC m4a

I’ve got all my music in fancy Apple Lossless files. CD quality, but big; 500 megs a CD? I’m importing to a small hard drive and need to resample to 128kbps m4a. I looked at a lot of options, including shell scripts and ffmpeg. But I decided to just let iTunes to do the work; I trust it to handle metadata and album art better than something I cobble together myself.

I ended up following these instructions more or less. Here’s what I did:

  1. Start with an empty iTunes library
  2. Choose a new directory for my iTunes Media folder location in Advanced Preferences
  3. Make sure “copy files” and “let iTunes manage library” were unchecked in Advanced Preferences
  4. Open all my ALAC files from a read only remote file server, so iTunes now knows where all my music is.
  5. Go to iTunes preferences and change the CD import options to AAC encoder. Despite the horrible UI, that’s the option used when encoding all music, not just CDs.
  6. Select all my music. Right click, choose “Create AAC Version”
  7. Wait patiently for conversion.
  8. Press “delete”; this will remove the selection from my library, which still points to all the ALAC originals and not the AAC copies.
  9. The AAC copies are now in the folder I specified in step 2. I think these are safe, complete versions, although I haven’t verified that metadata (particularly album art) is in those files and not just in iTunes’ database. (Update: the album art does seem to be in the new files.)

The main problem with this process is step 7 needs to work correctly. If it’s interrupted then just resuming what wasn’t finished is a PITA. Not great when it will take many hours. Also step 4, the initial import, takes a very long time. I don’t think iTunes is actually reading the entire file, at least I hope it only reads a metadata header, but I’m not positive.

Update guess what, step 7 didn’t work correctly! The machine went to sleep on me, and between that and the Screen Sharing login I was using I ended up having to reboot. It wasn’t too hard to figure out where to resume encoding; you can quickly tell from the Bit Rate column which songs haven’t been re-encoded (or spot the dupes) and I hadn’t changed the sort order. So now I’m encoding the second half of my library. Step 8 won’t work now, no selection intact, but I think I can either use Bit Rate to find the original ALACs to remove or else unmount the disk and have iTunes remove the missing songs.

Update 2 36 hours of conversion later and it’s close to done, but not complete. I think it’s getting slower as time goes on but I’m not positive. There’s no major memory leak, don’t know what’s up. iTunes is a piece of garbage. One more problem with letting it do the work; iTunes names files its own way, it doesn’t copy the source filename. So there’s no real way to just diff directories to see what’s incomplete. I finally had to abort the import about 3% from complete; I may have to write a custom tool just to find what’s missing :-(

Update 3: I decided to redo the conversion and asked on Stack Exchange how best to do it. Glad I did; someone pointed me to Max and it’s doing the job well. It handles all metadata correctly (including Unicode) and it’s fast thanks to being multithreaded. I’ve got 8 encoding threads running on my iMac and have maxed out the hard drive bandwidth. Still no solution for resuming an incomplete batch job but since the whole thing only takes 3.5 hours now, I can live with it.

Adding album art to Thinner’s MP3

The Thinner netlabel included JPG images for all their albums but didn’t embed them in the MP3 files. Consequently iTunes can’t find them. Dealing with id3 is a bit of a black art, the tools and formats are varied and poorly documented. But I think this works and is safe:

eyeD3 --to-v2.3 --add-image thn018.jpg:FRONT_COVER *.mp3

That adds thn018jpg as a front cover to all MP3s in the current directory. The converstion to 2.3 is necessary; eyeD3 can read but not write the 2.2 tags that are in the early Thinner releases. Note that this will add a second image if one already exists. Only safe to run once :-P

Getting clever:

#!/bin/bash
for d in thn*; do
 JPG=$d/$d.jpg
 if [ ! -f "$JPG" ]; then
 echo "$JPG not found, skipping directory"
 continue
 fi

eyeD3 --to-v2.3 --add-image $JPG:FRONT_COVER $d/*.mp3 > /dev/null
done

Sad fact: iTunes won’t display GIFs, only JPGs.

Sonos id3v2 tags

Over on the Sonos forums I asked about which ID3v2 tags the Sonos uses. I got a great reply that seems to be correct, reproducing it here. It’s from Rick Parsons aka “renowden”.

TIT2 [Title/songname/content description] - commonly called Track

On the Sonos this is called “Track” and is available in an index and on the controller screen when the track is playing.

TPE2 [Band/orchestra/accompaniment] - commonly called Album Artist

On the Sonos this is called “Artist” as an index but does not appear on the display at all when a track is playing.

TPE1 [Lead performers(s)/soloist(s)] - commonly called Artist.

On the Sonos this is called “Contributing Artist” as an index. It shown on the display as “Artist” when a track is playing. In theory multiple artists can be put in this field (separated by a “/” but some tag editors show it as a “;”). In practice the Sonos sometimes shows only the last one on the list. I haven’t been able to determine why.

TALB [Album/movie/show title] - commonly called Album

On the Sonos this is used as an index. It also shows on the display when a track is playing.

TRCK [Track number/position in set]

This is not displayed anywhere but is used to determine the track order in albums.

TCOM [Composer(s)]

This is used as an index but does not show on the display during playback.

TCON [Content type] - commonly called Genre.

This is used as an index but does not show on the display during playback.

COMM [Comments] {iTunNORM}

This is written by iTunes and is discussed at length elsewhere. In summary it can, in the right conditions, be used to level the volume of playback.

There is another tag written by Windows media Player which performs a similar function to iTunNORM but I haven’t discovered what it is.

Canonical music genres

Still wrangling the metadata on my music library. ReadyToPlay did a good job on the rip and categorized all music into a relatively small set of Genres. I’m taking this as canonical for now.

Avant-Garde • Ballet • Blues • Chamber Music • Choral • Christmas • Comedy\Spoken • Concerto • Country • Electronica • Folk • Jazz • Keyboard • Latin • New Age • Opera • Orchestral • R&B • Rap • Reggae • Rock • Soundtrack • Spoken Word • Symphonic • Vocal Music • World

Well, not entirely canonical; I’ll probably unify a couple of these. Also the classical feels wrong to me: I couldn’t tell you Orchestral from Symphonic. I’d prefer to break it down by Musical era: Early, Baroque, Classical, Romantic, Modern. Of course those are ambiguous too.

One thing that’s really annoying in my metadata; music is indexed by the composer’s first name. So Tchaikovsky is filed under “P”, for “Pyotr Il’yich Tchaikovsky”. It’s a bit of a trivia game.

 

Metadata for .m4a apple lossless (ALAC) files

My new music library is all nicely ripped Apple Lossless files in .m4a containers. These contain metadata, but it’s not id3v2 and the universe of mp3 tools mostly don’t work. ffmpeg’s ffprobe sort of works but doesn’t show all tags.

What does work for displaying m4a metadta is mp4v2, installable via Homebrew. Docs here. It seems pretty stable but still gets some updates.

(imac) = mp4file --list test.m4a
BRAND  COMPAT              SIZING  FILE
----------------------------------------------------------------------
M4A    M4A,isom,mp42       32-bit  test.m4a

(imac) = mp4info test.m4a
mp4info version 1.9.1
test.m4a:
Track	Type	Info
1	audio	alac, 260.806 secs, 562 kbps, 44100 Hz
 Name: Pastourelle (E passo de dossai: Ah! viens pres de moi), folksong for voice & orchestra (Chants d'Auvergne, Series 2, No. 1)
 Artist: Dawn Upshaw
 Composer: Joseph Canteloube
 Release Date: 1994
 Album: Canteloube: Songs of the Auvergne
 Track: 1 of 15
 Disk: 1 of 1
 Genre: Vocal Music
 BPM: 0
 Part of Compilation: no
 Cover Art pieces: 1
 Album Artist: Kent Nagano
 Media Type: Movie
 TV Episode: 0
 TV Season: 0

(imac) = mp4track --list test.m4a
track[0] id=1
  type           = audio
  enabled        = true
  inMovie        = true
  inPreview      = true
  layer          = 0
  alternateGroup = 0
  volume         = 1.0000
  width          = 0.00000000
  height         = 0.00000000
  language       = UNDEFINED(0)
  handlerName    =
  userDataName   = <absent>

(imac) = mp4art --list test.m4a
IDX     BYTES  CRC32     TYPE       FILE
----------------------------------------------------------------------
  0     11255  299646cd  jpeg       test.m4a

(imac) = mp4tags
mp4tags: You must specify at least one MP4 file.
usage mp4tags OPTION... FILE...
Adds or modifies iTunes-compatible tags on MP4 files.

      -help            Display this help text and exit
      -version         Display version information and exit
  -A, -album       STR  Set the album title
  -a, -artist      STR  Set the artist information
  -b, -tempo       NUM  Set the tempo (beats per minute)
  -c, -comment     STR  Set a general comment
  -C, -copyright   STR  Set the copyright information
  -d, -disk        NUM  Set the disk number
  -D, -disks       NUM  Set the number of disks
  -e, -encodedby   STR  Set the name of the person or company who encoded the file
  -E, -tool        STR  Set the software used for encoding
  -g, -genre       STR  Set the genre name
  -G, -grouping    STR  Set the grouping name
  -H, -hdvideo     NUM  Set the HD flag (1\0)
  -i, -type        STR  Set the Media Type(tvshow, movie, music, ...)
  -I, -cnid        NUM  Set the cnID
  -l, -longdesc    NUM  Set the short description
  -L, -lyrics      NUM  Set the lyrics
  -m, -description STR  Set the short description
  -M, -episode     NUM  Set the episode number
  -n, -season      NUM  Set the season number
  -N, -network     STR  Set the TV network
  -o, -episodeid   STR  Set the TV episode ID
  -P, -picture     PTH  Set the picture as a .png
  -s, -song        STR  Set the song title
  -S  -show        STR  Set the TV show
  -t, -track       NUM  Set the track number
  -T, -tracks      NUM  Set the number of tracks
  -w, -writer      STR  Set the composer information
  -y, -year        NUM  Set the release date
  -R, -albumartist STR  Set the album artist
  -r, -remove      STR  Remove tags by code (e.g. "-r cs"
                        removes the comment and song tags)

Energy usage notes

My electricity bill is just terrible now, $500 / month. Since we moved in we’re using 800-1200 kWh / month, or about 1400W average usage all day every day. We’re both home all day and use computers, so I expect our power usage to be high, but that’s absurd. Where’s it going?

Now that we have a Smart Meter, PG&E has an awesome “My Energy” site where you can see hourly energy usage for your house, per day. Here’s a typical day, Tuesday January 24, 2012. We tend to be awake from 7am to 10pm. (I also have a private graph for the whole month.)

Looking at this, it’s clear turning the lights on in the morning and at night has a big impact. Our house has terrible lighting design, a lot of light wasted in ceiling cans. Also still all incandescent bulbs, although on fancy dimmers that should lower power usage.

What really surprises me is the constant usage of 700W all the time, even when we’re asleep. We turn the lights out at night! And sometimes it’s worse, up to 1000W. Fixing that nighttime usage seems like a good place to start.

Here’s a quick audit of things I know take constant power.

  • 150W Wine cooler (450W when active)
  • 50W Refrigerator (average)
  • 120W My computer (when in use)
  • 200W Ken’s computer (constant)
  • 50W Linux server (constant)
  • 80W A/V rack (when idle)

That’s 650W right there, all the time. We can easily turn off my computer and Ken’s computer, that’d cut about 300W out of the wasteage. My computer already goes down to 30W when idle but I can make that 1W. Ken’s computer is awful; it never goes to low power mode and the monitors constantly wake up in the middle of the night. I don’t know why, it’s a Windows 7 box.

I just unplugged the wine cooler. It’s really not necessary in winter. It’s insane that it runs one third of the time even when it’s cool outside; the manual says something about maintaining humidity. Paying $40 / month to keep my wine at 54F instead of 65F seems stupid. It may be more power than that, btw, the Kill-a-Watt registers 450W but 750VA. The website says it draws 6 amps when running, which is more like 660 kWh/hour, yes?

It’d be nice to shut down the A/V rack. But the Tivo is actively doing something useful, and that’s half the power. The other half is keeping a bunch of Sonos units running at 5W each. Probably not worth the bother to buy a timer or something.

Other ideas

It’d be awfully nice to get the usage data in real time off my meter and not have to wait 2 days for it to show up on the website. The buzzword for this is “Home Area Network” and PG&E, of course, is slow to deploy. No doubt in part because they have to worry about the insane people with imaginary diseases. Anyway, here’s some info on a HAN trial.

It’d be nice to install a solar panel on my roof. SF Solar Map estimates I have 1300 sq ft of space for panels which is good for 5kW. At 4.5 hours of sunlight / day that’s 6324 kWH / year, or about half my electricity usage for the year. A 5kW system costs $32,000, but after incentives the cost to me is $21,000. It’d save me about $2600 / year so I’d break even in roughly 8 years. A 2kW system would cost $7400 and break even in about 7 years. (Cost estimate assume $6.50 / W-dc, which may be optimistic.)

Surround sound formats

Theory

All this TV setup makes me curious; am I getting proper surround sound? I have 5.1 speakers connected to a Denon AVR-2309CI and everything HDMI, is it actually working?

The Denon receiver can decode the following formats via HDMI. I barely know what most of these are, but here’s a useful reference, also wikipedia.

  • 2 channel linear PCM (16, 20, or 24  bit samples, 32-192 kHz), also multi-channel.
  • Dolby Digital (5.1), DD Plus (7.1), Dolby TrueHD (7.1 high quality). Also known as AC3.
  • DTS (5.1) and DTS-HD (7.1)

When playing back a 2 channel audio source, my Denon supports a bunch of playback modes to fake out surround sound (“matrixed”). I believe the sound has to have been mixed this way for this to actually work.

  • Dolby Pro Logic II (fake 5ch) and IIx (fake 7.1)
  • DTS Neo:6 (fake 6.1) and “Neural” (XM HD Surround)

Looking at the random video files I have on my hard drive, most have audio in MP3 2.0 or AAC 2.0. One is DTS 5.1 and a couple are Dolby Digital 5.1. I don’t think there’s any way to tell if any of those 2.0 files are matrix encoded fake surround, probably not.

Playback

That’s all the theory, what happens in practice?

The good news is my new AppleTV seems to correctly play back 5.1 sources, via both Netflix and PLEX. In particular the receiver seems to autodetect DTS or Dolby Digital and if I stand next to a rear speaker it does sound differentiated. Yay! It may help I told PLEX my receiver can decode AC3 (aka Dolby Digital).

The confusing news is for all these stereo sources I don’t really know what receiver setting is best to use. I have no idea how common this matrixed audio stuff is or whether it’s worth the effort to decode it. I’ve got a button on my remote labelled “Movie Sound” that cycles the various matrix modes but can’t really hear much difference in a quick test.

Testing

After a bit of looking I found a test suite, the charmingly named “AC3 Dolby digital 5 1ch Sound Test”. It’s available around the net in various places, like filestube. (Or watch it in 2.0 on Youtube.)

This file plays back fine via PLEX on my Apple TV. I also played with using Handbrake to encode it in various ways. Sounds great in true Dolby Digital 5.1. Also sounded surprisingly good in matrixed Dolby PLII; the rear channel separation worked well, although the subwoofer was silent. HandBrake also supports a “6-channel discrete” mode which didn’t really work right on my A/V system.

TV remote success

My A/V rack is controlled by a UniversalRemote MX 900 with a Univeral MRF-350 RF Base Station. It’s not going to win any UI awards but when we were shopping for this stuff three years ago this came in as the most capable and flexible system. So sad the A/V guy I hired to set it up, money well spent: he did an excellent job. My whole system is controlled from a single remote that’s not awful to use.

And as of today, now the new Apple TV is, too. I reprogrammed the remote myself. It turned out to be relatively easy..

  1. Get a copy of the programming software MX_900Setup.zip (23,290,684 bytes); the official source requires a password they only give to resellers.
  2. Run it on a windows box and plug the remote in via Mini-USB
  3. Select “Communication / Upload” to get a copy of the current remote configuration from the remote itself.
  4. Save that file away for safekeeping.
  5. Edit. The manual is essential because the paradigm is weird. Most things are driven by the Program menu. Macros are recorded by clicking simulated remote buttons on the emulator. Codes can be imported via a database, and there’s a learning mode I fortunately didn’t have to use.
  6. Download back to remote. Done!

The hardest part turned out to be digging through boxes to find a spare IR emitter on a cable. The IR Blaster in the front of my base station didn’t seem to be enabled, probably to help prevent crosstalk. It’s 2012 and we still use infrared and little cables to control A/V devices, it’s terrible.

 

Unlocking AppleTV notes

I’m trying to unlock a new AppleTV 2 so I can use XBMC or Plex to play videos from my home network on my PC. It’s been seven years since I first ran XBMC on a hacked Xbox and it’s still way too hard to get low power hardware to play your own TV.

AwkwardTV seems like a useful reference.

Some notes on the jailbreak process:

  • Apple firmware is signed via some online process. You need a “shsh” signature to bless firmware to run, even on already jailbroken systems. In general Apple only signs the most recent firmware, so it’s very hard to downgrade firmware.
  • There’s a program called TinyUmbrella that will generate shsh for firmware you have already. However, it’s mostly not useful except generating a shsh for a current version. My AppleTV out of the box had 4.3 but I was “too late” to get a shsh for it, despite it running. TinyUmbrella is evil software that modifies /etc/hosts and does god knows what else as root. There’s a competitor called iFaith, which may get shsh even for old firmwares, but it’s Windows only.
  • Seas0npass is the preferred jailbreaking software. Their guide is quite good. Don’t be fooled that it’s dated a year ago; they keep updating the jailbreak software.
  • Jailbreaking really boils down to putting the AppleTV in DFU mode and reflashing the firmware with some funky thing. All the weirdness around Seas0npass is creating that firmware and then scripting iTunes to install it.
  • If something goes wrong this Seas0npass troubleshooting guide is great. In particular I had the problem of iTunes saying “This device isn’t eligible for the requested build”. Turns out TinyUmbrella had evilly rewritten my /etc/hosts and was breaking the iTunes update process; telling TinyUmbrella not to do that fixed it.
  • It took about seven tries, but I now have an Apple TV 2 running 4.4.4 (3330), but jailbroken. Ie: I can run my own software and the hardware I purchased.

Now what? Well simple thing is log in as root with the default password “alpine”. Hey, look, it’s like a Unix box! It’s even got apt-get, plus a bunch of apt sources of dodgy software.

First thing up is to install Plex, a media player that works by streaming video from a transcoding server. There are many sets of conflicting instructions on how to install Plex. This forum thread seems up to date as of January 2012. Conceptually...

  • Install Python via apt
  • Download this scary installer(a zip file)
  • Change your root password back to the default “alpine”
  • Run the scary installer
  • It reboots the Apple TV, and now you have Plex!
  • Run Plex, go to Settings / Security and disable tracking.
Plex Media Server is awfully finicky about finding files. It desperately wants to match video filenames to a poorly documented naming system; if files don’t match, they just don’t show up. And it tries to cache the scan so simply renaming files doesn’t really force a rescan. There’s no “scan everything” option in the web UI (there is in the native client). Oh, and the Web UI is terribly buggy and you have to reload it every time you change the folder list.

Next thing would be to install XBMC, but I’m already feeling bruised from dealing with all this poorly packaged hackerware. Full props to the folks making media software on unauthorized devices, but man is usability a challenge.

BTW, two crappy things about the Apple TV:

  • There’s no HDMI cable in the box
  • The remote is IR only

Cyberpower pwrstatd notes

I bought a Cyberpower UPS for my Linux server. I mostly like it, but the Linux software they include for it (pwrstat and pwrstatd) is comically bad. Network UPS Tools supports this UPS hardware too, if I weren’t so invested in this software already I’d try it instead.

Here are some bugs:

  1. There’s no source code available, just two little ELF binaries pwrstat and pwrstatd
  2. pwrstatd has to run as root, not a big surprise since it can shutdown the machine, but see bug #1. Also pwrstat (the userspace program) has to run as root, even to get the UPS status! It seems to mmap() itself into pwrstatd :-(
  3. The default configuration is to shut down your machine after 60 seconds of power failure, then shut the whole UPS off after 10 minutes. That’s awfully aggressive.
  4. Once a Linux box is shutdown, the ACPI system means it won’t reboot itself again when power is restored. Wake-on-LAN is the right way to fix this, I don’t know a quick and dirty way.
  5. The various utility shell scripts /etc/pwrstatd-*.sh are very poorly written. The mail program assumes /bin/mail has a -r flag (mine doesn’t). One script has a test for ENABLE_EMAIL being “YES”, the other tests for it being “yes”. None of the test arguments are quoted so missing variables throw shell syntax errors.
  6. Did I mention all the real work is done in pwrstatd, which runs as root, and for which there is no source code provided?

The cool thing about the UPS is the status report it gives over the USB includes a bunch of data, including how many watts the UPS is driving right now. I wrote a little Munin script and now I have a fancy graph of my server’s power consumption.

That graph above includes me unplugging the UPS and letting it run to zero. Original estimate was 82 minutes of runtime, actually got about 70. Oddly the power drain went up 10W after unplugged; the inefficiency of the AC generation?

This UPS seems to consume 10W of its own even when fully charged, and about 20W when charging. Not happy about that 10W. Also the “battery capacity” value is totally bogus during charging; it only updates when I force the UPS to run off battery or run a self-test.

Here’s my Munin plugin (first ever!)

#!/usr/bin/env python

"""
pwrstat - Plugin to monitor Cyberpower UPS via pwrstat

by Nelson Minar <nelson@monkey.org>, placed into the public domain

Unfortunately this plugin must run as root, because pwrstat requires
root to even read data from the UPS.
"""

import sys, subprocess

# config
if len(sys.argv) > 1:
 if sys.argv[1] == "config":
 print """
graph_title Cyberpower UPS Status
graph_category UPS
graph_vlabel value

inV.label Utility Voltage
inV.min 0
inV.max 200
inV.warning 100:130

outV.label Output Voltage
outV.min 0
outV.max 200
outV.warning 100:130

battery.label Battery Capacity (Percent)
battery.min 0
battery.max 100
battery.warning 35:105

runtime.label Remaining Runtime (Minutes)
runtime.min 0
runtime.max 200
runtime.warning 10:200

loadWatts.label Load (Watts)
loadWatts.min 0
loadWatts.max 1000
loadWatts.warning 30:150

loadPct.label Load (Percent)
loadPct.min 0
loadPct.max 100
loadPct.warning 0:75
"""
 sys.exit(0)
 else:
 sys.stderr.write("Unknown argument %s\n" % sys.argv[1])
 sys.exit(0)

# fetch

output = subprocess.check_output(("/usr/sbin/pwrstat", "-status"), shell=False)
output = output.split('\n')
data = {}
for datum in output[10:-2]:
 name = datum[:29].strip('.').strip()
 value = datum[31:].strip()
 data[name] = value

print "inV.value", data["Utility Voltage"].split()[0]
print "outV.value", data["Output Voltage"].split()[0]
print "battery.value", data["Battery Capacity"].split()[0]
print "runtime.value", data["Remaining Runtime"].split()[0]
print "loadWatts.value", data["Load"].split()[0]
print "loadPct.value", data["Load"].split()[1].split('(')[1]

sys.exit(0)

# This is the pwrstat format that we parse. Note, it contains tabs.
# Comes from pwrstat version 1.2
exampleOutput="""
The UPS information shows as following:

Properties:
 Model Name................... UPS CP1000AVRLCD
 Firmware Number.............. BFC7101.4K1
 Rating Voltage............... 120 V
 Rating Power................. 600 Watt

Current UPS status:
 State........................ Normal
 Power Supply by.............. Utility Power
 Utility Voltage.............. 125 V
 Output Voltage............... 124 V
 Battery Capacity............. 100 %
 Remaining Runtime............ 77 min.
 Load......................... 54 Watt(9 %)
 Line Interaction............. None
 Test Result.................. Passed at 2012/01/25 01:39:47
 Last Power Event............. None
"""