Sunday, December 04, 2016

Using Conrad RSL sockets with RFXCom and Home Assistant

I wanted to get my Conrad RSL sockets (RSL3660R-UK) working with Home Assistant

The user guide for the RFXCom describes how to get them working, but I needed to work out what the device id for Home Assistant. Luckily Home Assistant just uses the parsing of a RFXtrx packet to work this out, so I just had to work out the format. I used the user guide and pyRFXtrx code to work it out. The bytes break down as follows:

  1. 09 - length
  2. 13 - lighting 4
  3. 00 - subtype = PT2262
  4. 04 - sequence number
  5. XX - cmd 1 - Group:
    • 15 - Group I
    • 45 - Group II
    • 51 - Group III
    • 54 - Group IV
  6. YY - cmd 2 - Unit:
    • 15 - Unit 1
    • 45 - Unit 2
    • 51 - Unit 3
    • 54 - Unit 4
  7. ZZ - cmd 3 - State:
    • 55 - On
    • 54 - Off
  8. 01 - high byte of pulse timing (425ms)
  9. A9 - low byte of pulse timing (425ms)
  10. 00 - seems to always be null
However there isn't any way to send lighting 4 packets directly from Home Assistant. Luckily Linux is happy to share ttys, so the following commands work:
# Group I, unit 1 - on
echo -ne '\x09\x13\x00\x04\x15\x15\x55\x01\xA9\x00' > /dev/serial/by-id/usb-RFXCOM_RFXtrx433_A1WRPM1W-if00-port0
Trying to work out the correct stack of escaping of text in both YAML and shell (which will be dash on Ubuntu and Debian systems) makes it far easier to write a script to do this. So I put the following into /home/hass/bin/switch_rsl.sh:
#!/bin/bash

set -e

# Path to your RFXCOM device
RFXCOM_DEV=/dev/serial/by-id/usb-RFXCOM_RFXtrx433_A1WRPM1W-if00-port0
# Number of times to send the command
REPEAT=2
# Pause between each command being sent
REPEAT_DELAY=0.2

function print_usage()
{
  echo "Usage: $0 [I|II|III|IV] [1|2|3|4] [On|Off]"
}

case $1 in
I)
  GROUP=15
  ;;
II)
  GROUP=45
  ;;
III)
  GROUP=51
  ;;
IV)
  GROUP=54
  ;;
*)
  echo "Invalid group: $1"
  print_usage
  exit 1
  ;;
esac

case $2 in
1)
  UNIT=15
  ;;
2)
  UNIT=45
  ;;
3)
  UNIT=51
  ;;
4)
  UNIT=54
  ;;
*)
  echo "Invalid unit: $2"
  print_usage
  exit 1
  ;;
esac

case $3 in
On|on|1)
  STATE=55
  ;;
Off|off|0)
  STATE=54
  ;;
*)
  echo "Invalid state: $3"
  print_usage
  exit 1
  ;;
esac

for V in 1 .. $REPEAT
do
  echo -ne "\\x09\\x13\\x00\\x04\\x$GROUP\\x$UNIT\\x$STATE\\x01\\xA9\\x00" > "$RFXCOM_DEV"
  sleep $REPEAT_DELAY
done
Then the configuration for Home Assistant is just:
switch:
  - platform: command_line
    switches:
      rsl_i_1:
        command_on:  "/home/hass/bin/switch_rsl.sh I 1 On"
        command_off: "/home/hass/bin/switch_rsl.sh I 1 Off"
      rsl_i_2:
        command_on:  "/home/hass/bin/switch_rsl.sh I 2 On"
        command_off: "/home/hass/bin/switch_rsl.sh I 2 Off"
      rsl_i_3:
        command_on:  "/home/hass/bin/switch_rsl.sh I 3 On"
        command_off: "/home/hass/bin/switch_rsl.sh I 3 Off"

Sunday, June 26, 2016

Wifi device detection with Domoticz and OpenWRT

I've recently started using Domoticz to control my various home automation systems. One of the bits of information about the house that I wanted to gather was the presence of mobile phones on the wireless network. Both my partner and I always have our phones with us, so if they are present on the network then it's a good bet that we're at home. This allows constructing domoticz rules based on who's in the house.

There are many examples of scripts on the internet that show how to do this in Domoticz using either ping, arp-scan or a combination of the two. However the success of them seems to be varied at best. The main issue appears to be that mobile devices attempt to conserve power by not being 'active' (whatever that means) on the wireless network. I tried to make my scripts more accurate by adding more and more layers of complexity and complex rules. Eventually I decided the active scanning approach was doomed.

Luckily I run OpenWRT on both of my wireless access points. Logging into the OpenWRT boxes and running

