TUTORIAL: Part 1
I have been trying to set up a mobile music player intended to use in connection with my car stereos for the last few days. It was a quite painful process. Finally, I have managed to sort out almost 90% of the problems and tested today for the first time. I will try to describe it here if somebody wants to try it. A word of caution – if you don't have enough patience, do not even think about it.
Aim
Setting up a wireless music player using the Raspberry Pi and the car stereos.
- The Raspi should boot up using the car's 12V/2A cigarette lighter and a double 2A usb adapter
- The Raspi coud be run headless (or with a 7 inch monitor) and controlled by a mobile phone or tablet as a remote
- In addition to streaming from the various mobile devices, it should stream music as well from the attached USB storage device
- A mobile phone (iOs or android) could be used for various purposes such as a:
1) REMOTE (for ssh or VNC connection) or a
2) CLIENT (A client for MPD server utilising MPoD for iphone or MPDroid for android) or a
2) MUSIC HOST (live spotify, shoutcast, youtube or any music player for iphone – streaming to Raspi via Air Play) or a
3) HOT SPOT for an internet connection
Basic scenario
The Raspi boots when the engine is started. It scans for the availability of a WIFI offered by a mobile phone HOTSPOT (like iphone) using a cron job every minute. If this is available (or later becomes available), it connects automatically. If not, then as a fallback it creates itself an access point, so other clients could connect and control it.
Problems occured so far
There are plenty ready-made options for raspberry Pi in order to play music and video. When you are at home and connected to network with monitor, keyboard / mouse, everything is straight forward and there are various options available. Within a car, you are limited with scarce resources. The easiest option is to use a XBMC-based distro. The problem, however, at the time of this writing, was that the XBMC did not offer ALSA driver so you are stucked with a horrible on-board analog sound with annoying clicks and poor quality sound output. In addition, their network managers are very limited – you cannot do anything fancy with those distros concerning the WIFI. I have tried all of the possible options (raspbmc, xbian, openelec) and gave up due to the problems / drops in a mobile wifi-environment. Finally I was ready to settle down with Airplay using the USB-sound card, however, then I could not use the attached music storage of the Raspi any more. Then accidentally I found the MPD and this related site (many thanks to the developer). Eventually I gave up the XBMC entirely and sticked to the MPD, which I think is superb. It is light, fast and solid. The situation might change in future when XBMC distros will come with ALSA driver (check for the audio engine and ALSA news in the Raspbmc distro). In addition, I like to have a "proper" debian distro, on top of which you could add / remove anything you want. Well, almost anything.
I had serious problems with HOSTAPD when using the raspi as an AP (access point) and Air Play and streaming from a client (e.g spotify). The connection dropped every other second. In addition, the scanning for available mobile networks when the hostapd was running proved impossible, since it sits over the wlan interface and does not allow any scanning unless you turn it off. When you turn it off, you loose the connection (well obviously) and your music is interrupted – which was not acceptable. The answer to this was to use another usb wifi dongle (well another 10-15€ spent) and dedicate this only to the wpa-supplicant cli, which does not interfere with the wlan adapter and scanning became possible. Therefore, I use here the HOSTAPD only on WLAN0 interface, which creates an AP when needed, and the WLAN1 interface for scanning / monitoring purposes and connecting as a client to another hotspot (e.g iPhone) when this becomes available.
You need
1. Main Raspi Unit
2. 2-port USB lighter adapter (5V/2A)
3. A powered USB-hub
4. Y-cable for double USB power and data-connection
5. Wifi USB dongles (2 pieces – get one with AP functions)
6. USB sound card
7. A small USB memory stick (e.g. 16 or 32GB) for music storage
(8. A 7" monitor – only for cosmetic reasons and if you want to see what is going on)
PS: I will try to write a STEP-by-STEP guide later and publish it here, however, first I need to check if I could use any styling (bold, code, links, etc) and attachments (for the wifi script) in the post. Otherwise it will be very painful to read and follow.
Coming soon… (hopefully).
Edit: Corrected a few typo errors.
Part 2
STEP by STEP GUIDE
INSTALL RASPBIAN (a debian wheezy distro for Raspberry PI)
Raspbian
Installer
Note: Follow the instructions carefully and test the set-up and make sure everything is running!
#########
INSTALL VNC (for maintanance / update and installing purposes)
I followed this
Note: Autostart VNC (more about this here: http://myraspberrypiexperience…..p-vnc.html) at each boot. If you don't want a graphical VNC connection, you can omit this step and use the SSH command line instead.
#########
ADJUSTMENTS & TWEAKS REQUIRED AT THIS STAGE
- Turn-off "blank monitor" property: If this is not done, your monitor will go blank for power saving purposes. We are running a 5W system on 4-wheels, so we are not worried about this at all. Let's turn the monitor on for ever (well, as long as you have the ignition on)
sudo nano /etc/kbd/config and enter the following values:
BLANK_TIME=0
POWERDOWN_TIME=0
Some body has claimed that this did not work. Therefore, in addition, I used this as well:
sudo nano /etc/lightdm/lightdm.conf
Look for [SeatDefault] and insert:
xserver-command=X -s 0 dpms
- Sound output via the USB sound card / DAC
Note: The analog onboard sound is bad and the output is weak. I did not try the digital HDMI-sound, since a DAC needed here as well to get the audio via 3.5mm aux plug for the car stereos. If any body has tested this, would love to hear the results, as well. Once again, we are in a car, so probably we do not have a digital sound input port for the car stereo. At home, probably, I would go with HDMI-sound and by-pass it via my stereo amplifier which has a decent DAC.
First install alsa-util and plug-ins if not already installed
sudo apt-get alsa-util alsa-plugins
Check if your usb sound card is recognised by the system and note the card and the device number – write it down.
aplay -l
Your hardware will be presented in the list. Note down the numbers. Mine reads:
card 0: Device [C-Media USB Audio Device], device 0: USB Audio [USB Audio]
card 1: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
So, the USB-sound device is "hw:0,0" and the onboard analog device "hw:1,0"
Now change the default output from snd-bcm2835 to your sound card using the alsamixer
alsamixer
Make this the default sound device after a reboot.
sudo nano /etc/modprobe.d/alsa-base.conf
Comment-out the following line from "options snd-usb-audio index=-2" to:
#options snd-usb-audio index=-2
Next, modify the following file in order to use the USB-sound instead of analog output (this file will be disabled when you start using MPD later – but at this stage it is still needed)
sudo nano /etc/.asound.conf
Comment out all what is there and ADD to the end the following:
pcm.!default {
type plug
slave {
pcm "hw:0,0"
rate 48000
}
}
ctl.!default {
type hw
card 0
}
- Auto login to DESKTOP (use raspi-config and change the setting)
- Enable SSH (use raspi-config and change the setting)
#########
CREATING an AP
I have used this excellent TUTORIAL
Note: There is a bug which turns the wlan interface off when the HOSTAPD is on. This is not important and there is no need to correct if you will be using the scenario and the attached script here. We will be manually putting the wlan interface UP and DOWN.
Add my WIFI Script (I need to attach this or publish as a separate post later: wifi.sh) to your home directory and start it at BOOT with adding a line (/path/to/your/script.sh &) to the file sudo nano /etc/rc.local. Then add a crontab job in order to run this script every minute:
sudo crontab -e
Add the following line:
* * * * * sudo /home/pi/wifi.sh > /home/pi/wifilog.txt
Create a log file at your home directory named wifilog.txt to which the output of the crontab job will be written every time when it is run
cd /home/pi
sudo touch /home/pi/wifilog.txt
*if you want to run it more seldom you can change the first "*" to "*/2", 2 minutes or "*/5" min etc.
As an alternative – if you will not be using internet connection – you can create an Ad hoc network instead. I tried this
TUTORIAL
Note: I could get the Raspi connected as a client and everything worked fine when a mobile phone's HOTSPOT used. However, in a ad-hoc environment, I could get the SSID name advertised, but could not manage to make a proper connection or uniterrupted streaming using this.
#########
AIR PI / SHAREPORT (with iOs 6 hack)
Use this this TUTORIAL – everything needed is there including the iOs 6 hack!
#########
Check / test / check and make sure that everything is running as intended. Make proper adjustments, ask questions, do some google-search and make sure the first part of the project is over and you are able to STREAM from your phone to the RASPI using Air Play. Now we need to be able to stream from RASPI and connected USB STORAGE. For that we need the MPD and that is why you came here at the first place, right?
#########
INSTALL MPD OVER Raspberry PI
Go back to the first page and do some reading there
Once you managed to get the MPD streaming, download MPoD for iphone or MPDroid for android or Genome Music Player or ARIO for your Raspi, get the VNC connection and play your music via your car's stereos to which the raspi is connected using a 3.5mm plug.
#########
TO – DO LIST
So far I am very happy with this setting and everything is sorted out automatically (almost). Now I want to have a nice full-window banner showing the "Now Playing" INFO with song & artist name, duration, number of the track and the album cover on the server-side. This should be displayed on the attached 7" display. I have been reading and doing some testing. So far, I could only get an info buble with basic information. However, I could not get the album cover displayed yet. In additon, the present banner is very small and located at the upper right corner of the monitor. Any suggestions are very welcome. Then the project will be finally ready.
Part 3: The Wifi Script
The following is the "wifi.sh" script mentioned before. The script is heavily modified from 2-3 earlier scripts and all credits go to these original writers. I have just made some additions and modifications. Copy the code between the lines as a text file named "wifi.sh". Make it executable (chmod +x /path/to/wifi.sh). Add it to your /etc/rc.local file and run a crontab job as described in the previous post. Any suggestions to clean the code or make it shorter is very welcome. This is the one which I have managed to work without interruptions, though. I am very novice when it comes to linux, so please keep that in mind when going through the code.
The SSID for your AP is already defined when you have built your AP using HOSTAPD. Here you need to know the SSID of the mobile hotspot (read = your mobile phone or tablet) you will be using in your car. You need to find out the IP of your gateway (in my iPhone it is 172.20.10.1) and the IP which Raspi gets from the gateway's DHCP (mine was 172.20.10.2).
What the script does? It first checks if the Raspi has assigned an IP. If not, it scans for the hotspot created by your phone and connects to it. If the assigned IP starts with "17", it pings the gateway and if the result is a success, it quits. If your mobile phone is not available, it starts HOSTAPD and creates the AP you have defined earlier. After a minute the second wlan interface scans once again for the gateway and if it is found, then the HOSTAPD is turned off and a new IP obtained using the WPA_SUPPLICANT.
Good luck.
######################################################################################
#!/bin/bash
######################################################################################
# Modified from the original scripts by
# A Project of TNET Services, Inc
# Title: WiFi_Check
# Author: Kevin Reed (Dweeber)
# Project: Raspberry Pi Stuff
# Copyright: Copyright (c) 2012 Kevin Reed
# https://github.com/dweeber/WiFi_Check
#
# Lasse Christiansen Development
# Connect to WiFi or Create An Encrypted DHCP Enabled Ad-hoc Network as Fallback
# http://lcdev.dk
#
# Severly modified & combined & rewritten by A T / 2013. All credits go to the
# original writers mentioned above
######################################################################################
# S E T T I N G S – MAKE THE CHANGES HERE!
######################################################################################
lockfile='/var/run/WiFi_Check.pid' # Location of the Lockfile
wlanAP='wlan0' # WLAN Interface for the dedicated access point (AP)
wlan='wlan1' # WLAN Interface for scanning and connecting to a hotspot
host1='10.0.0.1' #IP of Raspi when it functions as an AP
client1='172.20.10.2' #IP of Raspi as a client of a mobile hotspot
# You must define the client1 IP value above by checking it when Raspi is connected
# to the hotspot offered by your mobile phone (host2)
host2='172.20.10.1' #IP of the mobile hotspot. You must define the host2 IP from your
# mobile phones DHCP, ie. this is your mobile phones IP when it shares its internet
# connection with the clients eg. Raspi
ssids=( 'nameofyourphonesnetwork' ) #ESSID of the mobile network of your phone
NetworkUp=`/sbin/ifconfig $wlanAP`
hostapd=`pidof hostapd`
######################################################################################
# NO NEED TO MAKE CHANGES BELOW! (EXCEPT IP NUMBER 17 MARKED BELOW)
######################################################################################
echo
echo "Starting WiFi check for $wlan"
date
echo
if [ -e $lockfile ]; then
pid=`cat $lockfile`
if kill -0 &>1 > /dev/null $pid; then
echo "Process still running, Lockfile valid"
exit 1
else
echo "Old lockfile, Removing Lockfile"
rm $lockfile
fi
fi
echo "Setting Lockfile"
echo $$ > $lockfile
######################################################################################
# Create own dedicated AP if mobile hotspot is not available
######################################################################################
createAPNetwork(){
echo "Performing Network check for $wlanAP"
echo "Do we have an IP?"
MyIP=$(ifconfig $wlanAP | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
MyIPs=$(echo "${MyIP}" | sed 's/\(.\{2\}\).*/\1/')
echo "AP IP = $MyIP ($MyIPs)"
if [ "$MyIPs" = "" ]; then
echo "We don't have an IP, trying to get one now"
service hostapd start
service dnsmasq start
ifconfig $wlanAP $host1 up
elif [[ $NetworkUp =~ "$host1" ]]; then
echo "IP is $host1 – hostapd is running"
echo "pid of hostapd is $hostapd"
else
echo "interface is unknown"
fi
}
######################################################################################
# Check if an IP is assigned then exit or attempt a new connection to mobile HOTSPOT
######################################################################################
echo "Performing Network check for $wlan"
echo "Do we have an IP?"
MyIP=$(ifconfig $wlan | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
MyIPs=$(echo "${MyIP}" | sed 's/\(.\{2\}\).*/\1/')
echo "IP of the client is $MyIP ($MyIPs)"
if [ "$MyIPs" = "" ]; then
echo "================================="
echo "RPi Network Conf Bootstrapper 0.1"
echo "================================="
echo "Scanning for known WiFi networks"
connected=false
for ssid in "${ssids[@]}"
do
if iwlist $wlan scan | grep $ssid > /dev/null
then
echo "First WiFi in range has SSID:" $ssid
sudo service hostapd stop
echo "Stopped AP mode"
sudo ifconfig $wlanAP down
sudo ifconfig $wlan down
echo "Starting now supplicant for WPA/WPA2 in client mode"
wpa_supplicant -B -i $wlan -c /etc/wpa_supplicant/wpa_supplicant.conf > /dev/null 2>&1
echo "Obtaining IP from the gateway using DHCP"
sudo ifconfig $wlan $client1 up
connected=true
echo "Connected to WiFi"
break
else
echo "Not in range, WiFi with SSID:" $ssid
createAPNetwork
break
fi
done
elif [ "$MyIPs" = "17" ]; then
### CHANGE No 17 ABOVE TO WHATEVER FIRST TWO DIGITS OF YOUR IP OBTAINED FROM YOUR PHONE!!!!
for ssid in "${ssids[@]}"
do
if iwlist $wlan scan | grep $ssid > /dev/null 2>&1
then
echo "Pinging for mobile HOTSPOT – please wait"
ping -c 3 -t 1 -I $wlan $host2 > /dev/null 2>&1
if [ "$?" -eq 0 ]; then
echo "Already connected to your phone, quitting now…"
sudo service hostapd stop
sudo ifconfig $wlanAP down
break
else
echo "iPhone is available, but does not respond to pinging – we will try after 1 minute"
break
fi
else
echo "iPhone hotspot is not around, going for AP"
createAPNetwork
exit 0
fi
done
else
echo "IP is $MyIP"
fi
######################################################################################
# Job is done, write out new IP and quit
######################################################################################
echo
echo "Current Setting: AP"
ifconfig $wlanAP | grep "inet addr:"
echo
echo "Current Setting: Client"
ifconfig $wlan | grep "inet addr:"
echo
# Check is complete, Remove Lock file and exit
rm $lockfile
exit 0
######################################################################################
# End of Script
######################################################################################
________________________
Hi aht961, good luck with your project.
Just a couple of notes -
I've been running the audio through the on-board analogue for a couple of days now and there's no clicks and the sound is actually quite good. It might be to do with the clock speed that the pi is running at.
I've tried to use internet streaming audio while travelling for a couple of years now around the UK and the 3G/2G reception is so poor on the move that I have given up and now rely on stored audio on the device. i say this as you might spend a lot of time getting mobile internet working only to find that you've wasted your time.
Have fun and report back how it's going.
Probably you are right with regard to the live streaming. However, in Finland, particularly in urban areas the LTE/3G is quite ok and makes the problem a little bit more bearable. On the other hand, when I used the Raspi as a client in order to stream music form the attached storage, my phone lost the connection now and then, when I had to reboot again. Therefore, I thought an AP or ad-hoc could solve the problem. With that scenario, I lost the chance to use the live streams, though. Therefore went back to the first set up. At the end, I made a compromise and added another wifi-dongle to have a backup for the both options. If you ask, is it worthwhile for the time wasted – nobe, I do not believe it is – if you don't do this for fun. At the end of the day, you could forget all of this including the Raspi and wire your phone directly to your stereos
http://www.raspyfi.com/wp-cont…..-laugh.gif
Yes, i do sometimes wonder if the pi is a solution looking for a problem. There are a number of things that I've seen pi do that could have been done just as well with a piece of wire!
A few notes with regard to the WIFI SETTINGS
Probably you have done this already, but if you have not yet, you should check these files:
1. Add your mobile phone's SSID and PSK-keys to sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="yourwifiNAME"
psk="yourwifiPASSKEY"
}
2. Make changes to your network interfaces so WLAN could be managed manually:
sudo nano /etc/network/interfaces
It should look like this
auto lo wlan0
iface lo inet loopback
allow-hotplug wlan0
iface wlan0 inet manual
allow-hotplug wlan1
iface wlan1 inet manual
This is a huge piece of work!!!
If you don't mind I'll place a link on this tutorial on frontpage! Well worth it, if you want to take some pictures of it…
I can also start a projects category, and yours will be the first project on it… What you say?
admin said
This is a huge piece of work!!!
If you don't mind I'll place a link on this tutorial on frontpage! Well worth it, if you want to take some pictures of it…
I can also start a projects category, and yours will be the first project on it… What you say?
Thanks. I do not mind – you are the boss here
12:32
Hello aht961,
Thanks for this great post! It will help me to put my car music streamer together.
Personally I will do away with the hotspot functionality. I live in Belgium and my streamer will mostly be used during holidays outside belgium where I do not use 3G because of the roaming charges.
Could you please explain the following in more detail:
- if I count correctly you have 4 usb devices. How do you connect them? I assume you use a powered usb hub? Is that why you need the 2-port lighter adapter? I have been thinking about building a power supply myself using the instructions from Issue 6 of the MagPi. In that case I would need two probably. The reason for building one myself is to make sure to get the best audio quality from the Pi.
- does your installation support ALAC? If not, can you suggest how to get that working? In any case, I will try this weekend.
Thanks again!
guussie said
- if I count correctly you have 4 usb devices. How do you connect them? I assume you use a powered usb hub? Is that why you need the 2-port lighter adapter? I have been thinking about building a power supply myself using the instructions from Issue 6 of the MagPi.
You are very welcome. That is why I have a Y-splitter (was meant initially for my external usb HDD attached to my laptop). 2-port 5V/2A USB adapter is attached to a single lighter port. One feeds directly PI as usual using the micro-USB. The other port is attached to the powered hub using the POWER end of the USB Y-splitter cable. The other end (host) of the splitter goes to the powered hub and the other USB DATA cable to the backport of the PI. This Y-cable powers also the PI using the back port (so if I did not have so many adapters, I could go with this alone). One of the USB wifi dongles could draw 500mA and the other 450mA. So, this 500mA unit is attached to the second USB port of the PI. The sound card (200mA), 32GB usb stick (150mA) and the other wifi card are all attached to the hub. Check your devices power consumption typing usb-devices Since you don't need the other wifi dongle, just stick the one you have to PI and both the sound card and the memory stick to the hub.
- does your installation support ALAC? If not, can you suggest how to get that working? In any case, I will try this weekend.
All of my rips are using Apple lossless, so there should not be any issue there.
Good luck – let us know of the progress.
Aht
Part 4: A SCRIPT FOR NOTIFICATION & ALBUM COVER ART RETRIEVAL
aht961 said
TO – DO LISTSo far I am very happy with this setting and everything is sorted out automatically (almost). Now I want to have a nice full-window banner showing the "Now Playing" INFO with song & artist name, duration, number of the track and the album cover on the server-side. This should be displayed on the attached 7" display. I have been reading and doing some testing. So far, I could only get an info buble with basic information. However, I could not get the album cover displayed yet. In additon, the present banner is very small and located at the upper right corner of the monitor. Any suggestions are very welcome. Then the project will be finally ready.
I am referring to my post above. This was the missing part of the project. Now I have found a nice solution, which is quite nice, however, requires further improvements. I will describe the process in the following for those who are willing to try it.
The basics are straight forward. When MPD plays a song, a notification bubble with an album cover, song and related info is displayed on the upper right corner for a 5 seconds. If a cover could not be found in the default folder, a query is made to http://www.albumart.org and if a match is found it is downloaded in the default directory. The script uses for displaying the notification (notify-osd).
We need these:
mpc #Required (Command line MPD client: probably you already have)
Notify-OSD#Required (check if you have it already installed)
libnotify-bin #Required (not very sure about this, since I have installed this earlier)
ImageMagick #Optional
Ario #Optional (if you want to download cover art)
Lets install these
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install packagename
Substitute package name with: mpc notify-osd libnotify-bin imagemagick ario
I have been looking for a ready solution and tested a few options. Only with a 3 year old script by pbrisbin and KittyKat I have managed to have the notification displayed but with no album cover. There were few typo mistakes and changes in the URL and I have changed them. Before running the script, first install the packages above and TEST if notification is functioning.
notify-send "Hello World"
You should see this at your display's upper right corner. If you don't see, you should try to sort this out before you proceed with the following. I was using a VNC connection and could not see anything. I had to define my display before the notify-send command.
For VNC connection it was DISPLAY=:1 and for the primary attached monitor DISPLAY=:0.0
Try both and check which one works for you. So, first you export the display then the command
export DISPLAY=:1; notify-send "hello" or
export DISPLAY=:0.0; notify-send "hello"
You see it on the monitor – great, now you are ready to proceed.
A. CREATE THE NOTIFICATION SCRIPT
Copy the code below and save it as mpdnotify at your home directory /home/pi
###########################################################################
#!/bin/bash
###########################################################################
# pbrisbin 2010
# http://pbrisbin.com:8080/bin/bashnotify
# modify the config after it's written!
#
# modified by KittyKatt (http://www.silverirc.com/kittykatt/) 2010
#
# modified and few bugs corrected by AT aht Tekay @ 2013
###########################################################################
### utilities {{{
message() { echo 'usage: mpdnotify [start|stop|restart]'; exit 1; }
logger() { echo "$(date +'[ %d %b %Y %H:%M ]') :: $*" | tee -a "$log"; }
errorout() { logger "error: $*"; exit 1; }
# }}}
### write config file {{{
write_config() {
if [ ! -f "$config" ]; then
logger "NOTE: writing example config to $config…"
logger "you should edit this file before starting the deamon"
cat > "$config" << EOF
#!/bin/bash
#
# mpdnotify config – any valid bash is allowed, you
# only need to define handle_event() for the deamon
# to run properly
#
# \$mydir exists, and it's value is $mydir
# Constants
if [ "\$MPD_HOST" ]; then HOST="\$MPD_HOST"; else HOST="localhost"; fi
if [ "\$MPD_PORT" ]; then PORT="\$MPD_PORT"; else PORT="6600"; fi
MPD_TCP="/dev/tcp/\$HOST/\$PORT"
coverDir="\$HOME/.covers" # THE DIR FOR YOUR COVERS
tmpCover="/tmp/cover"
baseCover="\$HOME/extras/base.png" # THE DIR FOR YOUR DEFAULT IMAGES
topCover="\$HOME/extras/top.png" # THE DIR FOR YOUR DEFAULT IMAGES
noCover="\$HOME/extras/NOCOVER.png" # THE DIR FOR YOUR DEFAULT IMAGES
myPID="\$HOME/.config/mpdnotify/pid"
mpdPID=\$(pidof mpd)
mpdArtist="Could not find Artist's name"
mpdTitle="Could not find Song's title"
mpdAlbum="Could not find Album's name"
mpcLength="Could not find Song's length"
mpcInfo="Cound not find Song's info"
showCover="true"
expireTime="5000"
#logout="true"function mpd_sndcommmand() {
# \$1 command
exec 5 \$MPD_TCP 2>/dev/null
[[ \$? -gt 0 ]] && return 1
echo \$1 >&5
echo "close" >&5
tmp=\$(cat &-
_ret=\$(head -n -1 <<< "\$tmp" | tail -n +2)
return 0
}function mpd_getinfo() {
mpd_sndcommmand currentsong
[[ \$? -gt 0 ]] && return 1
_tmp=\$_ret
mpdTitle=\$(grep "^Title: " <</dev/null | sed "s/Title: //")
mpdArtist=\$(grep "^Artist: " <</dev/null | sed "s/Artist: //")
mpdAlbum=\$(grep "^Album: " <</dev/null | sed "s/Album: //")
_songtime=\$(grep "^Time: " <</dev/null | sed "s/Time: //" | cut -f 1 -d
(( _mm=\$_songtime / 60 ))
[[ \${#_mm} -eq 1 ]] && _mm="0\$_mm"
(( _ss=\$_songtime – \$_mm * 60 ))
[[ \${#_ss} -eq 1 ]] && _ss="0\$_ss"
mpdLength="\$_mm:\$_ss"
mpd_sndcommmand "status"
_tmp=\$_ret
mpdSongID=\$(grep "^songid: " <</dev/null | sed "s/songid: //")
mpdPlaylistL=\$(grep "^playlistlength: " <</dev/null | sed "s/playlistlength: //")
}function fetch_cover() {
###################################################################################
# CHANGE THE FOLLOWING LINE TO MATCH YOUR COVER TAG in coverDircoverjpg="\$coverDir/\${mpdArtist}-\${mpdAlbum}.jpg"
# If you have changed this, you should change the URL below as well
###################################################################################
album=\$1
file="\$coverjpg"
if [ ! -f "\$file" ] ; then
logger "\$file is not in covers… " >/dev/null
###################################################################################
# CHANGE THE FOLLOWING IF YOU HAVE CHANGED THE COVER TAG ABOVE OR IF THE URL FOR
# SEARCHING AT albumart.org changesurl="http://www.albumart.org/index.php?skey=\${mpdArtist// /+}-\${mpdAlbum// /+}&itempage=1&newsearch=1&searchindex=Music"
###################################################################################
cover_url=\$(curl -s "\$url" | awk -F 'src=' '/zoom-icon.jpg/ {print \$2}' | cut -d '"' -f 2 | head -n1)
if [ -n "\$cover_url" ]; then
logger "\$file retrieved and placed in covers directory…" >/dev/null
wget -q -O "\$file" "\$cover_url"
else
logger "ERROR: Album cover not found online. Searched for: \${album// /+}" >/dev/null
fi
fi
}handle_event() {
###################################################################################
# CHANGE THE FOLLOWING LINE TO MATCH YOUR COVER TAG in coverDircoverjpg="\$coverDir/\${mpdArtist}-\${mpdAlbum}.jpg"
# NO CHANGES REQUIRED BELOW
###################################################################################
if [[ -z \$mpdPID ]]; then
echo "MPD is not currently running!"
if [[ -f "\$myPID" ]]; then
rm "\$myPID"
fi
exit
else
mpd_getinfo
if [ "\${showCover}" = "true" ]; then
if [ -f "/tmp/cover" ]; then rm /tmp/cover; fi
if [ -f "\$coverjpg" ]; then
cp "\$coverjpg" /tmp/cover
else
fetch_cover "\$mpdAlbum"
if [ -f "\$coverDir/\$mpdAlbum" ]; then
cp "\$coverDir/\$mpdAlbum" /tmp/cover
else
cp "\$noCover" /tmp/cover
fi
fi
mogrify -resize 144x144! \$tmpCover
# convert \$baseCover "\$tmpCover" -geometry +4+3 -composite \$topCover -geometry +0+0 -composite "\$tmpCover"
mpdAlbum=\$(echo "\$mpdAlbum" | sed -e 's/&/&/')
mpdTitle=\$(echo "\$mpdTitle" | sed -e 's/&/&/')
mpdArtist=\$(echo "\$mpdArtist" | sed -e 's/&/&/')
[[ "\${#mpdArtist}" -gt "25" ]] && mpdArtist=\$(echo "\${mpdArtist:0:25}…")
[[ "\${#mpdTitle}" -gt "25" ]] && mpdTitle=\$(echo "\${mpdTitle:0:25}…")
[[ "\${#mpdAlbum}" -gt "25" ]] && mpdAlbum=\$(echo "\${mpdAlbum:0:25}…")
notify-send --expire-time="\${expireTime}" -i "\${tmpCover}" "$(echo "${mpdTitle}")" "\$(echo "By: \${mpdArtist}"; echo "From: \${mpdAlbum}"; echo "Length: \${mpdLength}"; echo "Position: \${mpdSongID} / \${mpdPlaylistL}")"
else
notify-send --expire-time="\${expireTime}" "$(echo "${mpdTitle}")" "\$(echo "By: \${mpdArtist}"; echo "From: \${mpdAlbum}"; echo "Length: \${mpdLength}"; echo "Position: \${mpdSongID} / \${mpdPlaylistL}")"
fi
if [ "\$logout" == "true" ]; then
echo -e "\$mpdTitle \n \$mpdArtist \n \$mpdAlbum \n" > \$HOME/mpdout
fi
fi
}EOF
exit 0
fi
. "$config"
type -p handle_event || errorout 'handle_event() not defined, check your config'
}# }}}
### start/stop deamon {{{
start_daemon() {
[ -f "$pid" ] && errorout "file found at $pid, daemon already running?"# start listening in background
( while read -r; do
handle_event
done < "$pid"
}stop_daemon() {
if [ -f "$pid" ]; then
kill $(cat "$pid") || errorout 'error stopping daemon'rm "$pid"
fi
}# }}}
### constants
if [ "$XDG_CONFIG_HOME" ]; then
mydir="$XDG_CONFIG_HOME/mpdnotify"
else
mydir="$HOME/.config/mpdnotify"
fi
config="$mydir/config"
pid="$mydir/pid"
log="$mydir/log"
pipe="$mydir/pipe"### run it
if [ ! -d "$mydir" ]; then
mkdir -p "$mydir" || errorout "unable to create my dir $mydir"
fiwrite_config
case "$1" in
start) start_daemon ;;
stop) stop_daemon ;;
restart) stop_daemon; sleep 3; start_daemon ;;
status) handle_event ;;
*) message ;;
esac#######################################################################
# E N D O F S C R I P T
#######################################################################
How to run: Install mpdnotify at your home directory and run it as a daemon:
Remember to make it executable first
sudo chmod +x /home/pi/mpdnotify
Then start it:
/home/pi/mpdnotify start
At the first run, you will have the configuration files written at /home/pi/.config/mpdnotify. Adjust the directories in the config file.
You won't be able to see anything yet, since we must add EXPORT DISPLAY commands and get rid of the PID file written from the last session at the next boot. In addition, we want to have this run automatically at each boot. Now we will go through these steps.
B. MAKE A STARTUP SCRIPT AND MAKE IT RUN AFTER YOU HAVE LOGGED TO YOUR LXDE DESKTOP
I have made a script for this. Copy the code below as start_mpdnotify.sh and install it at /home/pi
Adjust the DISPLAY= value if the default does not work.
#################################################################################
#!/bin/bash
######################################################
# By AT aht Tekay @ 2013
# Starting MPD-NOTIFY
######################################################
# SETTINGS
lockfile='/home/pi/.config/mpdnotify/pid'
# Change this to match the dir of your lock file
# You may need to change the DISPLAY number below
######################################################
export DISPLAY=:0.0
if [ -e $lockfile ]; then
pid=`cat $lockfile`
rm $lockfile
export DISPLAY=:0.0
/home/pi/mpdnotify start
exit 1
else
export DISPLAY=:0.0
/home/pi/mpdnotify start
fi
exit 0#############################################################################
# E N D O F S C R I P T
#############################################################################
We need to run this ONLY after the LXDE Desktop session is started. It won't function if you addd it at e.g. /etc/rc.local. Remember this.
Go to /home/pi/.config/autostart, create a .desktop file including the details below.
cd ~/.config/autostart
touch mpdnotify.desktop
using e.g. nano enter the following lines in the mpdnotify.desktop you have just created
nano mpdnotify.desktop
[Desktop Entry]
Type=Application
Name=MPD Notification
Comment=Starts the now playing notification in MPD
Exec=/home/pi/start_mpdnotify.sh
Save. Go to your desktop menu using GUI: > Preferences > Desktop Session Settings. There you will see a NEW shortcut named MPD Notification: Activate. This will run the script after reboot and the initiation of the LXDE session.
We are all setup. REBOOT and start MPD if it is not already running. After each song you will se a nice notification with album cover, name, title, artist, track. etc. In addition, make an image file named NOCOVER.png and put it in /home/pi/extras. This will be showed if the album does not have an image to display. If you have album covers, you put them in your coverDir="$HOME/.covers". If you don't have. Install, ARIO and install covers usng it. Thereafter, copy all images from ARIO's /covers folder to your default .cover folder. Ario tags the cover image as Artist Group Name-Album Name.jpg. If yours is different, then you should obviously make the adjustments in the scripts above.
I think this should be a selectable default option in e.g. RASPYFI
IMPORTANT NOTE – EDIT:
There is a funny smiley in the middle of the code where reads:
_songtime=\$(grep "^Time: " <</dev/null | sed "s/Time: //" | cut -f 1 -d * This does not belong there!!!! Add ":" ")" there where the * is but nothing else. The forum is not very friendly for posting codes or styling
MISSION ACCOMPLISHED – GOOD LUCK
05:15
One option that you could look at to simplify some of this would be to use a 3g/wireless router – like the TPLink wr-703n – (around $25) – this would connect via ethernet to your PI and will auto connect to your home network through Wireless when in range and through 3G when on the road – this would act as your incar Wifi access point so your head end (android etc) could access the PI over this.
You could also use this to access the Pi remotely – leave this powered all the time and use one of the USB TTL lines to wake up the pi remotely – you would then be able to remotely download/sync music to the Pi .
If ultimate audio quality was your goal then put a 2nd Pi in the car to act as a NAS with USB HDD and a small ethernet switch to interconnect everything !
May simplify much of the work you have done – but i like what you have done and will use is as the base of what i intend to build for my car going forward – my plan is as follows
TPlink as Wirelesss Hub/access point and 3G router – this will be permanently mounted to my windscreen for best range
Small 5 port ethernet switch
headless Raspberry pi as MPD player with USB DAC – connected to ethernet switch
2nd pi as NAS with 2.5 inch HDD and ethernet connected to switch
I am still working out the power setup but as i will have an android in the car for some other automation projects may leave the TPlink permanently powered from a small 12v (7.2ah) battery – this would then be able to receive a command through ssh to wake the PI – which would go to the android to enable a relay to turn on power to the Pi.
Rysnc will then run from my music collection in the house and download any updates to the Pi NAS ready for the next time i drive off.
In Australia our 3g is patchy – but my hope is that i can also get spotify working reliably.
Craig
14:57
So can we use a Venice 7 module (or even a DAB+ usb stick in a r-pi car computer a la mp3car.com, yet?
Hey Craig, does your curtin refer to the suburb in the ACT? Or are you just fond of the old PM?
Thank you for your interest in the project. Nice suggestions. I have few comments, though.
craigcurtin said
One option that you could look at to simplify some of this would be to use a 3g/wireless router – like the TPLink wr-703n – (around $25) – this would connect via ethernet to your PI and will auto connect to your home network through Wireless when in range and through 3G when on the road – this would act as your incar Wifi access point so your head end (android etc) could access the PI over this.
The logic behind Pi is to keep the budget at minimum. If you add a 3G router, you need an additional 3G subscription. Taking into account the amount of time you spend in the car, at least to me, sounds not very practical.
The second problem comes with the power for the router. Then you will need probably a 12V/220V inverter.
If ultimate audio quality was your goal then put a 2nd Pi in the car to act as a NAS with USB HDD and a small ethernet switch to interconnect everything !
Why do you think that adding another Pi would improve the audio quality?
TPlink as Wirelesss Hub/access point and 3G router – this will be permanently mounted to my windscreen for best range
Small 5 port ethernet switch headless Raspberry pi as MPD player with USB DAC – connected to ethernet switch 2nd pi as NAS with 2.5 inch HDD and ethernet connected to switch
As I have said, this is doable if you want to dedicate a 3G subscription for your auto-PI. But if I were you and willing to have an internet connection dedicated to PI in the car, then I would go for a 7" touchscreen monitor for PI and forget the mobile phone and remote connection. Then you will have your HDD, USB DAC attached and also could directly connect to spotify if you wanted, The only reason I needed to have this client/AP options was to use the mobile phone for internet connection.
I am still working out the power setup but as i will have an android in the car for some other automation projects may leave the TPlink permanently powered from a small 12v (7.2ah) battery – this would then be able to receive a command through ssh to wake the PI – which would go to the android to enable a relay to turn on power to the Pi.
Very interesting.
Rysnc will then run from my music collection in the house and download any updates to the Pi NAS ready for the next time i drive off.
I do that by just taking the small 32GB USB drive home or bringing the laptop to the car while I am still in the garden
04:33
aht961 said
Thank you for your interest in the project. Nice suggestions. I have few comments, though.
craigcurtin said
One option that you could look at to simplify some of this would be to use a 3g/wireless router – like the TPLink wr-703n – (around $25) – this would connect via ethernet to your PI and will auto connect to your home network through Wireless when in range and through 3G when on the road – this would act as your incar Wifi access point so your head end (android etc) could access the PI over this.The logic behind Pi is to keep the budget at minimum. If you add a 3G router, you need an additional 3G subscription. Taking into account the amount of time you spend in the car, at least to me, sounds not very practical.
The second problem comes with the power for the router. Then you will need probably a 12V/220V inverter.
If ultimate audio quality was your goal then put a 2nd Pi in the car to act as a NAS with USB HDD and a small ethernet switch to interconnect everything !
Why do you think that adding another Pi would improve the audio quality?
TPlink as Wirelesss Hub/access point and 3G router – this will be permanently mounted to my windscreen for best range
Small 5 port ethernet switch headless Raspberry pi as MPD player with USB DAC – connected to ethernet switch 2nd pi as NAS with 2.5 inch HDD and ethernet connected to switchAs I have said, this is doable if you want to dedicate a 3G subscription for your auto-PI. But if I were you and willing to have an internet connection dedicated to PI in the car, then I would go for a 7" touchscreen monitor for PI and forget the mobile phone and remote connection. Then you will have your HDD, USB DAC attached and also could directly connect to spotify if you wanted, The only reason I needed to have this client/AP options was to use the mobile phone for internet connection.
I am still working out the power setup but as i will have an android in the car for some other automation projects may leave the TPlink permanently powered from a small 12v (7.2ah) battery – this would then be able to receive a command through ssh to wake the PI – which would go to the android to enable a relay to turn on power to the Pi.
Very interesting.
Rysnc will then run from my music collection in the house and download any updates to the Pi NAS ready for the next time i drive off.
I do that by just taking the small 32GB USB drive home or bringing the laptop to the car while I am still in the garden
The TPLink router runs on 5V USB so you would just power it from a 12V to USB converter
You are right about the additional data subscription for a Sim for a 3G dongle – however note this is just a 3G/4G dongle that plugs into a USB port on the TPLink router – i currently carry one of these around with me for my laptop connection so it is no additional cost – YMMV – it sounded like it simplified a lot of the issues
My understanding was that there were USB issues on the PI and sharing a high throughput device like a Hard disk and trying to use a DAC on the same USB bus was not thought to be a good idea ?
Craig
04:36
kew1 said
So can we use a Venice 7 module (or even a DAB+ usb stick in a r-pi car computer a la mp3car.com, yet?
Hey Craig, does your curtin refer to the suburb in the ACT? Or are you just fond of the old PM?
Both i guess – he was a distant relative and the suburb is named after him !
Craig
craigcurtin said
The TPLink router runs on 5V USB so you would just power it from a 12V to USB converter
Craig
That sounds superb – unfortunately, seems to be unavailable in Finland. I have looked for such a "mobile" small router to no avail. Now when I realize that such a 5V/USB router is available at market and with that price tag – I definitely would go for it instead of two usb wifi dongles as I have used. This one you can take with you anywhere you go – i.e. no need to leave it in the car if you did not want to.
11:11
aht961 said
craigcurtin said
The TPLink router runs on 5V USB so you would just power it from a 12V to USB converter
CraigThat sounds superb – unfortunately, seems to be unavailable in Finland. I have looked for such a "mobile" small router to no avail. Now when I realize that such a 5V/USB router is available at market and with that price tag – I definitely would go for it instead of two usb wifi dongles as I have used. This one you can take with you anywhere you go – i.e. no need to leave it in the car if you did not want to.
It is available on EBAY for dirt cheap and shipping is no issue – they even preload the latest OpenWrt on it.
I mount mine up in the top corner of my windscreen. When i get in the car i just plug the USB 3G/4G dongle into a hub i have mounted in the car – ready to go !
Craig
Most Users Ever Online: 200
Currently Online:
7 Guest(s)
Currently Browsing this Page:
1 Guest(s)
Top Posters:
Gyp: 82
yoghurtlidlicker: 37
PaulM: 36
icai: 35
Derek: 29
Karsten: 27
tc-fi: 22
Ronaldo: 21
ENSen: 21
chriz: 20
Member Stats:
Guest Posters: 3619
Members: 569
Moderators: 0
Admins: 1
Forum Stats:
Groups: 4
Forums: 10
Topics: 469
Posts: 13163
Newest Members: polo2016, dongdong8, wlpwlp, Sager, ninestab123, lmx66, lmx, jlgg, chenyan, guoyanying
Administrators: admin (401)