#
# virtual switch
#
# Input pins
#	image (iplimage)
#	roi (roi)
#
# Output pins
#	roi (roi)
# 	action_fired (bool)
#

type virtual_switch
name "Virtual Switch"
args -x -y -c

# Camera source. Create a forwarder to export the pin ...
create forward forwardin_image
# and export it as "image"
export_ipin forwardin_image in image iplimage

# ROI input
create forward forwardin_roi
export_ipin forwardin_roi in roi roi

# Camera panel ans its roi
#create roi_storage roi -s 0.05 0.05 -c 0.25 0.5 --color 16711680
create roi_storage roi -s 0.05 0.05 -c $-x$ $-y$ --color $-c$
export_opin roi roi

# Connect external viewer
connect forwardin_roi out roi roi_same_id

#connect roi roi viewer roi
#connect forward out viewer image

# Optical flow tracker and its roi
create optical_flow_tracker oftracker
connect roi roi oftracker roi
connect forwardin_image out oftracker image

#
# Optical flow output processing
#

# Split output for each axis
create split split -o 2
connect oftracker motion split input

# Compute motion modulus
create fmul mul_a
create fmul mul_b

connect split 1 mul_a b
connect split 1 mul_a a

connect split 2 mul_b b
connect split 2 mul_b a

create fadd modulus_adder

connect mul_a result modulus_adder b
connect mul_b result modulus_adder a

create fsqrt modulus
connect modulus_adder result modulus a

# DEBUG SLIDER
create widget_slider sldmotion_detected --min 0 --max 1 -l "Motion detected"
connect modulus result sldmotion_detected value
# DEBUG SLIDER



#
# Threshold slider + checkbox
#
import around_zero_threshold.sps
create around_zero_threshold thres -lsld _"Motion detection threshold" -lchk _"Motion detected" -max 0.3 -v 0.01
connect modulus result thres in

#
# Filter events by time
#
import filter_values_by_time.sps
create filter_values_by_time filter -t 1000
connect thres above filter in
create widget_slider sldtime --min 250 --max 5000 -l "Time (ms)" -v 1000 -i
connect sldtime value filter time



#
# Button to set noise level
#

create widget_button setthres_btn -l "Set threshold"
create forward noise_gate
connect setthres_btn pressed noise_gate gate
connect modulus result noise_gate in

# Condition value: average + scale
create freductor avg_motion -a -r 5
connect noise_gate out avg_motion in
create fmul scale_motion -v 10
connect avg_motion out scale_motion a

connect scale_motion result thres thres

create bcast bcast_motion
connect scale_motion result bcast_motion in
create not not_motion
connect bcast_motion out not_motion a
connect not_motion result noise_gate gate

#
# Time wait after 

# 
# Action fired

export_opin filter out action_fired

begin_gui_layout
	layout_begin vbox
		component setthres_btn
		component sldtime
		
		layout_begin collapsible _"Advanced"
			component sldmotion_detected
			component thres
		layout_end
	layout_end
end_gui_layout