/usr/sbin/iw dev wlan0 station dump
will give a dump of information about the various devices. The next question was how to get this information from the OpenWRT system to the system running Domoticz. I decided to use xinitd on OpenWRT, which allows binding the output of an arbitrary command to a TCP port. It's not at all secure, but I'm happy to take the risk as this isn't going to be facing the public internet. To configure OpenWRT do the following:
  1. Install xinitd:
    opkg update && opkg install xinitd
  2. Edit
    /etc/services
    to contain the following line:
    wlanap 8216/tcp
  3. Create
    /etc/xinetd.d/wlanap
    containing:

    service wlanap
    {
    socket_type     = stream
    protocol        = tcp
    wait            = no
    user            = root
    group           = root
    server          = /usr/sbin/dump_ap
    disable         = no
    only_from       = 192.168.XXX.XXX
    }


    Replacing
    XXX.XXX
    with the IP of the machine running Domoticz.
  4. Create
    /usr/sbin/dump_ap
    containing:

    #!/bin/sh
    /usr/sbin/iw dev wlan0 station dump
    Note: If your router has multiple wireless interfaces (e.g. 2.4GHz and 5GHz) then you should repeat the last line in the script for the other interfaces, such as wlan1.
  5. Mark it as executable:
    chmod a+x /usr/sbin/dump_ap
  6. Restart xinetd on OpenWRT
  7. Repeat for each OpenWRT box

It should be noted that the help for the iw tool does give the following warning:
Do NOT screenscrape this tool, we don't consider its output stable
. So every time I update OpenWRT I am going to be at risk of things breaking, but that will just add to the excitement of applying updates!

So the last piece in the puzzle was to write a script to periodically query my wireless access points and toggle virtual switches in Domoticz as appropriate. I created a couple of virtual switches in Domoticz for each of the devices of interest and then created a cronjob to run the following Python script periodically:
#!/usr/bin/env python
# Detects ARP addresses

import argparse
import json
import logging
import os
import re
import socket
import subprocess
import sys
import urllib2

log = logging.getLogger()

DEFAULT_ARP_SCAN = "/usr/bin/arp-scan"
DEFAULT_CONFIG_LOCATION = os.path.join(os.environ['HOME'], ".detect-arp", "config.json")

DOMOTICZ_URL = "http://localhost"

ARP_TO_IDX = {
    "12:34:56:78:9A:BC": 31, # Dave's Phone
    "DE:AD:BE:EF:00:12": 37, # Bob's Phone
}

WLANAP_HOSTS = ["AccessPoint1", "AccessPoint2"]
WLANAP_PORT = 8216
ARP_LINE_RE = re.compile(r"^Station ([0-9a-f:]{17}) \(on .+\)$")

def getArps():
    foundArp = set()
    for host in WLANAP_HOSTS:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, WLANAP_PORT))
        data = ""
        while True:
            dataFrag = s.recv(4096)
            if len(dataFrag) == 0:
                break
            data += dataFrag
        for line in data.split("\n"):
            m = ARP_LINE_RE.search(line)
            if m is None:
                continue
            arpAddr = m.group(1)
            log.debug("Found ARP %s", arpAddr)
            foundArp.add(arpAddr)
    return foundArp

def scan(args):
    log.debug("Starting scan")
    foundArp = getArps()
    
    # Update the switch state as needed
    log.debug("Toggling switches")
    for arpAddr, idx in ARP_TO_IDX.iteritems():
        # Get the current state
        stateUrl = "%s/json.htm?type=devices&rid=%d" % (
            DOMOTICZ_URL, idx)
        resp = urllib2.urlopen(stateUrl)
        jsonStr = resp.read()
        stateData = json.loads(jsonStr)
        if stateData.get("status", None) != "OK":
            log.err("Reply from '%s': %s", stateUrl, jsonStr)
            continue

        currentState = stateData["result"][0]["Status"]
        
        if arpAddr in foundArp:
            switchCmd = "On"
        else:
            switchCmd = "Off"
        if switchCmd == currentState:
            log.debug("Not switching %d due to unchanged state (%s)", idx, switchCmd)
            continue
        log.debug("Switching %s (%d) to %s", arpAddr, idx, switchCmd)
        switchUrl = "%s/json.htm?type=command¶m=switchlight&idx=%d&switchcmd=%s" % (
            DOMOTICZ_URL, idx, switchCmd)
        resp = urllib2.urlopen(switchUrl)
        data = resp.read()
        switchData = json.loads(data)
        if switchData.get("status", None) != "OK":
            log.err("Reply from '%s': %s", switchUrl, switchData)
            continue

def install(args):
    log.debug("Starting install")

def uninstall(args):
    log.debug("Starting uninstall")

