Let your computer welcome you with music

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/bin/bash
  2. ##### FUNCTIONS #####
  3. log() {
  4. # Beautiful logs
  5. date=`date +"%d/%m/%Y - %H:%M:%S"`
  6. echo "[$date]" $1
  7. }
  8. play_stream() {
  9. # Reset playback state
  10. curl -s -d '{"jsonrpc": "2.0", "id": 1, "method": "core.playback.stop"}' http://localhost:6680/mopidy/rpc > /dev/null
  11. curl -s -d '{"jsonrpc": "2.0", "id": 1, "method": "core.tracklist.clear"}' http://localhost:6680/mopidy/rpc > /dev/null
  12. # Add track infos
  13. stream=$1
  14. log "Playing stream $stream"
  15. data='{"jsonrpc": "2.0", "id": 1, "method": "core.tracklist.add", "params": [ [ { "__model__": "Track", "uri": "STREAM" } ] ] }'
  16. # Using sed cuz simple quotes
  17. data=`echo $data | sed "s,STREAM,${stream},"`
  18. # Play dat sound
  19. curl -s -d "$data" http://localhost:6680/mopidy/rpc > /dev/null
  20. curl -s -d '{"jsonrpc": "2.0", "id": 1, "method": "core.playback.play"}' http://localhost:6680/mopidy/rpc > /dev/null
  21. }
  22. stop_stream() {
  23. # Stop dat sound
  24. curl -s -d '{"jsonrpc": "2.0", "id": 1, "method": "core.playback.stop"}' http://localhost:6680/mopidy/rpc > /dev/null
  25. log "Stream stopped"
  26. }
  27. parse_arg() {
  28. # Echoes the value of a given parameter in a given configuration file
  29. value=$(cat $1 | grep -E "^$2" | cut -d"=" -f2)
  30. value=$(echo $value | sed "s,^\s+,,")
  31. echo $value
  32. }
  33. check_url() {
  34. # Check if URL is starting with "http(s)://"
  35. # Returns the same code as grep, which is 1 if incorrect,
  36. # 0 if correct
  37. echo $1 | grep -E "https?\://"
  38. return $?
  39. }
  40. ##### PROGRAM #####
  41. if [[ $# -eq 0 || ! -f $1 ]]; then
  42. echo "I need a config file as first argument"
  43. exit 1
  44. fi
  45. config_file=$1
  46. log "Parsing the configuration file"
  47. # Get parameters from the given configuration file
  48. stream=$(parse_arg $config_file "stream")
  49. threshold=$(parse_arg $config_file "device_threshold")
  50. address=$(parse_arg $config_file "device_address")
  51. if [ ! $(check_url $stream) ]; then
  52. echo "Incorrect stream address"
  53. exit 1
  54. fi
  55. log "Initialisation complete"
  56. while true; do
  57. # Lock file
  58. lock_file="/etc/welcomehome/home.lck"
  59. count=$(ping -W 1 -c $threshold $address | grep ttl | wc -l)
  60. if [ $count -gt 0 ]; then
  61. # mopidy.lck present = music already playing
  62. if [ ! -f $lock_file ]; then
  63. log "Device detected"
  64. play_stream $stream
  65. touch $lock_file
  66. fi
  67. else
  68. if [ -f $lock_file ]; then
  69. log "Device lost"
  70. stop_stream
  71. rm $lock_file
  72. fi
  73. fi
  74. done