I was actually researching the same problem today and found a solution to the remote switching issue.
Apple Keyboard Emulator to switch remotely switch Target Display Mode of an iMac without a physically connected keyboard
Problem
What you need
Step 1:
Download and install the Arduino IDE (I did this with version 1.8.12)
Step 2:
Modify the Arduino Leonardo board description in /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/boards.txt
in the Arduino IDE app package to include the necessary USB descriptor to match the following:
leonardo.name=Arduino Leonardo
leonardo.vid.0=0x2341
leonardo.pid.0=0x0036
leonardo.vid.1=0x2341
leonardo.pid.1=0x8036
leonardo.vid.2=0x2A03
leonardo.pid.2=0x0036
leonardo.vid.3=0x2A03
leonardo.pid.3=0x8036
leonardo.upload.tool=avrdude
leonardo.upload.protocol=avr109
leonardo.upload.maximum_size=28672
leonardo.upload.maximum_data_size=2560
leonardo.upload.speed=57600
leonardo.upload.disable_flushing=true
leonardo.upload.use_1200bps_touch=true
leonardo.upload.wait_for_upload_port=true
leonardo.bootloader.tool=avrdude
leonardo.bootloader.low_fuses=0xff
leonardo.bootloader.high_fuses=0xd8
leonardo.bootloader.extended_fuses=0xcb
leonardo.bootloader.file=caterina/Caterina-Leonardo.hex
leonardo.bootloader.unlock_bits=0x3F
leonardo.bootloader.lock_bits=0x2F
leonardo.build.mcu=atmega32u4
leonardo.build.f_cpu=16000000L
leonardo.build.vid=0x05ac
leonardo.build.pid=0x0221
leonardo.build.usb_product="Apple Keyboard"
leonardo.build.usb_manufacturer="Apple Computer, Inc."
leonardo.build.board=AVR_LEONARDO
leonardo.build.core=arduino
leonardo.build.variant=leonardo
leonardo.build.extra_flags={build.usb_flags}
Step 3:
Start/restart the Arduino IDE, open an example sketch for the keyboard library (I used the Keyboard Message Send
example). Plug in the Arduino Leonardo compatible board and upload the sketch. Plug the Arduino into the iMac to be used in Target Display Mode
Step 4:
Create a script (here I named it switchTDM.sh
) to send the CMD+F2
keyboard command telling the iMac to switch in or out of Target Display Mode. Put this script in the user directory (/users/<USERNAME>
).
#!/bin/sh
# switchTDM.sh script
osascript -e 'tell application "System Events" to key code 144 using command down'
echo 'Sent TDM switch signal.'
Modify the script to be executable:
chmod +x switchTDM.sh
Step 5:
Enable SSH access to the TDM iMac by enabling "Remote Login" in the sharing options of the System Preferences. And test whether you can login from a remote machine using:
ssh <USERNAME>:<PASSWORD>@<IP or hostname of iMac>
Step 6:
Bind the call to the remote script to a keyboard shortcut. I use BetterTouchTool: Add a new keyboard shortcut and execute the following terminal command:
ssh <USERNAME>:<PASSWORD>@<IP or hostname of iMac> ~/switchTDM.sh
That's it
Use your defined keyboard shortcut to switch your iMac in and out of Target Display Mode.