def getParser():
    parser = argparse.ArgumentParser(description="Detects devices on the network based on ARP")
    parser.add_argument("--arpscan", dest="arpScanPath", default=DEFAULT_ARP_SCAN,
                        help="Location of arpscan, default %(default)s")
    parser.add_argument("--config", dest="configPath", default=DEFAULT_CONFIG_LOCATION,
                        help="Location of the config file, default %(default)s")
    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true",
                        help="Enable verbose output")
    subParser = parser.add_subparsers(title="action", dest="action")

    scanParser = subParser.add_parser("scan", help="scan for devices")

    installParser = subParser.add_parser("install", help="install script into crontab")

    uninstallParser = subParser.add_parser("uninstall", help="uninstall script from crontab")

    return parser

def main():
    parser = getParser()
    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
    commandFn = globals()[args.action]
    commandFn(args)

if __name__ == "__main__":
    main()

Note: You'll want to customise the MAC address to switch indexes defined in
ARP_TO_IDX
and make sure that
WLANAP_HOSTS
contains each of the host names for your WiFi access points.

Thursday, August 21, 2014

Truncated Logs and Trees

When asking someone else for help it can be tricky to adjust between the information rich and bandwidth constrained worlds of the real and the virtual. If I have a tree at the bottom of my garden which loses all its leaves one summer then the conversation with an expert on tree disease would go something like this:

"Hello Dave the tree expert," I would say.

"Hi Toby, what's up?" he would reply.

"I think the tree at the bottom of my garden is dying."

Dave would then start to investigate, "Why do you think that?"

"Because it's lost all its leaves," I'd say.

"Hmmm," he would say as he stroked his chin with his hand, "did they all drop over a couple of days? Or was it over a period of weeks?"

The conversation would then continue to go back and forth between us with Dave asking various questions to narrow down the issue. Unless I'd had too much coffee that day I would be very unlikely to approach Dave and say:

"Hi Dave," I'd blurt out.

He would just have time to say, "Oh Hello Toby-"

I would then interrupt him and say, "I have a tree. It's dying. It's at the end of my garden. I have just got a new cat. All the leaves fell off the tree. They were green, but went brown before dropping off. They have a strange white haze on them. The neighbour has just had some building work done right next to the corner the tree is in. I had waffles for breakfast. I just planted a row of lavender at the other end of my garden. The tree trunk looks the same as always. It's been a dry summer, but the winter was very damp."

Trying to throw all this information at the person in one go, without knowing what is relevant and what isn't, just doesn't work as an efficient way to communicate. In fact it is generally the case that the best problem solvers in any given area aren't the experts with the most in-depth knowledge but the ones who know the right questions to ask, as well as what order to ask them in. However with computer systems this is not generally the case.

Most pieces of computer software produce logs. These contain a history of events and observations that the software has made about the world. They can be very useful for tracking down why a program is behaving in a particular way, especially if the information which is chosen to be logged describes the state of the system sufficiently.

When asking someone for help you should always give them full access to the logs. First you should described the problem; you should say what's happened, not what you think has gone wrong. Think "I crashed my car as the brake peddle didn't slow the vehicle down" rather than "I think my brake pads are worn".

Once you've done that you should provide the full logs. If you have some thoughts on which lines in the logs are most important then do explicitly mention them, but don't delete everything from the log apart from what you think is important. You are asking for help. You don't fully understand the system. You will cut important information out of the logs because you don't think it's relevant because you don't appreciate the full issue. If you did know enough about what was going on to know which log lines are relevant then you wouldn't need to ask for help!

So please, when asking for help, send full logs and describe what the issue is, don't just make guesses and provide incomplete information to someone who is trying to aid you.

Friday, September 06, 2013

PyMythTvFs

Fed up with MythTvFs breaking on my Linux MythTV backend when I upgraded MythTV I created PyMythTvFs.

PyMythTvFs is a Fuse based file system written in Python for accessing MythTv recordings as a file system. It's still very much work in progress but it is functional and allows playback of recorded programs.

In the future I intend to add several other features, such as folders, delete support and custom format strings. That's still to come, but for now it allows easy watching of MythTV programs.

Wednesday, February 01, 2012

Reverting or rolling back accidental commits in SVN

When using SVN it's sometimes the case that you'll type:
svn commit
Only to realise that you've just accidentally committed the wrong changes, or even some files you didn't want in the subversion repository.

Obviously the svn revert command won't help as that's for reverting local changes. If you want to undo and roll back your changes from r12345 then the magic SVN runes are:
svn merge -c -12345 .

Then you can review and then commit those changes (with a suitable commit log message about rolling back or undoing the revision).

