#!/bin/bash
# GPIO triggered video player

#Copyright (C) 2024 Andy D'Arcy Jewell, Chris Godbert and MakerPunkBuzz
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Requires vlc installed to run
# To autosatrt, add "/home/thedoctor/player.sh" to the end of .bashrc
# This version designed for Raspberry Pi OS "bullseye"

clear

# Map GPIO numbers to videos
declare -A vids
#vids["(GPIO number)]="/path/to/video.mp4"
vids["2"]="/home/thedoctor/Vids/vortex 1.mp4"
vids["3"]="/home/thedoctor/Vids/vortex 2.mp4"
vids["4"]="/home/thedoctor/Vids/vortex 3.mp4"
vids["17"]="/home/thedoctor/Vids/vortex 4.mp4"
vids["27"]="/home/thedoctor/Vids/vortex 5.mp4"
vids["22"]="/home/thedoctor/Vids/readout 1.mp4"
vids["10"]="/home/thedoctor/Vids/readout 1s.mp4"
vids["9"]="/home/thedoctor/Vids/readout 2.mp4"
#vids["11"]="/home/thedoctor/Vids/filename.mp4"

# Automatically play first video so we don't start with blank screen
# To select video to play, use the GPIO pin number from above vids 
# associative array. You can add your own videos there.
# For example, "${vids['9']}" means "/home/thedoctor/Vids/readout 2.mp4"
cvlc --no-video-title-show "${vids['9']}" > /dev/null 2>&1 &
# Set all our GPIOs to PULLUP
for gpio in ${!vids[@]}; do
	raspi-gpio set $gpio pu
done
while true; do
	#find any playing video
	vid=`ps aux|grep -o "/home/thedoctor/Vids/.*\.mp4"|head -n1`
	#loop through gpios checking if any are low = activated
        for gpio in ${!vids[@]}; do
		#get the file name of this video
                thisvid=${vids["$gpio"]}
		#read  state of  gpio pin (level =0)
		if [[ `raspi-gpio get $gpio|grep -o "level=."` == "level=0" ]]; then
			#is currently playing video different from the one  requested
			if [[ "$vid" != "$thisvid" ]]; then
				#force the  current video to end
				killall /usr/bin/vlc
				#play the requested video
				cvlc --no-video-title-show "$thisvid"  > /dev/null 2>&1 &
				sleep 1
			fi
		fi
	done

done

