Btplay.current

From Chumby Wiki
Revision as of 20:00, 22 April 2008 by Wayn3w (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

btplay.current is a CGI script that will print out the contents of btplay.properties as XML to make it easier for widgets to grab. In layman's terms, you can get the information about the currently playing music selection from btplay for use in your widgets.

Directions:

  1. Copy and paste this script into /psp/cgi-bin/btplay.current on your chumby
  2. change its permission to be executable by typing : chmod +x /psp/cgi-bin/btplay.current
  3. use the URL http://127.0.0.1/cgi-bin/custom/btplay.current to get the XML.
#!/usr/bin/perl -w

# Prints datum as XML given the tag name and tabstop level.
sub print_datum {
    my $tabstop = shift;
    my $tag = shift;
    my $datum = shift;

    print "\t" x $tabstop, "<", $tag, ">", $datum, "</", $tag, ">\n"; 
}

# prints a complex data structure as XML, where keys of hashes are 
# entity names and leaf nodes are data
sub print_data
{
    my $tabstop = shift;
    my $tag = shift;
    my $data = shift;

    if ( ref($data) eq "SCALAR" ) {
        print_datum( $tabstop, $tag, $$data );
    } elsif ( ref($data) eq "ARRAY" ) {
        for my $datum ( @{$data} ) {
            print_datum( $tabstop, $tag, $datum );
        }
    } elsif ( ref($data) eq "HASH" ) {
        print "\t" x $tabstop, "<", $tag, ">\n";
        for my $key ( reverse keys %{$data} ) {
            print_data( $tabstop+1, $key, $data->{$key} );
        }
        print "\t" x $tabstop, "</", $tag, ">\n"; 
    } else {
        print_datum( $tabstop, $tag, $data );
    }
}

#  Build up a hash of hashes:
#  name1/name2=data1 turns into
#  name1/name2=data2
#     turns into
#  $hash{name1}{name2} = [ data1, data2 ];
#
#  This version allows any number of names on a line
#
sub build_data {
    my $filename = shift;
    my $hash = shift;

    open FILE, $filename or die "Cannot open $filename: $!";
    while(<FILE>) {
        chomp;
        my ( $names, $data ) = split /=/;
        my @names = split/\//, $names;

        my $current_hash = $hash;
        my $last = pop( @names );
        foreach my $name ( @names ) {
            if ( !exists $current_hash->{ $name } )  {
                $current_hash->{ $name } = {};
            }
            $current_hash = $current_hash->{ $name };
        }
        push @{$current_hash->{ $last }}, $data;
    }
    close FILE;
}
 
my %hash;
my $filename = "/var/run/btplay.properties";

print "Content-type: text/xml\n\n";
print "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
build_data($filename, \%hash);
print_data(0 , "song", \%hash);

1;