The option -c -<#> is equivalent to -m <#>:<#-1>. Notice that there is a dash before the number, without it you would get -m <#-1>:<#>. The lone dot just tells SVN to work on the repository in the current directory.

Further details about the merge command options can be found here.

Tuesday, October 25, 2011

Fixing Samba failing to find canonical path for autofs mounted share locations

Following on from my previous post I was chatting with a friend and they pointed out that I could also make use of preexec to get my desired behaviour.

So I removed the entries for wide links and unix extensions from my smb.conf, allowing them to go back to being the default. I then changed my mythtv share to contain:

[mythtv]
        comment = Myth TV Recordings
        path = /auto/mythtv
        guest ok = Yes
        preexec = ls /auto/mythtv

This then solves the issue of Samba not allowing the share to be opened due to the "canonicalize_connect_path failed for service " error.

Tuesday, September 27, 2011

Sharing an autofs mount point over Samba

Since upgrading to Samba 2:3.5.11~dfsg-1 (or possibly slightly earlier) on my Debian based home server I found that some of the shares were no longer working. I could see them when browsing the network device, it just wouldn't let me access them.

This seemed to only be happening to my Samba shares which were pointing directly at the root of an autofs mount point, which in my case was a mythtvfs mount at /auto/mythtv.

What made this more puzzling was that if I ssh'ed into the machine then I could happily do

ls /auto/mythtv
and see all my files. The final piece of the puzzle fitted into place when I realised that the Samba share would work if the mount was already mounted.

A look at the samba logs indicated the following:
smbd/service.c:988(make_connection_snum)
  canonicalize_connect_path failed for service mythtv, path /auto/mythtv

On a hunch I tried the wide links option (which requires disabling unix extensions) by adding the following to the global section of my /etc/samba/smb.conf:
[global]

# Need to disable unix extensions and allow wide links to allow /auto to be mounted
unix extensions = no
wide links = yes
And then restarted samba with "/etc/init.d/samba restart". This then fixed the issue, allowing my autofs mount points to be mounted correctly. The big downside of this is that unix extensions which allow symlinks and hard links over samba are then disabled. If I get the time I might look into seeing if I can patch canonicalize_connect_path to work correctly with autofs mount points without exposing any security flaws.

Possibly the most irritating thing about this issue was that searching for the terms "Samba" and "autofs" gives lots of hits for the other side of the situation; using autofs to mount Samba shares automatically.

Friday, June 17, 2011

Tearing screen even with VSyncing on NVIDIA ION

I've got a home media machine which I to watch MythTV and various online video streaming services. It's been annoying me for a while (possibly since I updated to Ubuntu 11.04) that there was tearing on the screen. It looked exactly like it wasn't vsyncing correctly, but I had vsyncing enabled in all the players I was trying.

The machine I'm using is an Acer Revo with NVIDIA ION chipset, so it isn't the most powerful system. Searching the internet for 'tearing' turned up results which were mostly about people not being able to play 720p or 1080p videos. However that certainly wasn't my issue as I'd done all of the following:

  • Giving the graphics card 512MB of RAM (called UMA in the BIOS setting).
  • Enabling VDPAU acceleration.
  • Disabling the compiz window manager (selecting "Ubuntu classic (no effects)" as the session).
  • Setting export __GL_SYNC_TO_VBLANK=1 and ignoring issues with vsync occurring for the wrong display.
  • Checking the refresh rate was correctly setup with nvidia-settings utility.
  • Updating to the latest NVIDIA drivers

But none of this helped. I then realised that all rendering to the screen was suffering from this, not just video playback. I wondered if the ION couldn't handle the memory bandwidth, but turning down the resolution didn't help. I then thought that maybe it was my TV being a bit broken with HDMI, but testing that would require finding a VGA cable or moving a monitor downstairs, so I didn't try that.

I even got to the point of thinking about installing Windows XP to see if it had the same issue and, if it didn't, giving up on Ubuntu. However after one last search I discovered a post on the XBMC forum. It contained the wisdom of adding the following to /etc/X11/xorg.conf:
Section "Extensions"
    Option         "Composite" "Disable"
EndSection

So I went ahead and did that, restarted X and all tearing was gone. I don't know where the bug is in the system, but I'm just glad of the ability in Linux to control things like this.

Monday, May 16, 2011

MythTV not going fullscreen in Ubuntu 11.04 (Natty Narwhal)

Recently I started upgrading my various MythTV front-end machines to Ubuntu 11.04. I was disappointed to discover that the unity bar at the top of the screen is still there.

In previous version of Ubuntu this would happen if you had the Appearance setting on anything other than basic (I forget exactly what it was called, but it was the first option in the last tab in the Appearance settings application).

