Energy Measurements

Besides all the automation that you can do with Home Assistant it also has a very nice Energy Usage dashboard to keep track of everything going on in your house. Having historic data is always good, especially if you don’t yet have any solar or a house battery so you can size the systems properly.

My setup keeps track of my grid electricity and gas usage thanks to a smart meter, solar via a couple of raspberry Pi, and water thanks to the fact that water meters broadcast their reading unencrypted!

Electricity and Gas

I finally relented last year and got a smart meter. My electricity is with British Gas and they rather cheekily just booked a meter replacement appointment without me asking. I decided to keep it rather than cancelling it as I’m a sucker for tech! I was put off because my existing meter would actually run backwards if I was generating more than I was using.

With the meter installed, it comes with a readout to show you how much you are currently using. Its not quite straight forward to get the details into Home Assistant. You can sign up on an app called Bright and get half hourly meter readings for free, and this has an integration built into Home Assistant. This is a nice quick way of getting the data but it isn’t very granular.

Alternatively you can get a different display from Hildebrand that not only will read your meter for instantaneous data, but also connects to your wifi and provides data via an MQTT connection to Home Assistant, with an associated integration.

Once connected, you can add the relevant entities into the Energy dashboard.

Solar

I have two relatively small grid tied solar installs (limited by the amount of roof space), one on the garage and one on the main roof both using Solis inverters. The problem with these inverters is that the default method of logging the data writes all the info off to a third party in China. Now I’m not necessarily a security nut, but I do like to avoid cloud based services wherever possible.

Thankfully, the logging stick that comes with the inverter actually just reads RS485 (modbus) registers. After much trial and error due to lack of decent documentation (or more to the point, documentation that actually agrees!) I managed to write a python script which reads the registers and posts the data to MQTT using the Home Assistant auto discovery layout.

This script is running on a PiZeroW, using the connector off the standard logging stick. I did ask if they had any broken sticks to save wasting a working one, throwing away all the electronics.

Water

The last bit of the puzzle for my house was a bit of a long shot. When we moved in we decided to go with a water meter due to the rates for our area being way too high. I didn’t think much of it, but as I now had a smart meter for gas and electric, plus all the solar being logged into Home Assistant, I thought I’d take a look. The fact that the Energy dashboard had a section for water definitely had a influence!

After wiping off a rather thick layer of dust from the meter, I got the model number and started looking things up about it. Turns out it broadcasts the meter reading on a standard 868Mhz, which of course can be listened in on using a simple, cheap USB digital TV dongle. I may have a few of them laying around the house (including one listening in to all the planes passing overhead). Even better, it was unencrypted.

Thankfully I didn’t have to write everything myself, there is already an open source program call wmbusmeters that will use an RTL dongle and output the data in JSON to the stdout. With a quick python wrapper to read that data and post it via MQTT for Home Assistant to read (again, using the auto discovery layout)

Energy Dashboard

All the entities created are then entered into the relevant sections in the Energy Dashboard. This automatically configures everything to display and record the information. It gives a nice page to view all the data. I’ve also got a number of devices hooked up with plug in energy meters so I can see the consumption of things like my server rack, computer, tv, etc. All of these will also get displayed on the dashboard.

Along with the dashboard, I also have graphs in Grafana for more granular details and spotting trends.

Future

At some point I want to possibly get a battery for the house. Once I’ve collected a year or so of data I’ll have a much better idea on the suitable size to get and should be able to calculate a fairly accurate ROI. For now I’m just happy to keep track of the energy usage.

Control Panel and more!

As the weather is still terrible around here, I spent the weekend working on my home automation. A load of general maintenance such as replacing batteries and fixing broken things like the integration with the burglar alarm.

I also added a few new integrations:

  • DVLA Link – This lets me query details about our cars, and more specifically the due dates for MOT and insurance.
  • Waste Management – Link into the local government to know when and what type of refuse collection is coming up.

But, the most fun one was finally getting the 10 inch display and Raspberry Pi mounted on the wall as a custom control panel!

