I have it working. It's not very generic at the moment though.
1) Add 5400 to the end of the .var file, this means that the tool-in-spindle is saved when LinuxCNC exits.
2) Make this Python file executable, and "loadusr" early in the HAL file sequence.
Code:
#! /usr/bin/env python
import sys
import linuxcnc
import re
import time
s = linuxcnc.stat()
c = linuxcnc.command()
s.poll()
#inifile = linuxcnc.ini(sys.argv[1])
varfile = "sim_mm.var" #inifile.find("RS274NGC", "PARAMETER_FILE")
old_tool = 0
for line in open(varfile, "r"):
M = re.search("^5400\s([\.\d]*)", line)
if M: old_tool = re.search("^5400\s([\.\d]*)", line).group(1)
def ok_for_mdi():
s.poll()
return (not s.estop) and s.enabled and s.homed == (1,1,1,0,0,0,0,0,0) and s.interp_state == linuxcnc.INTERP_IDLE
while not ok_for_mdi():
time.sleep(0.5)
print "trying to set tool to %s" % old_tool
c.mode(linuxcnc.MODE_MDI)
c.wait_complete()
c.mdi("M61 Q%s" % old_tool)
Note that I have not figured out how to read the .var file name from the INI, so that needs to be hard-coded. Also it only works for a 3-joint machine. Change that by editing the (1,1,1,0,0,0,0,0,0) bit of the code that is testing for all axes to be homed.