However in 11.04 the Appearance settings application no longer has this options (this appears to be due to 11.04 using the Compiz window manage if it's available).

This is apparently a well known issue, but luckily the fix is fairly simple. From here I discovered that it's just a case of installing the advanced appearance settings application (called CCSM) and selecting Utility->Workaround->Legacy Fullscreen Support.

Quite what this workaround breaks and therefore why it isn't on by default isn't mentioned anywhere, but I'm happy for now as I can still watch TV.

Saturday, April 23, 2011

Updated Twitter Fixer

I've updated the twitter fixer user script so that now it doesn't cause some twitter information to be impossible to view. Previously if you clicked on a tweet or a twitter user to get further details then the box which contained the further details would be hidden on the right side of the screen.

This new version fixes that issue by presenting it to you in (almost) full screen, in the middle of your display.

If anyone sees any other issues then please let me know via a comment.

Wednesday, March 16, 2011

Twitter Column Expander

A friend mentioned to me that they were annoyed with the way the new Twitter layout wasted lots of pixels to the left and the right of the timeline. So I knocked together a quick user script for Google Chrome to do this.

I've had this sitting around for a while, but I've finally got around to setting up somewhere where I can put it.

Newspaper Spin Javascript

Looking for any excuse to play around with javascript I've written a newspaper spinning effect file which makes pages spin towards you like in the movies.

You can get it to happen on any site by saving the following link as a bookmark (or dragging it to your bookmark bar) and clicking on it:
Newspaper Spin This!

Turns out it's incredibly easy to do the transformations on the body element in HTML. It's just a case of setting the appropriate style value to the desired rotation amount.

Monday, January 31, 2011

User-scripts in Google Chrome aren't GreaseMonkey scripts

This weekend I was playing around with writing a GreaseMonkey script to force the new Twitter layout to take up the full screen width for the list of tweets.

What I expected to be a 5 minute job turned into an hour and a half. The main issue was that it turns out I wasn't writing a GreaseMonkey script. While the user-scripts in Google Chrome are very similar to GreaseMonkey scripts, they differ in how they handle security (as well as some other more minor differences such as no @require). Eventually I found a helpful page on the Chromiumn wiki explaining the differences.

For me the biggest difference was the absence of unsafeWindow. The easiest way I found to workaround this limitation (which is just a sensible security protect) was to inject the javascript to execute into the document.

The resulting code isn't pretty and is a little harder to debug, but it works and I now don't have large areas of blank screen space when using Twitter.

MythTV and network mounts

After setting up a MythTv 0.24 frontend to use a samba share for files from the backend I discovered that I could no longer watch live TV on it. If I tried to watch live TV there would just be a pause and then a "Error opening jump program file buffer" error message. Looking in the output on stdout wasn't much more helpful, with "Error: Took more than 10 seconds to be allowed to read, aborting" being about the only meaningful message.

It took me ages to track down that the problem is with cached IO on the network share. If the CIFS file system is caching the inode information (which includes the size attributes), then the MythTv frontend thinks that no live TV is being streamed and gives up after a while.

The solution to this is to add the 'directio' option when mounting the network partition (e.g. '-o directio' on the command line). If it's an NFS share then an alternative is to use 'forcedirectio' in the /etc/exports on the server (which is useful if you don't want to change all your MythTv frontends).

Friday, January 28, 2011

Upgrading MythTV 0.23 to 0.24 on Ubuntu

I recently upgraded MythTV 0.23 to 0.24 on both my backend (Debian testing) and the various front ends I use (Ubuntu with Mythbuntu auto-builds/MythTV-Updates).

Everything went smoothly until I tried to watch some TV or recordings from within the frontends. The video would playback at about half speed and with no audio.

After a while I managed to figure out that the problem was caused by using the default audio device. To fix this just update the audio device (in the frontend settings) to point to your actual audio device.

Saturday, January 22, 2011

Getting dual tuner KWorld U399 USB DVB-T working on linux 2.6.37

I recently upgraded the kernel version on my MythTV. One side affect of this was that the second tuner for my DVB-T USB stick (an af9015 based KWorld U399) no longer existed in /dev/dvb. In previous versions of the af9015 module it was just a case of explicitly enabling it with a module parameter of dual_mode=1 and possibly suffering some reception issues when both tuners are enabled.

To get the second tuner working it's necessary to use the very latest firmware for the device. So download the firmware file from here and place it in /lib/firmware. From a quick look at the source code for af9015 it looks like the driver now checks a value in the EEPROM to see if dual mode is safe or not. I assume the clever developer for the af9015 driver has worked out that this is what determines if there will be reception issues with both tuners enabled and that the 5.1.0.0 firmware updates this EEPROM in a suitable way.

You'll need to unplug your USB stick and replug it in to get it to use the new firmware, but you should then get two DVB tuners.