I’ve had it sat on my desk for about six months and decided it was actually time to get it done. I had to CAD up a box for wall mounting and hiding the electronics. Not the best design, and lots of things to improve, but its functional.

A quick couple of holes in the wall, and it was mounted.

Once I have the local voice assistant details finished, this will get that installed too. That will need a redesign of the case to support some speakers and volume controls. The actual dashboard needs a bit more work, and possibly an LCARS theme as an option.

But at least its off my desk and working now. Very handy for a quick glance at the calendar, weather, alarm status, and also to view the front door camera.

Automate Everything

Over the years I’ve messed with various home automation systems. From X10 in the early 2000’s, through Mi Casa Verde and z-wave going into the 2010’s, a few years using OpenHAB, up to the current day where I’m using Home Assistant.

Home Assistant has been around for a while, but I was loathe to move from OpenHAB as I already had a lot set up. However, as OpenHAB fell behind I finally bit the bullet and installed HAOS on a spare Raspberry Pi. This turned out to be a good thing.

I’ve been using it now for a couple of years, and it works really well as a central hub for all the different technologies in the house. This post is a quick overview of what I have set up.

Technologies

The beauty of Home Assistant is that it acts as a hub for many different home automation protocols, devices, and other information. A quick list of technologies I have integrated:

  • Zigbee
  • Z-wave
  • ESPHome
  • Matter
  • Thread
  • MQTT
  • WLED

But not only does it talk to these home automation systems, it can also tie into other things such as:

  • 3d Printers (Octoprint, Klipper, Bambu Labs)
  • Google Assistant (Ties your home automation into google voice commands)
  • Jellyfin/Plex
  • Fitbit
  • Raspberry Pi
  • Roomba
  • Smart Meters
  • Printers (you know, the none 3d kind)
  • Frigate (CCTV)
  • Solar Production

And lastly, you can pull in information from web APIs to help with automations:

  • Weather
  • Sunrise/Sunset
  • Moon phases
  • Astronomy Weather (More detailed weather more geared to astronomers)
  • Github (Monitor commits, issues, etc.)
  • Whois (Keep an eye on domains expiring)
  • DVLA (MOT and insurance due dates)
  • Waste Management (get dates and types of refuse collection)

This is a lot of tech, and this isn’t a complete list of everything I have tied in, just the majority.

My Setup

So, enough of what it can talk to. How is my house set up?

Core

The main core of the system is a Raspberry Pi 4 running Home Assistant OS. This is a simple install onto a Pi and is fully managed by Home Assistant. Everything runs in containers and gives you everything you need to get started.

The Pi is run from PoE in a rack, to keep things simple, and also has everything installed onto an SSD drive as it is a lot more reliable that using an SD Card (My old OpenHAB system was on SD Card and I had to rebuild it every now and again as the SD card wore out). Plugged into the Pi are two USB dongles, one for z-wave and one for Zigbee/Matter. This direct connection lets me control the majority of the devices I have.

Also, installed as part of HA OS I have a few other addons. These are:

  • InfluxDB – This keeps a historical record of all the stats in the house, which can then be pulled out into a Grafana Dashboard
  • Mosquitto MQTT Broker – Some devices talk directly to an MQTT server, so this is running to fill that role
  • ESPHome – A system designed to convert simple ESP32 or ESP8266 boards into home automation devices using a simple yaml language. Some commercial devices can also be flashed with ESPHome for extra functionality.
  • HA Google Backup – Backups!!
  • Lets Encrypt – Automatically renews my SSL cert
  • VaultWarden – A locally run version of Bitwarden password manager.

These are all running on the same Pi quite happily.

CCTV (Frigate)

I have a second Pi 4 running a system called Frigate. This is an open source CCTV system that integrates really nicely with Home Assistant. It also has functionality for not only motion detection but facial detection too so that it will only trigger if it detects a human (not a cat or squirrel) which definitely helps cut down on false positives. I have had to block out certain areas for detection tho, as in high winds it sometimes thought some of Joy’s flowers were a human!

I’m hoping to upgrade this to a Pi 5 when the PoE hat comes out, as I currently have 4 cameras going into it and it does struggle a bit. I do have a USB Coral AI stick from Google that I can offload some of the more AI related tasks too.

