Bash script that detect when a joypad is plugged in and retrive its ID_MODEL in a variable, then execute commands

102 views Asked by At

I want to detect with a bash script when a joypad is plugged in and retrive the ID_MODEL of the controller in a variable.

So the script should remain silently listening as long as it is plugged in a joypad (no hdd or other peripherals) and then it must execute some commands.

Even after the joypad in plugged, the script should continue listening if other joypads are plugged in and then it should execute the same commands as before with the new joypad.

I only can detect the joystick already plugged in with:

#!/bin/bash
 
# Get the name and id of the joystick
name=$(udevadm info --query=all --name=/dev/input/js0 | grep ID_MODEL= | awk -F= '{print $2}')

# Print the name and id of the joystick
echo "Joystick detected: Name=$name"

But i'm stuck at beginning of the script: I don't know how to make it stays listening if a joypad is inserted.

Im using Raspbian GNU/Linux 10 (buster)

Thanks

1

There are 1 answers

3
Gerge On

something like this should work:

#!/bin/bash
listofknownjoysticks=()
while [ 1 ]; do
  #get list of joysticks connected
  joysticks=($(ls /dev/input | grep js))
  for joystick in "$joysticks"; do #loop to check all joysticks in the list individually
    echo -n 'checking' $joystick
    if [[ "${listofknownjoysticks[@]}" =~ "$joystick" ]]; then  #if already included
      echo ' already connected'
    else
      # Get the name and id of the joystick
      name=$(udevadm info --query=all --name=/dev/input/$joystick | grep ID_MODEL= | awk -F= '{print $2}')
      # Print the name and id of the joystick
      echo " Joystick detected: Name=$name"
    fi
  done
  listofknownjoysticks=(${joysticks[@]}) #set the known joysticks to the currently connected ones
  sleep 2 #wait 2 seconds to not cause too much workload
done

I will leave the rest up to you. Have fun with the Pi.