Thursday, September 16, 2010

Accidentally installing Grub to /dev/sda on a Mac OS X machine

I managed to accidentally install GRUB to /dev/sda when setting up my MacBookPro to boot Ubuntu, WinXP and Mac OS X. I knew I shouldn't have, but I wasn't paying attention to the installer when it asked me. In my defence I was also slightly rushed as I wanted to get the installation running before I went to the pub...

Anyway after much hunting and not being able to boot Linux or Windows XP, I finally discovered the solution in this blog post. The author had, like me, managed to ignore all the warnings. Luckily recovery is just a simple case of sticking in the Mac OS X install CD, booting off it and running "fdisk -u /dev/rdisk0" in terminal. This will then restore the Mac OS X MBR to it's proper state.

I did get a warning about not being able to find an MBR file, but it still let me update the MBR and it all seems to be working anyway. As well as fixing Linux and Windows XP booting (which previously would just sit there with a blinking cursor in the top left) it also fixed the slightly annoying issue of rEFIT having a 'Boot Linux from HD' option which I couldn't get rid of.

Tuesday, August 24, 2010

Packing is Hard

Recently there has been some talk about a computer science problem and a, possible, proof that P doesn't equal NP. The proof of if P and NP are the same is one which I think that every computer science student must have a vague suspicion that they could prove when they first hear about it in their computational complexity course. Perhaps as a consequence of this, undergrads are told that they're not going to work it out as "lots of very clever people have tried to show it and failed".

Good for one week of backpacking?

As an aside, the work around showing P and NP being different or the same is a great example of the scientific method at it's best: all the experts generally agree that P isn't the same as NP, but that doesn't stop them from going through any proof which concurs with that belief with a fine-tooth comb. There is a such a clear separation of believe and the need for formal proof that there's a $1 million dollar prize available for a proof that shows P is the same as or different to NP.

What's In My Bag - a Photo of the contents of a backpack, including spade and bottle of alcohol

Given that few of us are likely to win that prize, why should everyday people care about if P is the same as NP. The simple answer is that it is applicable to many everyday problems, such as packing a bag. NP stands for 'nondeterministic polynomial time' which is a very complex way of saying that, when given a solution to an NP problem, you can easily show it is a correct solution to the problem. In the case of packing a bag this is as simple as seeing that they've fitted all the items into the bag.

A problem which is 'P' is a 'polynomial time problem', which is to say that finding a solution from scratch is as easy to find as showing that a solution is correct to an NP problem. So if it was to be shown that P problems are not the same as NP problems then it would confirm that it really is sometimes easier to solve a problem when you've got the solution.

On the other hand, showing that P isn't the same as NP doesn't help practical everyday computing. The vast majority of polynomial time problems still take too long to solve with current computing technology, so all a proof would show is that there are very very hard problems as well as very hard problems. Most importantly, showing P isn't the same as NP certainly won't stop your word processor crashing when you've forgotten to save for 10 minutes.

Sunday, May 23, 2010

Last.fm on Ubuntu Lucid Lynx (10.04)

Having recently got a nice shiny new netbook (an HP/Compaq 311c) I was trying to get last.fm to compile on it. My netbook was running a reasonably fresh install of Ubuntu Lucid Lynx (10.04).

So I downloaded the source for last.fm-1.4.2.58240 and unzipped it into my source directory. Knowing that it needed qt4 I then ran:
sudo apt-get install libqt4-dev

With that all installed I tried running ./configure in the source directory and it said everything was fine, so I went ahead and typed make.

After waiting while it compiled I was then greeted by the following error:
make[1]: Entering directory `/home/marvin/src/last.fm-1.4.2.58240/src/libFingerprint/fplib/pro_qmake'
g++ -c -pipe -O2 -w -fPIC -DNBREAKPAD -DLINUX -DNDEBUG -I/usr/share/qt4/mkspecs/linux-g++ -I. -I../../../../src -I../../../../build -I../../../libMoose -I../../../libUnicorn -I../include -I../src -I../../libs/fftw/src/api -I../../../../res/libsamplerate -o ../../../../build/fplib/release/FingerprintExtractor.o ../src/FingerprintExtractor.cpp
../src/FingerprintExtractor.cpp: In member function ‘bool fingerprint::FingerprintExtractor::process(const short int*, size_t, bool)’:
../src/FingerprintExtractor.cpp:445: error: ‘memcpy’ was not declared in this scope
make[1]: *** [../../../../build/fplib/release/FingerprintExtractor.o] Error 1
make[1]: Leaving directory `/home/marvin/src/last.fm-1.4.2.58240/src/libFingerprint/fplib/pro_qmake'
make: *** [sub-src-libFingerprint-fplib-pro_qmake-fplib-pro-make_default-ordered] Error 2
marvin@Anjie:~/src/last.fm-1.4.2.58240$