NAS (TrueNAS Scale)

I do have a NAS box set up that has a simplified Kubernetes system installed. On this I run a few other services, including Grafana for viewing stats of my home, Spoolman which keeps track of my 3d printer filament usage, and Trilium Notes for keeping track of the random things in my brain.

Other Hardware

So what have I actually got set up?

Most of the main lighting in the house are Phillips Hue lights, with their dimmer controllers. However, since realising just how much data the Hue hub was sending back, I removed that and now everything is directly controller via Zigbee. The only main exception to this is the garage which initially had fluorescent tubes and I use a z-wave in wall module to control that.

I’ve a lot of smart sockets around the house too, from plugin units to actual in wall faceplates. The vast majority of these allow for energy usage collection too so I can not only turn things on and off remotely, but I can also monitor the energy usage of various items such as 3d printers, server cabinets, desktops, TVs, etc.

The burglar alarm is also connected in, which turns all the various door and motion sensors into sensors that Home Assistant can use for automations.

WLED is a system to install onto an ESP8266 or ESP32 to control a string of RGB LEDs. I’m starting to incorporate more of these into the setup and they tie very nicely into Home Assistant

Control

What does all this gain me? The main benefit is a single app on my phone to control everything. I don’t need a Hue app, a Roomba app, to access a webpage to control my WLED lights, etc. I can create a dashboard on Home Assistant to give me a nice overview of the controls in the house. For instance, my setup main dashboard consists of an overview page (simple controls such as lights, along with main thermostat control and some other status) with the ability to click a room and get more detailed controls and information. That covers about 90% of everything.

Along with this, as I have Google Assistant integrated, I can also just ask google to turn lights on, set the thermostat, etc.

Automations

So far, most of the stuff is just allowing for remote control, but the real beauty is making things automatic. I’ve only really got some basic automations done at the moment and want to expand on this in the future.

  • Automatic outside lights. I have the lights set to come on at sunset, and turn off at midnight. They’ll also come on in the morning if Joy is going to work and its still dark out.
  • Turn the thermostat down at night. The thermostat will drop a couple of degrees at midnight whilst we’re asleep to save some energy. I have got the alternative set to turn it back up in the morning, but thats disabled for now as its just as easy to turn it up manually depending on what time we get up.
  • Send an alert if someone comes to the front door, and turn the light on. This is one of the reasons I want to upgrade the Frigate Pi. The Pi 4 is just a little slow on this, and hoping the extra processing power will speed things up.
  • Show video feed on my google home displays when someone is detected on the front door camera.
  • Automatic office lights. I’m terrible at remembering to turn my light off in the office, so I have a simple motion detector to automatically turn the lights on and off. They do turn off occasionally if I’m in the office concentrating on something and not moving much (such as writing a blog post about my home automation system) so I’ve just ordered some mm wave detectors to try which should be more sensitive.
  • Notifications when prints have finished or theres an issue.
  • Daily notification if a battery is low in a device. All my Phillips Hue Dimmers were bought at the same time, and I’ve just had to replace all the batteries at once!

Theres room to do a lot more of course, but these will do for now.

Monitoring

So, I’m a nerd and I like stats. One of my favourite things that Home Assistant does is store historical data so that I can pull information out and graph it in Grafana. I’ve no idea if this will have future uses, but it does produce some pretty pictures such as the one on the left that shows temperature and humidity over time.

Also, Home Assistant has an inbuilt energy dashboard. You can select the various entities you monitor for energy usage from smart meters or solar panels, and it will generate a nice dashboard to show your energy usage.

Water consumption is on there because it seems UK water meters broadcast their readings unencrypted on a band that can be read with a cheap USB dongle. I wrote some python to read the meter and push the stats into Home Assistant. I also wrote some software to run on a Pi connected to my two solar systems to read the meter information there and push it into Home Assistant.

I’m hoping once I’ve collected data for a full year, I can work out if I can get a decent ROI on a house battery.

Future Plans

