#!/usr/bin/python
#
# Complete dodgy hack to work around skew value bug in master-rt
# 
# Synopsis of the problem:
#
# When using the 7i77-ISOL between a 5i25/6i25 and 7i77, propagation
# delay is introduced by the isolator.  No worries, we can adjust for
# it by setting the encoder skew.
#
# The problem is that setting this value initially in the HAL is not
# effective, as it is immediately overwritten.  A little sleuthing
# around showed that there is at least one other place where it gets
# trashed, and that is during homing.  Rather than chance it, this
# component diligently keeps resetting it if it changes.  Hopefully
# this little hack will be null and void within moments of me posting
# it because the actual bugs will be addressed.
#
# Known affected versions:  	1.2.8.0-pre1.3493.ge1f42bf and earlier
# First introduced in version:  Unknown
# Resolved in version:		TBD
#
# Use:
# 
# In HAL, Add the following:
# 
# loadusr -W skewy
# setp skewy.configuredskew [SKEWY]7i77-ISOL_SKEW
# net skewy7i77 <=>  hm2_5i25.0.encoder.muxed-skew skewy.actualskew
#
# In INI, Add the following section :
# [SKEWY]
# 7i77-ISOL_SKEW = {YOUR SKEW VALUE}
#
#
# Note that the configured skew value only gets set in increments of 30,
# however, its not a normal modulus, as setting the value to something
# like 120 doesn't actually result in 120.  You have to actually be over
# the modulus increment in order for it to set, hence the little bit of
# screwball math.
#
#

import hal, time
h = hal.component("skewy")
h.newpin("configuredskew", hal.HAL_U32, hal.HAL_IN)
h.newpin("actualskew", hal.HAL_U32, hal.HAL_IO)
h.ready()

try:
    while 1:
        time.sleep(0.001)

	if h['configuredskew'] < 1:
	    skewvalue = 0
        else:
	    skewvalue = (( h['configuredskew'] -1 ) // 30 ) * 30
        
        if h['actualskew'] != skewvalue:
 	    h['actualskew'] = h['configuredskew']

except KeyboardInterrupt:
    raise SystemExit

