0

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

Isabelle
  • 41
  • 1
  • 7

1 Answers1

3

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.

Gerge
  • 93
  • 6
  • 2
    You can use systemd path unit. Check this article [Using systemd Path Units to Monitor Files and Directories - Putorius](https://www.putorius.net/systemd-path-units.html). I think what you ask are separate questions. You should create new questions. – Constantin Hong Jan 17 '23 at 08:26
  • If you are concerned about the load, I can assure you that bash scripts don't use much of the CPU. You can check the load of all running processes with the `top` command (it may not even show up because it is so little). As for the other things you are asking, they are a completely different topic, so as Constantin suggested just post a different Q. If you want you can also play with the `sleep` time and set it to a larger value, depending on how long you are willing to wait for a new joystick to be detected by the script. – Gerge Jan 17 '23 at 20:36
  • that is a nice solution and it works good. Thanks – Isabelle Jan 19 '23 at 13:40