One of the big things at the moment is LLMs (I won’t call them AI!) and Home Assistant can actually make use of them right now. This means I can replace all my spyware Google Homes with a fully local solution running on some low powered Raspberry Pi zeros, using a local LLM for more natural language communication. Plus you get the ability to add custom wake words, which will be fun.

I’ve also got a Pi with a 10 inch display on my desk that I want to turn into a control panel to put somewhere in the house, possibly in the entrance way.

Pretty Solar Graphs

The first step on my solar progress is to get some graphs done, to get an idea of how much energy I can get from my solar panels on an average day. From this I can work out what I can conceivably run from my setup.

Background

Previously, I installed a simple solar setup for testing. This is using an EPEver Tracer1210A solar charge controller, from Tracer. It wasn’t the cheapest, but it had a lot of good reviews (watch out for cheap copied). The other benefit was the fact it had a serial output that talked modbus, or rs485. Intended for official devices, they do provide the protocol to allow third parties to read the system details.

After doing some searching, I discovered Jamin on github who had done some coding and circuit design to get the current details from the charge controller and push the results out to a service called Blynk.

My Project

Overview

This project gave me the starting point for what I wanted to do. My idea was to do this:

Controller -> RS485 -> NodeMCU -> MQTT -> OpenHAB -> InfluxDB -> Grafana

A little bit convoluted, I could probably have pushed straight to a database for logging, and do the graphs in grafana. I decided that pushing via MQTT would allow me to integrate the logging into my OpenHAB system, which would give me the capability to trigger home automation actions depending on the statistics from the charge controller. For example, it makes it very easy to use OpenHAB to send an email if the battery level gets low, and not only that it could turn off some of the load running off the battery as it gets to different levels.

Circuit

The circuit is pretty much a direct copy of what Jamin used, only adapted for a NodeMCU rather than a ESP8266 Mini Dev board.

Bad photo of current system.

Prototype of circuit. Ordered a 5110 LCD to add to it, and will neaten it all up then.

I did look into powering this from the 5V on the serial output of the charge controller, but according to the documentation this can only put out about 50mA of power, which probably won’t be enough to cover the usage by the NodeMCU.

Code

The initial code can be found on my github repository here:

https://github.com/dpoulson/EPSolar

Still a work in progress, but it does the basics so far. Future improvements will allow writing of certain settings, maybe a simple webserver for point in time readings, or an LCD screen.

Logging

So the circuit will transmit the readings over wifi to my central MQTT server, running mosquitto. MQTT is just a simple messaging system when you can subscribe to, or publish to, certain queues.

Readings from the charge controller will be published to set queues on the server, which OpenHAB will be subscribed to, with the following items file:

Number EPSolar_Temp "Temperature [%.2f °C]" { mqtt="<[mymosquitto:EPSolar/1/ctemp:state:default" }

Number EPSolar_BattVolt "Battery Voltage [%.2f V]" { mqtt="<[mymosquitto:EPSolar/1/bvoltage:state:default" }
Number EPSolar_BattRemain "Battery Remaining [%.2f %]" { mqtt="<[mymosquitto:EPSolar/1/bremaining:state:default" }
Number EPSolar_BattTemp "Battery Temp [%.2f °C]" { mqtt="<[mymosquitto:EPSolar/1/btemp:state:default" }

Number EPSolar_LoadPower "Load Power [%.2f W]" { mqtt="<[mymosquitto:EPSolar/1/lpower:state:default" }
Number EPSolar_LoadCurrent "Load Current [%.2f A]" { mqtt="<[mymosquitto:EPSolar/1/lcurrent:state:default" }

Number EPSolar_PVVolt "PV Voltage [%.2f V]" { mqtt="<[mymosquitto:EPSolar/1/pvvoltage:state:default" }
Number EPSolar_PVCurrent "PV Current [%.2f A]" { mqtt="<[mymosquitto:EPSolar/1/pvcurrent:state:default" }
Number EPSolar_PVPower "PV Power [%.2f W]" { mqtt="<[mymosquitto:EPSolar/1/pvpower:state:default" }

Number EPSolar_ChargeCurrent "Battery Charge Current [%.2f A]" { mqtt="<[mymosquitto:EPSolar/1/battChargeCurrent:state:default" }

