--[[

SCRIPT: SNAP
AUTHOR: Mike Shellim
URL: http://www.rc-soar.com/opentx
DATE: 01 Mar 2018
VERSION: 4.1.0
DESCRIPTION:

Adjustable snapflap mix.

	Snap
	^
	|              xxxxxx
	|            x
	|          x
	|        x
	|      x
	|    x
	|xxxx---------------- elevator stick
	    |         |
	    p1        p2

INPUTS:
	p1 (supplied by external control)
	p2 (supplied by external control)

OUTPUTS:
	Snap -  snapflap value -100 to +100


SCRIPT INSTALLATION
1. Save script with .LUA extension to \SCRIPTS\MIXES on SD Card
2. Open Custom Scripts menu in transmitter
3. Assign script to an empty slot. Note the slot number
4. Open the script, and assign controls for p1 and p2 adjustments
5. Test by moving elevator stick and observing 'snap' value
6. Close Custom Scripts menu

MIXER SETUP
- Create mixer line in high channel, call it 'snap'
	Set source = [n]Snap where n is the script number from (3) above.
	Create a mix line in each flap channel and assign the shap channel as source.
- To adjust snapflap volume, alter weight of the snap mix
-	Or adjust via control (e.g. Thr trim) in a subsequent MULTiply mixer line
- To alter expo, set expo in the snap mix line (ideally, as a GVar linked to a control)
- To alter p1, move assigned control
- To alter p2, move assigned control
- To restrict snapflap to +ve or -ve elevator, specify curve="x<0" or "x>0" in the servo mixes
]]--


local inp =
	{
		{ "p1", SOURCE}, -- p1 value via specified control {-1024 to +1024}
		{ "p2", SOURCE}  -- p2 value
	}
local out = {"Snap"}
local MIN_SEPARATION = 10 -- (stick deflection %)


-- periodically called function

local function run_func(p1, p2)

	local elev_in
	local elev
	local snap = 0

	-- validate inputs. An error returns zero snap.

	if p1 < 0 or p1 > 1024 or p2 < 0 or p2 > 1024 or p1 > (p2 - MIN_SEPARATION*10.24) then
		return 0
	end

	-- get elevator stick value

	elev_in = getValue (MIXSRC_Ele)

	if elev_in < 0 then
		elev = -elev_in
	else
		elev = elev_in
	end

	-- calculate snap value

	if elev >= p2 then
		snap = 1024
	elseif elev <= p1 then
		snap = 0
	else
		snap = 1024 * (elev-p1)/(p2-p1)
	end

	if elev_in < 0 then
		snap = -snap
	end

	return snap
end

return {run=run_func, input=inp, output=out}
