Maybe there's more than one way to do this but the method I know is described here:
Extending LinuxCNC. Basically you need to remap an existing or unused code to accomplish your goal. The TRICK HERE is that you can define a Python routine to do your bidding. While in Python you have access to all the variables you desire with the one caveat that you don't know what their names are. Maybe someone else knows what they are but I just nose around until I find what I'm looking for.
Anyway, once you understand this method the world is yours. You can call either a Python or o-word function. You can use the Python prolog & epilog functions to save/restore settings and/or set named parameters for use in an o-word call.
For example, in Python, if I want to know the GUI setting for the Spindle Type and provide a name parameter for it I would do this:
self.params["_spindle"] = int(self.redis.hget('machine_prefs', 'spindle_type'))
where
SPINDLE_TYPE_STANDARD = 0
SPINDLE_TYPE_SPEEDER = 1
SPINDLE_TYPE_HISPEED = 2
In your case you could write a routine as a complete new function to accomplish your goal, or have it stuff all the info you want into some parameter locations for use by your G-code.