Number EPSolar_PVVoltMax "PV Voltage MAX (today) [%.2f V]" { mqtt="<[mymosquitto:EPSolar/1/stats_today_pv_volt_max:state:default" }
Number EPSolar_PVVoltMin "PV Voltage MIN (today) [%.2f V]" { mqtt="<[mymosquitto:EPSolar/1/stats_today_pv_volt_min:state:default" }

My OpenHAB system is configured to store persistence data into an InfluxDB server, which is a common setup amongst the OpenHAB community and is well documented. This InfluxDB stores historic data on items in OpenHAB, which is searchable by Grafana. Grafana gives a nice interface to produce all the pretty solar graphs you might want.

Solar Graphs

Using Grafana to get some pretty solar graphs

Pretty Solar Graphs

This makes it really easy to see just what is happening, including the charging states as it you can see the switch from bulk to float charge on the battery voltage. This should allow me to make sure the charging is correct for the Lithium Ion batteries I want to eventually connect.

Solar!

Over the last couple of years I’ve been looking at the feasibility of  getting photovoltaic cells put on the roof of my house. I’ve only got a small amount of roof space seeing as I live in a mid terrace so wasn’t sure if I could get enough panels to make it worth while. A couple of months ago I decided to take the plunge and get a few quotes in. Unfortunately, this is where I met the main hurdle with the whole project. Despite emailing half a dozen companies, I only got two visits to give me a quote, and only one of those actually sent me a quote.

Thankfully I’d done enough research into the technology and rough costs so that I knew the quote I got back was a pretty typical price. The company also seemed to be pretty decent with some good reviews and a good web site. With all that in mind, I decided to go for it and accepted the quote. I was very impressed with how quickly things went. One of the requirements for getting the feed in tariff from the government is to get an Energy Performance Certificate (EPC) and within a few days I’d had the survey done for that and the certificate in my hands. Only a little over a week later the panels were installed, commissioned and my meter was running backwards.

 

Solar install

Solar install

So, what did I actually get installed? All together, 16 panels were squeezed onto my roof across two elevations with 8 on a west facing aspect and then 8 on the south facing which gave me 4kW in total. The installation is fairly straight forward and involves the two arrays of panels going into an inverter which feeds into the main circuit breaker panel. I’ve also installed a full monitoring system that keeps track of power consumed and solar power produced, which I’ll probably write about in another blog post.

The big question however is, is it all worth it? I haven’t been running them for long enough really to give a definitive answer, but from the calculations I’ve done I think the answer is a resounding yes. The feed in tariff is index linked, so will increase over the 20 year lifespan of the panels along with inflation, and it is highly unlikely that the price of electricity is going to go down, all of which means that I should have paid off the panels totally in under 8 years. I can see that number dropping quite a bit too as electric prices increase. Also, the feed in tariff runs for 20 years, but the panels should last even longer than that and are still 80+% efficient after the 20 year mark so should be providing free electricity for many years after the feed in tariff has finished. Over a 20 year period, the initial investment should see a return of over 12% which is so much more than any bank can offer.

If you can afford to get PV installed, I’d definitely recommend it. I’ve already seen a drastic drop in my electric usage and the money is much better installed on my roof than in the bank.

 

Home Monitoring

Over the past few months I’ve been slowly stocking up on all the equipment needed to properly get back into electronics. As I was gathering things together I discovered Arudinos. These are an easy entry into microcontrollers, much simpler in my opinion to PICs, and cheaper than most other developers kits. The fact that they’re open source and open hardware just seals the case. The standard Arudinos are rather nice to work with, but since messing with them on a few mini projects to teach myself about them, I came across a guy who was selling his own custom design, utilising the arduino bootloader and interface, but in a much smaller form factor and inbuilt wireless communications.

These JeeNodes are about the size of a pendrive, and have an inbuilt RF12B wireless module. Along with the nice hardware design, there are also some easy to use libraries, and a great website to accompany them, with lots of nice tutorials, information, and general geekiness.

Home Automation

