A solution I use involves a 3d print server. I have defined shell scripts that address the GPIO ports of the Raspberry Pi that runs OctoPrint. OctoPrint is a 3d print server that can be accessed over your home network.
From the OctoPrint homepage:
OctoPrint is the snappy web interface for your 3D printer that allows
you to control and monitor all aspects of your printer and print jobs,
right from your browser.
This print server application allows for specification of custom Gcode commands (linked to system commands for instance; note this is a plug-in called "GCODE Systems Commands", see image below).
As an example, e.g. OCTO100 is scheduled to run fan_on.sh shell script. This script in its turn drives a relay to switch the annoying extruder cooling fan that is always on when the printer is powered. These codes can then be used throughout your sliced file to do stuff you want (e.g. by using the TweakAtZ plugin of Cura). E.g. my extruder fan will stay on several minutes before it is scheduled off after a successful print through OCTO110 which in itself runs the script fan_off.sh.

The scripts from the figure could be setup to schedule to do something, e.g. fan_on.sh controls a relay using port 22 of the GPIO of the Raspberry PI:
#!/bin/bash
gpio export 22 out
gpio -g write 22 0
So to disable the fan you would need fan_off.sh to be:
#!/bin/bash
gpio export 22 out
gpio -g write 22 1