Knowing that memcpy is part of the standard C library I thought this seemed a little strange. So I opened up last.fm-1.4.2.58240/src/libFingerprint/fplib/src/FingerprintExtractor.cpp and added the following line in bold:
#include <cmath>
#include <string.h>

Then recompiled.

The next error was the following:
g++ -c -pipe -O2 -w -fPIC -DNBREAKPAD -DLINUX -DNDEBUG -I/usr/share/qt4/mkspecs/linux-g++ -I. -I../../../../src -I../../../../build -I../../../libMoose -I../../../libUnicorn -I../include -I../src -I../../libs/fftw/src/api -I../../../../res/libsamplerate -o ../../../../build/fplib/release/OptFFT.o ../src/OptFFT.cpp
../src/OptFFT.cpp: In constructor ‘fingerprint::OptFFT::OptFFT(size_t)’:
../src/OptFFT.cpp:262: error: ‘exit’ was not declared in this scope
make[1]: *** [../../../../build/fplib/release/OptFFT.o] Error 1
make[1]: Leaving directory `/home/marvin/src/last.fm-1.4.2.58240/src/libFingerprint/fplib/pro_qmake'
make: *** [sub-src-libFingerprint-fplib-pro_qmake-fplib-pro-make_default-ordered] Error 2
marvin@Anjie:~/src/last.fm-1.4.2.58240$


Which I fixed by editing last.fm-1.4.2.58240/src/libFingerprint/fplib/src/OptFFT.cpp to include the line in bold:
#include <iostream>
#include <memory.h> // for memcopy
#include <stdlib.h>

And then once again ran make.

The next error was:
g++ -c -pipe -O2 -w -D_REENTRANT -fPIC -DNBREAKPAD -DLINUX -DQT_NO_DEBUG -DQT_SQL_LIB -DQT_XML_LIB -DQT_GUI_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtNetwork -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtXml -I/usr/include/qt4/QtSql -I/usr/include/qt4 -I../../src -I../../build -I../libMoose -I../libUnicorn -Ifplib/include -I../src/ -I../../res/mad -I../../build/LastFmFingerprint/release -o ../../build/LastFmFingerprint/release/MP3_Source_Qt.o MP3_Source_Qt.cpp
MP3_Source_Qt.cpp: In function ‘short int f2s(mad_fixed_t)’:
MP3_Source_Qt.cpp:70: error: ‘SHRT_MAX’ was not declared in this scope
MP3_Source_Qt.cpp:72: error: ‘SHRT_MAX’ was not declared in this scope
MP3_Source_Qt.cpp: In member function ‘virtual void MP3_Source::skipSilence(double)’:
MP3_Source_Qt.cpp:379: error: ‘abs’ was not declared in this scope
MP3_Source_Qt.cpp:385: error: ‘abs’ was not declared in this scope
make[1]: *** [../../build/LastFmFingerprint/release/MP3_Source_Qt.o] Error 1
make[1]: Leaving directory `/home/marvin/src/last.fm-1.4.2.58240/src/libFingerprint'
make: *** [sub-src-libFingerprint-make_default-ordered] Error 2


So I opened last.fm-1.4.2.58240/src/libFingerprint/MP3_Source_Qt.cpp and added the lines in bold:
#include <cassert>
#include <stdexcept>
#include <stdlib.h>
#include <limits.h>


And ran make once more.