So, where does home monitoring come into this? One of the addon boards that Jeelabs sell are little room monitoring nodes that detect temperature, humidity, and light level. Add a PIR and you’ve got a motion sensor too. The guy behind the JeeNodes, Jean-Claude Wippler, has done some great work on power consumption meaning that these room nodes can run off a single AA battery for nearly a year. There are about a dozen or so of these nodes now spread across my house, logging into a database, and I’ve done some basic graphs to display the data.

Home Automation

Now I’d also noticed another project using arduinos to monitor electric consumption that was also based on JeeNodes, and reporting back to a central server to log into a database. This got me thinking, could I combine these, and maybe more. The beauty of open source is the fact you can tweak and edit to your hearts content. The fact that both these projects used JeeNodes, and more importantly, the RF12B library from JeeLabs, means that I only need one receiving station and a few small edits to the nodes.

To the transmissions I added a node type to the beginning of the data. This defined whether the node was a room node, power node, or any other future node types I may define. Most of the rest of the code was left untouched, except to assign a node number to each node. That was the easy bit.

Next I needed a receiving station, and some way to get the data it received into a database. For this I once again turned to the JeeNode. Handily, JeeLabs also sell a nice case for the JeeNode, along with a Ethernet add on. This gives me a very small self contained module that simply needs power, and an ethernet connection. Both the energy monitor project, and the room node project had their own code for a base station, and for getting the data into the database. In the best traditions of open source, I have stolen from both these projects and combined my favourite ideas out of both.

The houseNode sits and listens for any broadcasts from any nodes. It knows about the different types of nodes, and the data structure to be expected for those nodes. When a data packet is received then the node type is stripped out, and the rest of the data put into a structure definition depending on the type. Then a JSON structure is constructed, and sent via HTTP POST to a web server. No acknowledgements of data being received are currently sent, but with future expansions that I have in mind, this will be a requirement.

Home Automation Home Automation

The web server will receive the POST command, and basically dump this information into a database. From this database, a front end can draw graphs and report on anything you want. The front end is very much still in construction, but can be viewed at http://home.22balmoralroad.net/

Future developments I am considering are a thermostat node, to control our central heating, and RFID entry/exit nodes to log in and out of the house. The RF12B modules have a limit of 32 addresses, two of which are reserved. However, 30 nodes should be enough for most of my ideas! It does have the other benefits of very low power, very simple, and the JeeLabs library even has encryption built in. Below are the Arduino sketches for each of the nodes.

 

 

Caller ID from Asterisk to all phones, MythTV’s and SqueezeBoxes

Well, I had some spare time and finally got round to getting CallerID sorted on my phones. I’ve had it enabled on the line for a while now, and even had it doing database lookups to display a name on the phone handsets as well as the number, tho’ that broke when I upgraded Asterisk. I have, however, sorted out that problem and expanded everything a little.

Now, when the phone rings, the number is looked up in a database of known numbers, then sent out to all the phone handsets as well as any active MythTV frontend or Squeezebox on the network! If we are watching the TV a box pops up with the time, date, number, and if found, name of the incoming call. Likewise if we are in the library where we can’t actually hear the phone, then the Squeezebox display will change to the name and number and we can decide wether to answer it or not!

All this is done using a feature in Asterisk call AGI, or Asterisk Gateway Interface. This is very similar to CGI scripts found on web pages. AGI scripts are run from the Asterisk dialplan to do various things. In this case the AGI perl script is run and the incoming call number is passed to it. This number is looked up in a database to see if its a known number. Wether it is known or not, the script sets the full CID info in Asterisk.

It then procedes to use a utility call cidbcast that is in the contrib directory of MythTV. This cidbcast sends out a UDP broadcast over the network to any listening machine, in this case the MythTV backend server which has the mythudprelay program running, another one from the MythTV contrib directory. This picks up the broadcast and sends the message to all MythTV frontends using mythtvosd.

Lastly the AGI script connects to the SlimServer which controls all the Squeezeboxes. Talking over the CLI port (9090) on the server it gets a list of all current players and proceeds to send a simple two line display message consisting of the number and name. The majority of this part of the script is a simple cut and paste of the relevant parts of the Squeezebox plugin written by Max Spicer.

All in all this is a fairly simple thing to implement, but is very useful for those as lazy as me!

Script

#!/usr/bin/perl

use DBI;
use IO::Socket;

# MySQL settings for asterisk
my $dbhost = 'localhost';
my $dbuser = 'asterisk';
my $dbpass = 'asterisk';
my $dbname = 'asterisk';

# Slimserver Settings
my $serverAddress = 'mythbe-1';
my $serverPort = 9090;
my $maxVolume = 75;
my $displayTime = 30;
my $debug = 0;

# Mythtv Setting
my $mythxmlfile = '/usr/lib/asterisk/cidbcast.xml';



################
# Get name from mysql for the incoming number
#
$|=1;

#Get the initial data
     my %input;
     while() {
         chomp;
         last unless length($_);
         if (/^agi_(\w+)\:\s+(.*)$/) {
         $input{$1} = $2;
     }
}

my $dbh = DBI->connect ("dbi:mysql:host=$dbhost:database=$dbname","$dbuser","$dbpass") or die "Can't connect to database: $DBI::errstr\n";
my $sth = $dbh->prepare( "SELECT cid FROM known_numbers WHERE source='$input{callerid}'" );
$sth->execute();
@row = $sth->fetchrow_array();
$cidname = @row[0];
print "SET CALLERID \"@row\"<$input{callerid}>";

###############
# Broadcast info to MythTV
my $command;
$command = "cidbcast --once --file=$mythxmlfile 6947 $input{callerid} \"$cidname\" line";
system("$command &> /dev/null");

################
# Send out to squeezeboxes
# Code ripped from Squeezebox CID plugin by Max Spicer
# http://www.thespicers.net/cid.html
#

my $socket = IO::Socket::INET->new (PeerAddr => $serverAddress,
                                    PeerPort => $serverPort,
                                    Proto    => 'tcp',
                                    Type     => SOCK_STREAM)
or die 'Couldn\'t connect to server';

# Get the number of players
my $playerCount = sendAndReceive('player count ?');
$debug && print "$playerCount players found\n";

# Display message on each player and adjust volume if necessary
for (my $i = 0; $i < $playerCount; $i++) { my $playerId = sendAndReceive("player id $i ?"); # Put the players display at max brightness if it's currently 0 my $powerState = sendAndReceive("$playerId power ?"); my $brightnessPref = $powerState ? 'powerOnBrightness' : 'powerOffBrightness'; my $brightness = sendAndReceive("$playerId playerpref $brightnessPref ?"); $debug && print "brightness: $brightness\n"; if ($brightness == 0) { sendAndReceive("$playerId playerpref $brightnessPref 4"); } $cidname =~ s/\s/%20/g; $debug && print("Sending: $playerId display Incoming%20call:%20$input{callerid} $cidname $displayTime\n"); sendAndReceive("$playerId display Incoming%20call:%20$input{callerid} $cidname $displayTime"); # Drop the volume if necessary my $playerMode = sendAndReceive("$playerId mode ?"); $debug && print "playerMode: $playerMode\n"; if ($playerMode eq "play" && sendAndReceive("$playerId mixer volume ?") > $maxVolume) {
    $debug && print "Decreasing volume\n";
    sendAndReceive("$playerId mixer volume $maxVolume");
  }
}
$debug && print "\n";
exit 1;

# Send given cmd to $socket and return answer with original command removed from
# front if present.  Routine nicked from code by Felix Mueller. :-)
sub sendAndReceive {
  my $cmd = shift;
  return if( $cmd eq "");

  print $socket "$cmd\n";
  $debug > 1 && print "Sent $cmd to server\n";
  my $answer = <$socket>;
  $debug > 1 && print "Server replied: $answer\n";
  $answer =~ s/$cmd //i;
  $answer =~ s/\n//;

  return $answer;
}

Database table structure

mysql> describe known_numbers;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| source | varchar(13) |      | PRI |         |       |
| cid    | varchar(26) |      |     |         |       |
+--------+-------------+------+-----+---------+-------+