This time it was a linking error:
g++ -Wl,-O1 -shared -Wl,-soname,libLastFmFingerprint.so.1 -o libLastFmFingerprint.so.1.0.0 ../../build/LastFmFingerprint/release/Sha256File.o ../../build/LastFmFingerprint/release/Sha256.o ../../build/LastFmFingerprint/release/MP3_Source_Qt.o ../../build/LastFmFingerprint/release/Fingerprinter2.o ../../build/LastFmFingerprint/release/FingerprintCollector.o ../../build/LastFmFingerprint/release/FingerprintQueryer.o ../../build/LastFmFingerprint/release/moc_Fingerprinter2.o ../../build/LastFmFingerprint/release/moc_FingerprintCollector.o ../../build/LastFmFingerprint/release/moc_FingerprintQueryer.o -L/home/marvin/src/last.fm-1.4.2.58240/bin -L/home/marvin/src/last.fm-1.4.2.58240/build/LastFmFingerprint/../fplib -L/usr/lib -lMoose -L/home/marvin/src/last.fm-1.4.2.58240/bin -lLastFmTools /home/marvin/src/last.fm-1.4.2.58240/build/fplib/libfplib.a -lsamplerate -lfftw3f -lQtSql -lQtXml -lQtGui -lQtNetwork -lQtCore -lpthread
/usr/bin/ld: cannot find -lsamplerate
collect2: ld returned 1 exit status
make[1]: *** [../../bin/libLastFmFingerprint.so.1.0.0] Error 1
make[1]: Leaving directory `/home/marvin/src/last.fm-1.4.2.58240/src/libFingerprint'
make: *** [sub-src-libFingerprint-make_default-ordered] Error 2
marvin@Anjie:~/src/last.fm-1.4.2.58240$


So I ran sudo apt-get install libsamplerate0 libsamplerate0-dev libfftw3-dev libfftw3-3 libmad0-dev libmad0 libgpod-dev libgpod4 libasound2-dev and then ran make again.

If you're wondering how I came up with all the libraries above, it was just from running make several times and then using apt-cache search to search for the missing libraries. I didn't include these steps as they're a bit tedious.

Having done all that it's possible to run last.fm with bin/last.fm.sh.

Thursday, March 04, 2010

Not all equals are born equal

The relationship between two things is something that we learn early in life. It's quite an important thing to know about, especially for understanding the world we live in.

However the question of 'are these the same' or 'are these equal' is surprisingly tricky. It might immediately seem rather obvious, but in actual fact there is a surprising amount of complex mathematics to do with equality and how you define it. As it turns out there are quite a few ways of saying that things are the same, leading to a description of all the different ways of comparing things being called an Equivalence relationship.

Equivalence relationships have three key properties:

  • Reflexive - That everything is equal to itself.
  • Symmetric - That if object A is equal to thing B then thing B must be equal to object A.
  • Transitive - That if A equals B and B equals C then A must equal C.
All of which might seem rather obvious, but mathematicians like to flip-flop between stating the massively obvious and the painfully complex.

For example consider the following:

Maisy
=
Maisy
Quite clearly, for most sensible definitions of equality these will be the same; mostly due to them being identical.

Where it starts to get tricky is if there is some variation between the two things being compared. Initially the answer to this might appear to be "no, they aren't equal", but consider the following:

Maisy
=
Maisy
If you took a poll of people to ask if these two were equal you'd probably come up with the following options in some proportion:
  • Yes, it's the same image.
  • Yes, apart from one is a bit distorted.
  • No, they look different.
All of which are acceptable answers, it just depends on how you define equality. The first answer assumes the comparison is about the contents of the image rather than how it's presented. The second answer is the middle ground, acknowledging that the images are the same but that there is a different in how they a presented. The final answer is the other extreme, the pictures aren't the same so they're not equal.

This all ties in very deeply with one of the foundations of computer science; the distinction between comparing the concept represented by some data and the data itself. A clearer example of the distinction here would be to use two pictures where the idea of equality is even more fuzzy.

Maisy
=
Maisy

As before the answer to if these two are equal is yes and also no. If the question being asked is "are these the same cat?" then the answer is yes; if the question is instead "are these photos the same?" then the answer is no. Usually it's obvious which of these questions is being asked from the context and generally the question is phrased in the more explicit way.

Computers are no different. Ever since Ada Lovelace realised that numbers could be used to represent ideas, concepts and physical objects there has been the need to distinguish between the two types of equality. It's necessary to explicitly tell the computer if you're asking if the numbers are the same (asking if the photos are the same for the above example) or asking if the thing the numbers represent are the same (asking if it's the same cat).

This distinction between the values and what the values are meant to represent occurs frequently in computer languages. For example in the Java language the operator '==' is used to compare the number representing the object, where as the 'equals()' method is used to compare the concept/item that the object represents.

Some languages complicate this further, such as JavaScript where there is the '==' equality operator and the '===' strict equality operator. The need for this arises because when JavaScript first came into existence the '==' operator was defined in such a way that the number 5 was equal to a sequence of text which is the character 5. This is a little confusing, but for various reasons computers choose to represent the character/digit of 5 as the number 53.

This distinction between a character/digit of 5 and the number 5 (which you get from adding 2 and 3) might seem a little strange, but consider the phrase "I ate 5 strawberries". It's necessary for there to be some way to represent each character/letter as a number and the method of representation that has become standard has the digit 5 represented by the number 53.

Coming back to the difference between '==' and '===', the former will say that "5" is equal to 5, where as the latter will say that they are not equal (due to the internal representation being different). This can be a little confusing when first coming to JavaScript and is the main reason for writing this post. I discovered the difference and thought I should share.

So the next time you're trying to work out if two things are the same, just remember to think what you are wanting to compare.

Creative Commons License
The words and photos on this webpage which are created by Toby Gray are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.0 England & Wales License.